コード例 #1
0
ファイル: functions.py プロジェクト: NotDeepmind/NeliTrainer
def CheckEntry(Answers, vocable, requested, user, selector, path, mode):
    if not selector.idx == [] and mode == "nach Reihenfolge" and len(
            selector.Entities) == 2:
        logger.debug('Setting new last_stop to ' + str(selector.idx))
        db = Database(path)
        db.set_lessons_last_stop(user, 'Alles', selector.idx)
    RecentAnswer = []
    label_colors = []
    for Answer in Answers:
        RecentAnswer.append(Answer.get())
    CorrectInstance2 = 0
    for request in requested:  # second loop here because all answers have to be saved to cross-check answer
        CorrectInstance = 0
        for Answer in RecentAnswer:
            if Answer == request or Answer == "#":
                label_colors.append("#50AA50")
                CorrectInstance = 1
                CorrectInstance2 += 1
        if CorrectInstance == 0:
            label_colors.append(
                "#FF0000")  #no combination matched --> wrong Answer
    if CorrectInstance2 == len(RecentAnswer):
        correctness = 'Richtig'
    else:
        correctness = 'Falsch'
    answer_datetime = vocable.EnterResults(RecentAnswer, correctness, user,
                                           path)
    return label_colors, correctness, answer_datetime
コード例 #2
0
ファイル: functions.py プロジェクト: NotDeepmind/NeliTrainer
def AddVocables(vocables, path_add, path):
    if path_add == "":
        path_add = filedialog.askopenfilename(filetypes=[("TSV Files",
                                                          "*.tsv *.txt")])
    if path_add[-3:] != "txt" and path_add[-3:] != "tsv":
        logger.warning(
            "User somehow managed to try and load a file with neither txt nor tsv extension"
        )
    else:
        NewVocs = ParseTxt_toDicts(path_add)
    if len(NewVocs) == 0:
        logger.warning("Could not parse any vocables from the TSV!")
    else:
        db = Database(path)
        for entry in NewVocs:
            prev_entry = db.find_vocable(", ".join(entry["deutsch"]),
                                         ", ".join(entry["spanisch"]),
                                         entry["kommentar"])
            if len(prev_entry) > 0:
                logger.warning(
                    "Trying to add existing vocable to the database, matching vocID "
                    + str(prev_entry[0][0]))
            else:
                db.add_vocable(", ".join(entry["deutsch"]),
                               ", ".join(entry["spanisch"]),
                               entry["kommentar"])
                new_vocID = \
                    db.find_vocable(", ".join(entry["deutsch"]), ", ".join(entry["spanisch"]), entry["kommentar"])
                for user in ["Andreas", "Christa", "Gemeinsam"]:
                    db.add_lessons_entry(user, "Alles", new_vocID[0][0],
                                         entry["answers"][user]["NextTime"])
                logger.debug("Added vocable " + ", ".join(entry["deutsch"]) +
                             " to the database")
    return vocables
コード例 #3
0
 def add_lessons_entry(self, user, lesson, vocID, NextTime):
     """ new lesson entries should be placed in random locations.
     To do that quickly, a random entry is replaced by the new one, and the old one is added to the end of the table
     This is done to prevent all new entries to cluster at the end of a table"""
     all_IDs = self.read_lesson_vocIDs(user, lesson)
     new_entry_loc = random.randint(1, len(all_IDs))
     old_entry = self.read_lessons_entry_byVocID(user, lesson,
                                                 new_entry_loc)
     self.c.execute(
         "UPDATE {}_lesson_{} "
         "SET vocIDref = :vocID, delay = 1, next_time = :NextTime "
         "WHERE rowid = :new_entry_loc".format(user, lesson), {
             "new_entry_loc": new_entry_loc,
             'vocID': vocID,
             'NextTime': NextTime
         })
     self.c.execute(
         "INSERT INTO {}_lesson_{} "
         "(vocIDref, delay, next_time) "
         "VALUES (:vocID, :delay, :NextTime)".format(user, lesson), {
             "vocID": old_entry[0][0],
             "delay": old_entry[0][1],
             "NextTime": old_entry[0][2]
         })
     self.conn.commit()
     logger.debug("Added new entry in user's lesson table")
コード例 #4
0
 def Buttonfunc_AddDelay(self, delay):
     """ Used in Vocable Questionare. In modus 'Nach Fälligkeit' a delay is set after every answer. """
     logger.debug('Adding a new Interval of ' + str(delay) + ' days')
     self.current_vocable.AddDelay(self.user, delay, self.mode, self.path)
     if len(self.user_answers) >= self.MaxNumVocables:
         self.Buttonfunc_EndSession()
     else:
         self.Buttonfunc_NextVocable()
