Ejemplo n.º 1
0
 def print_state(self):
     debug(
         f"sent.: {self.index}/{len(self.current_sentences)}, "
         f"skip: {len(self.skip)}, "
         f"to repeat: {self.learning.to_repeat(self.skip)}"
     )
Ejemplo n.º 2
0
    def process_answer(self, message):

        debug("process_answer()")
        self.print_state()

        answer: str = message

        sentence_id: int = (
            self.current_sentences[self.index].sentence.id_
            if self.index < len(self.current_sentences)
            else 0
        )

        # Preprocess answer.
        answer: str = self.learning_language.decode_text(answer)

        self.index += 1

        if answer == self.word:

            self.index = 0

            self.learning.register(
                ResponseType.RIGHT, sentence_id, self.word, self.interval * 2
            )
            if self.items:
                string_items: list[str] = [
                    x.to_str(self.known_language, self.interface)
                    for x in self.items
                ]
                self.interface.print("\n".join(string_items))

            self.learning.write()

            self.print_state()
            return (
                "Right"
                + (
                    f", {self.learning.to_repeat()} to repeat"
                    if self.learning.to_repeat()
                    else ""
                )
                + "."
            )

        elif answer in self.alternative_forms:
            self.print_state()
            return "Right form."

        elif answer in ["/skip", "Skip"]:
            self.skip.add(self.word)
            self.index = 0
            self.print_state()
            return "Skipped for this session."

        elif answer == "/stop":
            return "Stop."

        elif answer in ["/no", "Don't know"]:

            self.interface.box(self.word)
            if self.items:
                string_items: list[str] = [
                    x.to_str(self.known_language, self.interface)
                    for x in self.items
                ]
                self.interface.print("\n".join(string_items))
            self.interface.box(self.word)

            new_answer = self.interface.input("Learn word? ")
            if not new_answer:
                self.learning.register(
                    ResponseType.WRONG,
                    sentence_id,
                    self.word,
                    SMALLEST_INTERVAL,
                )
            else:
                self.learning.register(
                    ResponseType.SKIP, sentence_id, self.word, timedelta()
                )

            self.learning.write()
            self.index = 0

            self.print_state()
            return f"Right answer: {self.word}."

        elif answer == "/exclude":
            self.user_data.exclude_sentence(self.word, sentence_id)
            self.skip.add(self.word)
            self.print_state()
            return "Sentence was excluded."

        elif answer.startswith("/hide "):
            parts = answer.split(" ")
            self.user_data.exclude_translation(self.word, " ".join(parts[1:]))
            self.skip.add(self.word)
            self.print_state()
            return "Translation was hidden."

        else:
            self.print_state()
            return "No."
Ejemplo n.º 3
0
                ):
                    self.worker = nearest
                    self.send(nearest.get_greetings())
                    self.state = ServerState.WORKER
                    self.step()
                    break
                elif self.lexicons and (
                    (nearest := sorted(self.lexicons)[0]).is_ready()
                ):
                    self.worker = nearest
                    self.send(nearest.get_greetings())
                    self.state = ServerState.WORKER
                    self.step()
                    break
                else:
                    debug(f"{datetime.now()} Waiting...")
                    sleep(60)

        elif self.state == ServerState.WORKER:
            if self.worker.is_ready():
                markup = types.ReplyKeyboardMarkup(
                    row_width=2,
                    resize_keyboard=True,
                    one_time_keyboard=True,
                )
                markup.add(
                    types.KeyboardButton("Skip"),
                    types.KeyboardButton("Don't know"),
                )
                for text in self.worker.get_next_question():
                    self.send(text)
