Exemple #1
0
class App:
    def __init__(self):
        self._model = Model()
        self._gui = Gui(self._model)
        self._ip = ImageProcessing(self._model)
        self._tf_session = None

    def set_coco_data(self, graph_definitions_file, class_labels_file):
        self._model.load_coco_data(graph_definitions_file, class_labels_file)

    def set_capture_input(self, filename_or_hardware_id, camera_type: Camera):
        self._model.set_capture_input(filename_or_hardware_id, camera_type)

    def run(self):
        self._tf_session = tf.Session()

        # Restore session
        self._tf_session.graph.as_default()
        tf.import_graph_def(self._model.graph_definitions, name='')

        self._ip.create_capture()
        self._gui.create_ui_elements()
        self.loop()

        self._ip.stop()
        self._gui.stop()

    def loop(self):
        while True:

            # read the next camera frame
            img_input = self._ip.get_next_frame()
            if img_input is None:
                break

            # setup tensorflow parameters
            num = self._tf_session.graph.get_tensor_by_name('num_detections:0')
            scores = self._tf_session.graph.get_tensor_by_name(
                'detection_scores:0')
            boxes = self._tf_session.graph.get_tensor_by_name(
                'detection_boxes:0')
            classes = self._tf_session.graph.get_tensor_by_name(
                'detection_classes:0')
            feed_dict = {
                'image_tensor:0':
                img_input.reshape(1, img_input.shape[0], img_input.shape[1], 3)
            }
            # Run the tensorflow/coco model
            tf_result = self._tf_session.run([num, scores, boxes, classes],
                                             feed_dict)

            # draw the tf results into the output image and display it
            img_output = self._ip.render_detection(tf_result)
            cancel = not self._gui.show_image(img_output)

            if cancel:
                break

    def __is_ready(self):
        return True
Exemple #2
0
    def __init__(self):
        self._app = QtWidgets.QApplication(sys.argv)
        self._model = Model()
        self._view = View()

        self.add_thread = AddThread()
        self.timer_thread = TimerThread()
        self.init()
def sample(args):

    import tensorflow as tf
    from app.model import Model
    from tensorflow.python import pywrap_tensorflow

    #reset everything not to raise variables exist/not exist error (crazy!)
    tf.reset_default_graph()

    with open(os.path.join(args.save_dir, 'config.pkl'), 'rb') as f:
        saved_args = joblib.load(f)
    with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'rb') as f:
        chars, vocab = joblib.load(f)
    #Use most frequent char if no prime is given
    if args.prime == '':
        args.prime = chars[0]
    model = Model(saved_args, training=False)
    with tf.Session() as sess:

        def get_tensors_in_checkpoint_file(file_name,
                                           all_tensors=True,
                                           tensor_name=None):
            varlist = []
            var_value = []
            reader = pywrap_tensorflow.NewCheckpointReader(file_name)
            if all_tensors:
                var_to_shape_map = reader.get_variable_to_shape_map()
                for key in sorted(var_to_shape_map):
                    varlist.append(key)
                    # print("checkpoint_var: ", key)
                    var_value.append(reader.get_tensor(key))
                # print(40 * '-')
            else:
                varlist.append(tensor_name)
                var_value.append(reader.get_tensor(tensor_name))
            return (varlist, var_value)

        def build_tensors_in_checkpoint_file(loaded_tensors):
            full_var_list = list()
            for i, tensor_name in enumerate(loaded_tensors[0]):
                try:

                    tensor_aux = tf.get_default_graph().get_tensor_by_name(
                        tensor_name + ":0")
                except:
                    print('Not found: ' + tensor_name)
                full_var_list.append(tensor_aux)
            return full_var_list

        CHECKPOINT_NAME = ('app/models/char_rnn/model.ckpt-1119')
        restored_vars = get_tensors_in_checkpoint_file(
            file_name=CHECKPOINT_NAME)
        tensors_to_load = build_tensors_in_checkpoint_file(restored_vars)
        saver = tf.train.Saver(tensors_to_load)
        saver.restore(sess, CHECKPOINT_NAME)

        return (model.sample(sess, chars, vocab, args.n, args.prime,
                             args.sample).encode('utf-8'))
def main():
    arguments = sys.argv[1:]
    options = parse_arguments(arguments)
    config = load_config(options.config)
    environment = get_environment(config.environment_type, config.environment)
    policy = get_policy(config.policy_type, config.policy, environment)
    model = Model(config.model, environment, policy)
    model.load(config.save_model)
    test(model, environment, config)