コード例 #5
0
ファイル: functions.py プロジェクト: NotDeepmind/NeliTrainer
def LoadData(path, Selector, user="******"):
    ListOfObjects = []
    path_no_ending, file_extension = path.split(".")
    path = path_no_ending + ".db"  # work with db in future
    if not os.path.isfile(path):
        if os.path.isfile(path_no_ending + ".json"):
            with open(path_no_ending + ".json", encoding='UTF8') as json_file:
                vocablesDict = json.load(json_file)
        elif os.path.isfile(path_no_ending + ".tsv"):
            vocablesDict = ParseTxt_toDicts(path_no_ending + ".tsv")
        for entry in vocablesDict:
            ListOfObjects.append(C_vocables.C_vocables(entry))
    db = Database(path)
    if len(ListOfObjects) > 0:
        db.convert_JSON(ListOfObjects)

    # load with different priorities, use db if exists, use json if not, use tsv or txt if no json exists
    # old file formats are converted to db and will solely be used in the future
    ListOfObjects = []
    ListOfVocIDs = []
    ListOfDueVocIDs = []
    for vocID in db.read_lesson_vocIDs(user, "Alles"):
        entry = db.read_vocable_byID(vocID[0])
        if len(entry) > 0:
            entry_dict = {
                'vocID': entry[0][0],
                'deutsch': entry[0][1].split(", "),
                'spanisch': entry[0][2].split(", "),
                'kommentar': entry[0][3]
            }
            ListOfVocIDs.append(entry_dict['vocID'])
            entry_faellig = db.read_lessons_entry_byVocID(
                user, "Alles", entry_dict['vocID'])
            entry_dict['delay'] = entry_faellig[0][1]
            entry_dict["NextTime"] = entry_faellig[0][2]
            if dt.today() >= dt.strptime(entry_dict["NextTime"], "%Y-%m-%d"):
                ListOfDueVocIDs.append(entry_dict['vocID'])
            ListOfObjects.append(C_vocables.C_vocables(entry_dict))
            logger.debug('Loaded vocables vocID ' + str(entry_dict['vocID']) +
                         ', deutsch: ' + ", ".join(entry_dict['deutsch']) +
                         ', spanisch: ' + ", ".join(entry_dict['spanisch']) +
                         ', kommentar: ' + entry_dict['kommentar'] +
                         ', last delay was: ' + str(entry_dict['delay']) +
                         ', next time on: ' + entry_dict["NextTime"])
        else:
            logger.warning(
                "You tried to load an entry that has vocIDref " +
                str(vocID[0]) + " in the lesson " + user +
                "_lesson_Alles, but it does not exist in the vocable table")
            logger.warning("Removing entry from user " + user +
                           "lessons 'Alles'")
            try:
                db.delete_lesson_entry_byVocID(user, "Alles", vocID[0])
            except:
                pass
    Selector.NumbersOfEnteties(ListOfVocIDs)
    Selector.NumbersOfEnteties(ListOfDueVocIDs)
    return path, ListOfObjects, Selector
コード例 #6
0
 def ChangedEntries(self, deutsch, spanisch, kommentar, path):
     db = Database(path)
     logger.info("Saving changed on vocID: " +
                 str(self.OrigEntires[self.idx]["vocID"]))
     logger.debug("New contents are:")
     logger.debug("german: " + deutsch + ", spanisch: " + spanisch +
                  ", comment: " + kommentar)
     db.set_vocable(self.OrigEntires[self.idx]["vocID"], deutsch, spanisch,
                    kommentar)
コード例 #7
0
ファイル: functions.py プロジェクト: NotDeepmind/NeliTrainer
def intervals(vocable, IntervalMatrix, user):
    # for key in vocable.content:
    #     print("content keys: " + key)
    # LastDelaysList = list(vocable.content["answers"][user]["delay"])
    # while -1 in LastDelaysList:
    #     LastDelaysList.remove(-1)
    last_delay = vocable.content['delay']
    for row in IntervalMatrix:
        if last_delay >= row[0] and last_delay <= row[1]:
            logger.debug('Old Delay was ' + str(last_delay) +
                         ', new choices are ' + str(row[2]) + ", " +
                         str(row[3]) + ", " + str(row[4]))
            return row[2:]  # find the right row of the delay matrix