Ejemplo n.º 4
0
    def get_next_question(self) -> list[str]:

        debug("get_next_question()")
        self.print_state()

        if self.index > 0:
            if self.index < len(self.current_sentences):
                return [self.get_sentence(max_translations=1)]
            elif self.index == len(self.current_sentences):
                return ["No more sentences."]

        self.word = self.learning.get_next(self.skip)
        if not self.word:
            return ["No more words."]

        self.interval = self.learning.knowledges[self.word].interval

        ids_to_skip: set[int] = set()
        if self.word in self.user_data.exclude_sentences:
            ids_to_skip = set(self.user_data.exclude_sentences[self.word])

        self.current_sentences: list[Translation] = self.sentences.filter_(
            self.word, ids_to_skip, 120
        )
        if self.interval.total_seconds() == 0:
            self.current_sentences = sorted(
                self.current_sentences, key=lambda x: len(x.sentence.text)
            )
        else:
            random.shuffle(self.current_sentences)

        dictionaries: Dictionaries = Dictionaries(self.dictionaries)

        def log_(interval):
            if interval.total_seconds() == 0:
                return 0
            return int(math.log(interval.total_seconds() / 60 / 60 / 24, 2)) + 1

        index: int = 0

        self.alternative_forms: set[str] = set()
        exclude_translations: set[str] = set()

        if self.word in self.user_data.exclude_translations:
            exclude_translations = set(
                self.user_data.exclude_translations[self.word]
            )

        self.items: list[DictionaryItem] = dictionaries.get_items(self.word)

        if self.learning_language == GERMAN:
            for item in dictionaries.get_items(
                self.word[0].upper() + self.word[1:]
            ):
                if item not in self.items:
                    self.items.append(item)

        words_to_hide: set[str] = set()
        for item in self.items:
            words_to_hide.add(item.word)
            for link in item.get_links():
                words_to_hide.add(link.link_value)

        result: list[str] = []
        statistics: str = ""
        if self.interval.total_seconds() > 0:
            statistics += "◕ " * log_(self.interval) + "\n"

        if self.items:
            translation_list = [
                x.to_str(
                    self.known_language,
                    self.interface,
                    False,
                    words_to_hide=words_to_hide | exclude_translations,
                    hide_translations=exclude_translations,
                )
                for x in self.items
            ]
            result.append(statistics + "\n".join(translation_list))
            self.alternative_forms = set(
                x.link_value for x in self.items[0].get_links()
            )
        else:
            result.append(statistics + "\nNo translations.")

        if index < len(self.current_sentences):
            result.append(self.get_sentence(max_translations=1))

        self.print_state()

        return result
Ejemplo n.º 5
0
    def start(self) -> bool:

        while True:
            word: Optional[str] = self.learning.get_next(self.skip)

            if word:
                code: str = self.learn(
                    word, self.learning.knowledges[word].interval, 0
                )
                if code == "stop":
                    return False

                continue

            if self.learning.new_today() >= self.max_for_day:
                return True

            has_new_word: bool = False

            for index, word in self.words:
                if self.learning.has(word):
                    if self.learning.is_initially_known(word):
                        debug(f"[{index}] was initially known")
                    else:
                        debug(f"[{index}] already learning")
                    continue

                if word in self.skip:
                    debug(f"[{index}] skipped")
                    continue

                items: list[DictionaryItem] = self.dictionaries.get_items(word)
                if not items and self.learning_language == GERMAN:
                    for item in self.dictionaries.get_items(
                        word[0].upper() + word[1:]
                    ):
                        if item not in items:
                            items.append(item)

                # Skip word if current dictionaries has no definitions for it
                # or the word is solely a form of other words.
                if not items:
                    debug(f"[{index}] no definition")
                    continue

                if not items[0].has_common_definition(self.learning.language):
                    debug(f"[{index}] not common")
                    continue

                if self.learning.check_lexicon and self.lexicon.has(word):
                    if self.lexicon.get(word) != LexiconResponse.DONT:
                        debug(f"[{index}] word is known")
                        continue
                    # TODO: else start learning

                if not self.lexicon.has_log("log_ex"):
                    self.lexicon.add_log(
                        LexiconLog("log_ex", WordSelection("top"))
                    )

                has_new_word = True

                if self.learning.ask_lexicon and not self.lexicon.has(word):

                    self.lexicon.write()

                    _, response, _ = self.lexicon.ask(
                        self.interface,
                        word,
                        [],
                        self.dictionaries,
                        log_name="log_ex",
                    )

                    if response is None:
                        return False

                    if response != LexiconResponse.DONT:
                        continue

                code: str = self.learn(word, timedelta(), index)
                if code == "stop":
                    return False
                break

            if not has_new_word:
                break

        return True