Exemple #5
0
def predict():
    with db.app.app_context():
        model = Model()
        articles = Article.query.all()
        for a in articles:
            if a.score < 0:
                score = model.predict(a)
                a.score = score
        db.session.commit()
Exemple #6
0
class Controller:
    def __init__(self):
        super().__init__()
        self.model = Model()

    def login(self, data):
        return self.model.login(data)

    def registerUser(self, data):
        return self.model.registerUser(data)
Exemple #7
0
    def __init__(self, directory, master=None):
        Tk.Frame.__init__(self, master)
        self.master.title('MP3 Player')
        self.master.resizable(0, 0)

        self.model = Model(directory)

        self.init_mixer()

        self.main_frame = MainFrame(self)
        self.artwork = Artwork(self, self.main_frame.main_frame)
        self.seekbar = Seekbar(self, self.main_frame.main_frame)
        self.text_frame = TextFrame(self, self.main_frame.main_frame)
        self.buttons = Buttons(self, self.main_frame.main_frame)
        self.listbox = ScrollListBox(self, self.main_frame.main_frame)
        self.volume_window = VolumeWindow(self)
Exemple #8
0
def main():
    arguments = sys.argv[1:]
    options = parse_arguments(arguments)
    config = load_config(options.config)
    environment = get_environment(config.environment_type, config.environment)
    policy = get_policy(config.policy_type, config.policy, environment)
    replay_buffer = ReplayBuffer(config.batch_size, config.max_buffer_size,
                                 environment.observation_size,
                                 environment.action_size)
    model = Model(config.model, environment, policy)
    writer = SummaryWriter(log_dir='runs/' + options.name)
    train(model, replay_buffer, environment, config, writer)

    # save trained model
    if config.save_model is not None:
        os.makedirs(config.save_model, exist_ok=True)
        model.save(config.save_model)
Exemple #9
0
def retrain_model():
    try:
        print("Rentrenando Modelo")
        model = Model()
        joblib.dump(model, "./model.joblib")
    except Exception as e:
        print("Can't save model")
    return {"results" : "The model was retraining and successfully saved"}
    def __init__(self, models_cfg):
        self._models = {}
        self._default_model_name = models_cfg[0]['model']
        self._G = nx.DiGraph()
        for cfg in models_cfg:
            if not isinstance(cfg['source'], list) or not isinstance(
                    cfg['target'], list):
                log.error("Error in config source and target must be lists")
                import sys
                sys.exit(1)
            model = Model.create(cfg)
            if model.model in self._models:
                log.error("Model names should be unique")
                import sys
                sys.exit(1)
            self._models[model.model] = model
            if cfg.get('default'):
                _default_model_name = cfg['model']

            if cfg.get('include_in_graph', True):
                flip_src_tgt = cfg.get('target_to_source', False)
                for src_lang in cfg['source']:
                    for tgt_lang in cfg['target']:
                        # This will keep only the last model
                        self._G.add_edge(src_lang, tgt_lang, cfg=model)
                        if flip_src_tgt:
                            self._G.add_edge(tgt_lang, src_lang, cfg=model)

        # There may be more than one shortest path between source and target; this returns only one
        self._shortest_path = nx.shortest_path(self._G)
        _directions = []
        self._src_tgt = {}
        self._tgt_src = {}
        for item in self._shortest_path.items():
            u = item[0]
            for v in item[1].keys():
                if u != v:
                    display = '{}->{}'.format(to_name(u), to_name(v))
                    _directions.append((u, v, display))
                    targets = get_or_create(self._src_tgt, u)
                    targets.append(v)
                    sources = get_or_create(self._tgt_src, v)
                    sources.append(u)
        self._directions = sorted(_directions, key=lambda x: x[2])
Exemple #11
0
 def handle(self, source):
     doc_count = 0
     try:
         with open(source) as file:
             reader = csv.DictReader(file)
             for row in reader:
                 model = Model()
                 model.name = (row['name']).lower()
                 model.popularity = row['popularity']
                 try:
                     model.save()
                     doc_count += 1
                 except NotUniqueError as e:
                     logger.error(e)
                     continue
     except Exception as e:
         logger.error(e)
     logger.info('{} models imported'.format(doc_count))