コード例 #8
0
 def NextEntity(self, mode):
     #initiate correctly depending on mode
     if self.IDs == -1 and mode == "nach Reihenfolge" and len(
             self.Entities) == 2:
         self.listID = 0
         self.IDs = self.Entities[0].index(self.last_stop)
         logger.debug("knowing that last_stop was " + str(self.last_stop))
     elif self.IDs == -1 and mode == "nach Fälligkeit" and len(
             self.Entities) == 2:
         self.listID = 1
         self.IDs = -1
     self.IDs += 1
     #restart if end of list is reached
     if self.IDs >= len(self.Entities[0]) and mode == "nach Reihenfolge":
         self.IDs = 0
     elif self.IDs >= len(self.Entities[-1]) and mode == "nach Fälligkeit":
         print("Trying to call more Entries than exist?!")
     self.idx = self.Entities[self.listID][self.IDs]
     logger.info("Trying to show the vocID: " + str(self.idx))
コード例 #9
0
ファイル: functions.py プロジェクト: NotDeepmind/NeliTrainer
def NextVocable(Selector, mode, path, user, language, vocables,
                MaxNumVocables):
    db = Database(path)
    last_stop = db.read_lesson_last_stop(user, 'Alles')
    Selector.last_stop = last_stop[0][0]
    Selector.NextEntity(mode)
    logger.debug("Trying to find vocable with vocID " + str(Selector.idx))
    for vocable0 in vocables:
        if vocable0.content['vocID'] == Selector.idx:
            logger.debug("found!")
            vocable = vocable0.content
            current_vocable = vocable0
            break
    if language == 0:
        presented = vocable["deutsch"]
        requested = vocable["spanisch"]
    elif language == 1:
        presented = vocable["spanisch"]
        requested = vocable["deutsch"]
    kommentar = vocable["kommentar"]
    if mode == "nach Fälligkeit":
        MaxNumVocables = len(Selector.Entities[-1])
    return presented, requested, kommentar, MaxNumVocables, current_vocable
コード例 #10
0
 def convert_JSON(self, vocables):
     logger.info("Converting from JSON to MySQL DB")
     for user in vocables[0].content["answers"]:
         logger.debug("Creating Data for user: "******"Alles", range(1, 1 + len(vocables)),
                         vocables[0].content[user]["last_stop"])
     logger.debug("finished creation of user tables")
     user_answers = {}
     for vocable in vocables:
         logger.debug("Adding Vocable: " +
                      ", ".join(vocable.content["deutsch"]))
         self.add_vocable(", ".join(vocable.content["deutsch"]),
                          ", ".join(vocable.content["spanisch"]),
                          vocable.content["kommentar"])
         logger.debug("Finding vocID of the vocable")
         vocID = self.find_vocable(", ".join(vocable.content["deutsch"]),
                                   ", ".join(vocable.content["spanisch"]),
                                   vocable.content["kommentar"])
         logger.debug("Found! VocID: " + str(vocID))
         for user in vocable.content["answers"]:
             if "NextTime" in vocable.content["answers"][user]:
                 for idx in range(
                         len(vocable.content["answers"][user]["delay"])):
                     index = -1 - idx  # start checking for delay > 0 in reverse order
                     if vocable.content["answers"][user]["delay"][index] > 0:
                         logger.debug("updating table of " + user +
                                      " at vocID " + str(vocID) +
                                      " to show a delay of " +
                                      str(vocable.content["answers"][user]
                                          ["delay"][index]))
                         self.set_lesson_delay(
                             user, "Alles", vocID[0][0],
                             vocable.content["answers"][user]["delay"]
                             [index],
                             vocable.content["answers"][user]["NextTime"])
                         break
                     logger.debug("Did not find a delay > 0 on vocID " +
                                  str(vocID[0][0]) + " for user " + user)
             # logger.debug("Adding previous answers to the DB")
             for idx in range(len(
                     vocable.content["answers"][user]["delay"])):
                 if user not in user_answers:
                     user_answers[user] = []
                 try:
                     user_answers[user].append(
                         (vocID[0][0], ", ".join(vocable.content["answers"]
                                                 [user]["answer"][idx]),
                          vocable.content["answers"][user]["datetime"][idx],
                          vocable.content["answers"][user]["correctness"]
                          [idx]))
                 except:
                     logger.warning("corrupted data on Answer: " +
                                    ", ".join(vocable.content["deutsch"]) +
                                    ", " + user)
     for user in vocables[0].content["answers"]:
         self._check_user(user)
         self.c.executemany(
             "INSERT INTO {}_answertable "
             "VALUES (?, ?, ?, ?)".format(user), user_answers[user])