Exemple #12
0
 def __init__(self):
     super().__init__()
     self.model = Model()
all error handling and command execution is handled. 
"""


def get_script_path():
    return os.path.dirname(os.path.realpath(sys.argv[0]))


if __name__ == "__main__":

    # Sets up the database if it hasn't been set up yet.
    #directory = sys.argv[1:][0]
    #os.chdir(directory)
    path = get_script_path() + '/app/'
    conn = sqlite3.connect(path + "pomodorros.db")
    model = Model(conn)
    try:
        # First time using app
        model.initialize_tables()
        print("Successfully intialized PomodorrosCLI!")

    except sqlite3.OperationalError:
        # Subsequent uses of app
        settings = model.get_settings()
        task_log = model.get_task_log(settings)
        pomodorro_log = model.get_pomodorro_log(settings, task_log)

        # RecurrenceManager manages updating for the recurring pomodorros
        recurrence_manager = RecurrenceManager(pomodorro_log, task_log, model)
        recurrence_manager.update_pomodorros()
Exemple #14
0
	def post(self, name):
		try:
			#get the current user
			user = g.user
			inputs = request.get_json()
			parser = reqparse.RequestParser()
			#if response type is html, then return result as html file
			#otherwise return json
			parser.add_argument('response_type', type=str, location='args', 
										help='response type must be json or html')
			args = parser.parse_args()
			#firstly try to make sure the request body is correct enough to use
			if len(request.files.values()) == 0 and \
			   (inputs and (set(inputs.keys()) != set(['schema', 'input_table', 'target_column', 'primary_key']) \
			             and set(inputs.keys()) != set(['input_table', 'target_column', 'primary_key']))):
				return {'error': 'can not understand input body 1'}, 400
			# try to retrive this model from database
			try:
				#retrieve the corresponding model 
				model = user.retrieve_model(name)
				#if the retrieved model is SPSSModel and there is file uploaded from client
				if model.model_type == 'SPSS Predictive Model' and len(request.files.values()) != 0:
					uploaded_file = request.files.values()[0]
					#refresh this model with uploaded file
					model.refresh(secure_filename(uploaded_file.filename), uploaded_file)
				#if the retrieved model is DashdhModel and there is correct creation information
				elif model.model_type == 'DashDB In-database Model' and \
					inputs and (set(inputs.keys()) == set(['schema', 'input_table', 'target_column', 'primary_key']) \
			                 or set(inputs.keys()) == set(['input_table', 'target_column', 'primary_key'])):
					if 'schema' in inputs.keys():
						input_table = inputs['schema'] + '.' + inputs['input_table']
					else:
						input_table = inputs['input_table']
					model.refresh(input_table, inputs['target_column'], 
								  inputs['primary_key'], False)
				else:
					return {'error': 'can not understand input body 2'}, 400
				if args['response_type'] == 'html':
					return render_template('modal_alert.html', id="add-new-model-alert",
						info='Model has been refreshed. Click the button back to Catalog',
						jump_to='/catalog')
				else:
					return {'message' : model.model_type+' '+name+' has been successfully refreshed.',
							'url': url_for('ml_service_model', name=name, _external=True)}
			#if model does not exist in database,
			#create a model from input
			except e.ModelNotExistsError:
				if len(request.files.values()) != 0:
					uploaded_file = request.files.values()[0]
					#create a new spss model object
					model = Model.create_spss_model(name, user, secure_filename(uploaded_file.filename), uploaded_file)
				elif set(inputs.keys()) == set(['schema', 'input_table', 'target_column', 'primary_key']) \
						 or set(inputs.keys()) == set(['input_table', 'target_column', 'primary_key']):
					if 'schema' in inputs.keys():
						input_table = inputs['schema'] + '.' +inputs['input_table']
					else:
						input_table = inputs['input_table']
					model = Model.create_dashdb_model(name, user, input_table, inputs['target_column'], 
								  		inputs['primary_key'], is_sample=False)
				else:
					return {'error': 'can not understand input body 3'}, 400
				#after the model is created, retrieve their metadata
				model.retrieve_metadata()
				#finally store this model to database by committing
				model.commit()
				if args['response_type'] == 'html':
					return render_template('modal_alert.html', id="add-new-model-alert",
									info='Model has been created. Click the button back to Catalog',
									jump_to='/catalog')
				else:
					return {'message' : model.model_type+' '+name+' has been successfully created.',
							'url': url_for('ml_service_model', name=name, _external=True)}
		except Exception as error:
			if 'msg' in error.__dict__:
				#if 'msg' is one of the attributes of the error,
				#it means this is an error defined this application
				info = 'Deploying/refreshing model '+name+' failed: '+\
									  str(error.__class__.__name__)+': '+error.msg
				app.logger.error(info)
				return {'error':info}, 500
			else:
				exc_value = sys.exc_info()[1]
				#raise error
				info = 'Deploying/refreshing model '+name+' failed: '+\
					   str(error.__class__.__name__)+": "+str(exc_value)
				app.logger.error(info)
				return {'error': info}, 500
Exemple #15
0
class Controller:
    def __init__(self):
        self._app = QtWidgets.QApplication(sys.argv)
        self._model = Model()
        self._view = View()

        self.add_thread = AddThread()
        self.timer_thread = TimerThread()
        self.init()

    def init(self,):
        self.set_table_and_combox()

        self.add_thread.add_to_table_signal.connect(lambda: self._view.add_to_table(self.add_thread.items))
        
        self.timer_thread.set_label_signal.connect(self._view.set_label)
        self.timer_thread.update_signal.connect(self.update_data)

        self._view.add_btn.clicked.connect(
            lambda: self.insert_to_db(
                self._view.title_lineEdit.text(),
                self._view.time_lineEdit.text())
            )
        self._view.reset_btn.clicked.connect(self.settlement)
        self._view.delete_btn.clicked.connect(self.delete_data)
        self._view.play_btn.clicked.connect(self.start_playing)
        self._view.pause_btn.clicked.connect(self.pause_playing)
        self._view.stop_btn.clicked.connect(self.stop_playing)

    def settlement(self,):
        items = self._model.get_all_record()
        for item in items:
            title = item[0]
            target = item[1]
            owe = item[2]
            now = item[3]
            record_target = item[4]

            if owe!=0:
                owe -= now
                if owe<0:
                    target += owe
                    owe = 0
                    if target<0:
                        target = 0
            else:
                target -= now
                if target<0:
                    target = 0
                    
            owe += target
            self._model.reset_record(title, owe, 0, record_target)
            self.set_table_and_combox()

    def update_data(self, item: tuple):
        self._model.update_data(item[0], item[1], item[2], item[3])
        self.set_table_and_combox()

    def stop_playing(self,):
        self.timer_thread.stop_flag = True

    def pause_playing(self,):
        self.timer_thread.pause_flag = not self.timer_thread.pause_flag

    def start_playing(self,):
        if self.timer_thread.isRunning():
            self.pause_playing()
        else:
            self.timer_thread.title = self._view.comboBox.currentText()
            item = self._model.get_data('title', self.timer_thread.title)
            _, self.timer_thread.target, self.timer_thread.owe, self.timer_thread.now = item

            self.timer_thread.start()

    def delete_data(self,):
        items = self._view.tableWidget.selectionModel().selectedRows()
        for item in items:
            row = item.row()
            title = self._view.tableWidget.item(row, 0).text()

            self._model.delete_data(title)

            self._view.tableWidget.removeRow(row)

    def validate_title(self, title: str):
        if title.isdigit():            
            return False

        return not self._model.search_title(title)

    def validate_time(self, time: str):
        try:            
            return int(time)
        except ValueError:            
            print("Invalid time.")
            return False

    def insert_to_db(self, title: str, time:str):
        validated_title = self.validate_title(title)*60
        validated_time = self.validate_time(time)*60

        if validated_title and validated_time:
            self._model.insert_to_db(title, validated_time, 0, 0)
            try:
                # set items
                self.add_thread.items = (title, validated_time, 0, 0, validated_time)
                self.add_thread.start()
            except Exception as e:
                print(e)
        else:
            if title.isdigit():
                self._view.msgBox(f'<{title}> cannot only construct by number.')
            else:
                self._view.msgBox(f'<{title}> has repeat or time invalid failed.')

    def set_table_and_combox(self,):
        self._view.tableWidget.clear()
        self._view.tableWidget.setRowCount(0)

        items = self._model.get_all_record()
        for item in items:
            self._view.add_to_table(item)
            self._view.comboBox.addItem(item[0])

    def run(self):
        self._view.show()
        return self._app.exec_()
Exemple #16
0
class Controller:
    """
        Class that orchestrates the interactions between model(data) and view(user)
        
    """
    def __init__(self):
        self.model = Model()
        self.view = View()

    def run(self) -> None:
        """
            Method is the main method that orchestrates all the methods in the model, view, and controller
            
        """
        run = self.view.display(
        )  # if the user selects to procede, then with the main program
        if run == True:
            self.storeCredentials(
            )  # gets the credentials from the user and store in class methods
            self.storeSession(
            )  # gets the credentials to sign into duolingo via api, and then gets the user session and stores it in class method

            self.proccessLanguage()
            numEntriesComp = self.model.compareApiToTable(
            )  # boolean value for equality
            self.branchGetData(numEntriesComp)  # load data into model
            hashes = self.branchOutput(
            )  # gets the user's input to determine the batch of methods used in program
            wordHash = hashes[0]  # unpack the two dictionaries
            flagHash = hashes[1]
            print("len of flaghash: ", len(flagHash))
            self.iterateVocabHash(
                wordHash,
                flagHash)  # send and receive data from both model and view
            self.model.closeDb()
        else:
            self.exit()

    """
        The following methods:
        
            storeCredentials(), storeSession(), repeatStoreSession()
        
        address user authentication and storage
            
    """

    def storeCredentials(self) -> None:
        """
            Method that obtains from user duolingo credentials and stores it in the model
            
        """
        cred = self.view.getUserCredentials()  # get the user credentials
        self.model.storeUserCredentials(cred[0], cred[1])

    def storeSession(self) -> None:
        """
            Method that obtains from user duolingo credentials and stores it in the model
            
        """
        self.view.displayOutput("signing into duolingo with credentials... ")
        session = self.model.signIn(
        )  # given provided user credentials, attempt login into duolingo
        if session is None:
            self.repeatStoreSession(
            )  # the loop will repeat until valid credentials are given and signin succeeds
        self.view.displayOutput("signin successful!")

    def repeatStoreSession(self) -> None:
        """
            Method that obtains from user duolingo credentials and stores it in the model
            
            Similar to the storeSession method, but it contains additional print statements
            
        """
        self.view.displayOutput("signin unsuccessful...")
        self.view.displayOutput("try again!")
        self.storeCredentials()  # see method for details
        self.storeSession()  # see method for detials

    """
        The following methods:
        
           proccessLanguage(), chooseLanguage()
           
        address selecting and storing the target language
            
    """

    def proccessLanguage(self) -> None:
        """
            Method that initials collecting the language information from api and from user input.
            These two informations are coordinated until a user confirms the desired target language
            
        """
        languages = self.model.getLanguage()
        lang = self.chooseLanguage(languages)
        if lang == None:
            self.view.displayOutput("exiting application")
            self.view.displayOutput("no language avaliable to select")
        print("printing user lang input " + lang)
        self.model.language = lang

    def chooseLanguage(self, languages: List[str]) -> any:
        """
            Method that returns the language the user inputs, if and only if its a language started in the user's account
            
        """
        if len(languages) == 0:
            self.view.displayOutput("did not begin learning a language")
            self.view.displayOutput("go to duolingo and select a language")
            return None
        elif len(languages) == 1:
            self.view.displayOutput("selecting the language: {}".format(
                languages[0]))
            return languages[0]
        else:
            self.view.displayOutput("1 than more language available")
            self.view.displayOutput("choose a language from the following: ")
            s = ""
            for lang in languages:
                s += lang + " "
            self.view.displayOutput(s)
            while True:
                input_ = input().lower()
                if input_ in languages:
                    self.view.displayOutput(
                        "Successful. Choosing {}".format(input_))
                    return input_
                self.view.displayOutput("did not select properly")
                self.view.displayOutput("choose 1 of the following: " + s)

    """
        The following methods:
        
            dataToModel(), dataFromTable()
        
        address getting vocabulary data and storing the data in storage
            
    """

    def dataToModel(self) -> None:
        """
            Method that orchestrates obtaining from duolingo, vocabulary words and converts the words from a list to a hashmap
            
        """
        self.view.displayOutput("obtaining vocabulary...")
        self.model.pullVocab()  # store the vocab words in a list
        self.model.translateToHash(
        )  # translates the vocab words in a list into a dictionary/ hashmap

    def dataFromTable(self) -> None:
        """
            Method that orchestrates obtaining from table, vocabulary words and converts the words from a list to a hashmap
            
        """
        self.view.displayOutput("loading data...")
        self.model.queryHashFromTable(
        )  # converts the table rows and stores it in the class variable of the model
        keys = list(self.model.getWordHash().keys(
        ))  # gather the keys as a paramter for the makeNewFlagHash method
        flagHash = self.model.makeNewFlagHash(keys)
        self.model.setFlagHash(flagHash)  # setter method

    """
        The following methods:
        
            branchGetData(), branchOutput()
        
        address getting branches (if/else) statements that determine the flow of methods executed in the program
            
    """

    def branchGetData(self, lenComp: bool) -> None:
        """
            Method that determines the flow of the program. It obtains the existing entries in the table if it already exist. Otherwise, it deletes and recreates an empty table and obtains entries from the duolingo api, then saves the entries in the table for later"
            
        """
        if lenComp == True:  # same length
            self.view.displayOutput("getting data from table...")
            self.dataFromTable()  # get data from table and store in model
        else:
            self.view.displayOutput(
                "getting data from api and creating table...")
            self.dataToModel(
            )  # get the data from duolingo via api, and stores the data in the model
            self.model.queryHashToTable
            self.model.saveDataToPersistentStorage()

    def branchOutput(self) -> List[Dict]:
        """
            Method that obtains user input. The input determines the batch of methods that are run
            
        """
        self.view.displayOutput(
            "(T)arget to English, or (E)nglish to Target? \n")
        resp = self.view.displayInput()
        wordHash = {}
        flagHash = {}
        if (resp == "t"):
            wordHash = self.model.wordHash  # store as is
            flagHash = self.model.flagHash  # store as is
        elif (resp == "e"):
            wordHash = self.model.invertWordHash(
            )  # reverse the order of keys and values
            flagHash = self.model.makeNewFlagHash(
                wordHash.keys()
            )  # remake the flagHash variable, but with English words as the key
        else:
            self.view.displayOutput(
                "not an allowed command {}. Try again!".format(resp))
            self.branchOutput()
        hashes = [wordHash, flagHash]  # return the two dictionaries in a list
        return hashes

    """
        The following methods:
        
            iterateVocabHash(), vocabIO(), displayNumCorrect()
        
        address getting the model data to the view and getting the user input to the model
        
     """

    def iterateVocabHash(self, wordHash: Dict[str, str],
                         flagHash: Dict[str, int]) -> None:
        """
            Method orchestrates the interactions between the model(data) and view(user)
            
            Flag is a boolean variable; it releases the program loop if the user translates all of the words
            For loop repeats without the correctly translated words
            
        """
        userSolvedAll = self.model.vocabFlag(
            flagHash)  # boolean variable: default value is False
        while userSolvedAll != True:
            for key in wordHash:
                self.vocabIO(
                    key, wordHash, flagHash
                )  # give and get data from the view and model, respectively
            wordHash = self.model.updateVocabHash(
                wordHash,
                flagHash)  # filter the vocabHash with the translated words
            userSolvedAll = self.model.vocabFlag(
                flagHash
            )  # if all words are translated correctly, then update the flag variable
            self.displayNumCorrect(
                flagHash
            )  # print to the view the number of remaining unlearned words

    def vocabIO(self, key: str, wordHash: Dict[str, str],
                flagHash: Dict[str, int]) -> Dict[str, int]:
        """
            Method that displays the vocab word to the view and obtains the translation input from the user
            It also compares the user translation and recorded translation with the compareInput method
            
        """
        input_ = self.view.displayWord(
            key
        )  # gives the vocab word to the view, and gets the input translation from the user
        value = wordHash[key]  # get the translation of the vocab word
        flagHash = self.model.compareInput(
            key, value, input_, flagHash
        )  # boolean variable that compares user input with translation
        return flagHash

    def displayNumCorrect(self, flagHash: Dict[str, int]) -> None:
        """
            Method that computes and displays the number of remaining words unlearned
            
        """
        numCount = self.model.getNumCorrect(flagHash)  # see method for detials
        self.view.displayOutput("Number remaining: {} ".format(
            len(flagHash) -
            numCount))  # the computation gives the number of unlearned words

    def exit(self) -> None:
        """
            Method that safely exits the program
            
        """
        self.view.displayOutput("until next time...")
        sys.exit()
Exemple #17
0
 def __init__(self):
     self.model = Model()
     self.view = View()
Exemple #18
0
 def __init__(self):
     self._model = Model()
     self._gui = Gui(self._model)
     self._ip = ImageProcessing(self._model)
     self._tf_session = None
Exemple #19
0
class Controller(Tk.Frame):
    MUSIC_ENDED = pygame.USEREVENT + 1

    def __init__(self, directory, master=None):
        Tk.Frame.__init__(self, master)
        self.master.title('MP3 Player')
        self.master.resizable(0, 0)

        self.model = Model(directory)

        self.init_mixer()

        self.main_frame = MainFrame(self)
        self.artwork = Artwork(self, self.main_frame.main_frame)
        self.seekbar = Seekbar(self, self.main_frame.main_frame)
        self.text_frame = TextFrame(self, self.main_frame.main_frame)
        self.buttons = Buttons(self, self.main_frame.main_frame)
        self.listbox = ScrollListBox(self, self.main_frame.main_frame)
        self.volume_window = VolumeWindow(self)

    def init_mixer(self):
        pygame.mixer.init()
        pygame.mixer.music.set_endevent(Controller.MUSIC_ENDED)

    def play(self):
        self.model.play()
        self.reset_seekbar()

    def play_next(self):
        self.model.play_next()
        self.reset_seekbar()

    def update_frame(self):
        current_song = self.model.get_current_song()
        artist = self.model.get_artist()
        album = self.model.get_album()
        self.text_frame.set_current(current_song, artist, album)

    def update_listbox(self):
        self.listbox.listbox_itself.selection_clear(0,
                                                    len(self.model.song_list))
        self.listbox.listbox_itself.selection_set(
            self.model.current_song_index)

    def update_seekbar(self):
        sec = self.model.get_current_playing_position()
        self.seekbar.set_current_second(sec)

    def reset_seekbar(self):
        seekbar_length = self.model.convert_song_length()
        self.seekbar.reset_seekbar(seekbar_length)

    def mode_repeat(self):
        if not self.model.is_repeat:
            self.model.is_repeat = True
            self.model.is_shuffle = False
            self.buttons.mode_repeat()
        else:
            self.model.is_repeat = False
            self.buttons.mode_repeat_off()

    def mode_shuffle(self):
        if not self.model.is_shuffle:
            self.model.is_shuffle = True
            self.model.is_repeat = False
            self.buttons.mode_repeat_off()
            self.buttons.mode_shuffle()
        else:
            self.model.is_shuffle = False
            self.buttons.mode_shuffle_off()

    def play_pause_song(self, event):
        self.model.play_pause_song()
        if self.model.is_stopped:
            self.buttons.play()
        else:
            self.buttons.pause()

    def previous_song(self, event):
        self.model.previous_song()
        self.reset_seekbar()

    def next_song(self, event):
        self.model.next_song()
        self.reset_seekbar()

    def rewind_song(self, event):
        self.model.rewind_song()
        self.reset_seekbar()

    def on_enter(self):
        self.buttons.on_enter()

    def on_leave(self):
        self.text_frame.on_leave()

    def show_hide_listbox(self):
        self.listbox.show_hide_listbox()

    def get_song_list(self):
        return self.model.real_names

    def select_song(self, event):
        self.model.current_song_index, = self.listbox.listbox_itself.curselection(
        )
        self.model.is_stopped = False
        self.model.play_selected_song()
        self.reset_seekbar()

    def control_volume(self):
        if self.volume_window.is_visible:
            self.volume_window.is_visible = False
        else:
            self.volume_window.is_visible = True
        self.volume_window.set_window_visible()

    def change_volume(self, event):
        current_volume = self.volume_window.volume.get() / 100
        self.model.change_volume(current_volume)
from flask import render_template, flash, redirect
from app import app
from app.forms import LoginForm
from app.model import Model

model = Model()


@app.route('/')
def root():
    return redirect('/index')


@app.route('/index', methods=['GET', 'POST'])
def index():
    form = LoginForm()
    if form.validate_on_submit():
        model.find_similar(form.abstract_text.data)
        return redirect('/index')
    return render_template(
        'index.html',
        title='Sign In',
        form=form,
        tables=[
            model.result_df.to_html(
                classes=["table-bordered", "table-striped", "table-hover"])
        ],
        titles=model.result_df.columns.values)
Exemple #21
0
def train():
    with db.app.app_context():
        model = Model()
        articles = Article.query.all()
        data = [(a.body, 1 if a.flag_use else 0) for a in articles]