Esempio n. 1
0
def paste_ipa(editor: Editor) -> None:
    """ Paste IPA transcription into the IPA field of the Anki editor.

    :param editor: Anki editor window
    """
    lang_alias = editor.ipa_lang_alias
    note = editor.note

    # Get content of text field
    try:
        field_text = note[CONFIG["WORD_FIELD"]]
    except KeyError:
        showInfo(f"Field '{CONFIG['WORD_FIELD']}' doesn't exist.")
        return
    logging.debug(f"Field text: {field_text}")

    field_text = field_text.lower()

    if lang_alias == "english":
        ipa = get_english_ipa_transcription(field_text)
    else:
        # get word list from text field
        words = utils.get_words_from_field(field_text)
        logging.debug(f"Word list: {words}")

        # parse IPA transcription for every word in word list
        try:
            ipa = parse_ipa_transcription.transcript(words=words,
                                                     language=lang_alias)
        except (urllib.error.HTTPError, IndexError):
            showInfo("IPA not found.")
            return
        logging.debug(f"IPA transcription string: {ipa}")

    # paste IPA transcription of every word in IPA transcription field
    try:
        note[CONFIG["IPA_FIELD"]] = ipa
    except KeyError:
        showInfo(f"Field '{CONFIG['IPA_FIELD']}' doesn't exist.")
        return

    # update editor
    editor.loadNote()
    editor.web.setFocus()
    editor.web.eval("focusField(%d);" % editor.currentField)
Esempio n. 2
0
def add_pronunciation(editor: Editor, mode: Union[None, str] = None):
    if mode is None:
        modifiers = QApplication.keyboardModifiers()
        if modifiers == Qt.ShiftModifier:
            """Choose top pronunciation automatically when shift key is held down"""
            mode = "auto"

    deck_id = editor.card.did if editor.card is not None else editor.parentWindow.deckChooser.selectedId(
    )

    if editor.note is not None:
        note_type_id = editor.note.mid
    elif editor.card is not None:
        note_type_id = editor.card.note().mid
    else:
        note_type_id = editor.mw.col.models.current()["id"]

    search_field = config.get_note_type_specific_config_object(
        "searchField", note_type_id)
    if search_field is None or search_field.value not in editor.note.keys():
        d = FieldSelector(editor.parentWindow, editor.mw, note_type_id,
                          "searchField", config)
        d.exec()
        search_field = handle_field_select(d, note_type_id, "searchField",
                                           editor)
        if search_field is None:
            return

    audio_field = config.get_note_type_specific_config_object(
        "audioField", note_type_id)
    if audio_field is None or audio_field.value not in editor.note.keys():
        d = FieldSelector(editor.parentWindow, editor.mw, note_type_id,
                          "audioField", config)
        d.exec()
        audio_field = handle_field_select(d, note_type_id, "audioField",
                                          editor)
        if audio_field is None:
            return

    search_field = search_field.value
    audio_field = audio_field.value

    if editor.note is None:
        showInfo(
            "Please enter a search term in the field '" + search_field + "'.",
            editor.widget)
        return

    if mode == 'input':
        query, suc = aqt.utils.getText("Please enter a custom search term:",
                                       editor.widget,
                                       title="Enter custom search term")
        if not suc:
            showWarning("Didn't get any text, please try again.",
                        editor.widget)
            return
    elif editor.note is not None and search_field in editor.note.keys(
    ) and len(editor.note[search_field]) != 0:
        """If available, use the content of the defined search field as the query"""
        query = editor.note[search_field]
    else:
        showInfo(
            "Please enter a search term in the field '" + search_field + "'.",
            editor.widget)
        return

    query = BeautifulSoup(query, "html.parser").text

    if deck_id is not None:
        config_lang = config.get_deck_specific_config_object(
            "language", deck_id)

        if config_lang is None:
            d = LanguageSelector(editor.parentWindow,
                                 mw.col.decks.get(deck_id)["name"])
            d.exec()
            if d.selected_lang is not None:
                config.set_deck_specific_config_object(
                    ConfigObject(name="language",
                                 value=d.selected_lang,
                                 deck=deck_id,
                                 type=OptionType.LANG))
                language = d.selected_lang
            else:
                showInfo(
                    "Cancelled download because no language was selected.")
                return
        else:
            language = config_lang.value

        try:
            forvo = Forvo(query, language, editor.mw,
                          config).load_search_query()
            if forvo is not None:
                results = forvo.get_pronunciations().pronunciations
            else:
                raise NoResultsException()
        except NoResultsException:
            showInfo("No results found! :(", editor.widget)
            return

        hidden_entries_amount = 0
        if config.get_config_object("skipOggFallback").value:
            viable_entries = [p for p in results if not p.is_ogg]
            hidden_entries_amount = len(results) - len(viable_entries)
            if len(viable_entries) == 0:
                showInfo(
                    f"No results found! :(\nThere are {hidden_entries_amount} entries which you chose to skip by deactivating .ogg fallback."
                )
                return
            results = viable_entries

        if mode == "auto":

            def add_automatically(auto_results):
                """If shift key is held down"""
                auto_results.sort(
                    key=lambda result: result.votes)  # sort by votes
                top: Pronunciation = auto_results[
                    len(auto_results) - 1]  # get most upvoted pronunciation
                top.download_pronunciation()  # download that
                try:
                    if config.get_config_object(
                            "audioFieldAddMode").value == "append":
                        """append"""
                        editor.note.fields[get_field_id(
                            audio_field,
                            editor.note)] += "[sound:%s]" % top.audio
                    elif config.get_config_object(
                            "audioFieldAddMode").value == "replace":
                        """replace"""
                        editor.note.fields[get_field_id(
                            audio_field,
                            editor.note)] = "[sound:%s]" % top.audio
                    else:
                        """prepend"""
                        editor.note.fields[get_field_id(
                            audio_field, editor.note
                        )] = "[sound:%s]" % top.audio + editor.note.fields[
                            get_field_id(audio_field, editor.note)]
                except FieldNotFoundException:
                    showWarning(
                        "Couldn't find field '%s' for adding the audio string. Please create a field with this name or change it in the config for the note type id %s"
                        % (audio_field, str(note_type_id)), editor.widget)

                if config.get_config_object(
                        "playAudioAfterSingleAddAutomaticSelection"
                ).value:  # play audio if desired
                    anki.sound.play(top.audio)

                def flush_field():
                    if not editor.addMode:  # save
                        editor.note.flush()
                    editor.currentField = get_field_id(audio_field,
                                                       editor.note)
                    editor.loadNote(
                        focusTo=get_field_id(audio_field, editor.note))

                editor.saveNow(flush_field, keepFocus=True)

            editor.saveNow(functools.partial(add_automatically, results),
                           keepFocus=False)
        else:
            dialog = AddSingle(editor.parentWindow,
                               pronunciations=results,
                               hidden_entries_amount=hidden_entries_amount)
            dialog.exec()

            Forvo.cleanup()
            if dialog.selected_pronunciation is not None:
                try:
                    add_mode = config.get_config_object(
                        "audioFieldAddMode").value
                    if add_mode == "append":
                        editor.note.fields[get_field_id(
                            audio_field, editor.note
                        )] += "[sound:%s]" % dialog.selected_pronunciation.audio
                    elif add_mode == "prepend":
                        editor.note.fields[
                            get_field_id(audio_field,
                                         editor.note)] = "[sound:%s]" % dialog.selected_pronunciation.audio + \
                                                         editor.note.fields[
                                                             get_field_id(audio_field,
                                                                          editor.note)]
                    elif add_mode == "replace":
                        editor.note.fields[get_field_id(
                            audio_field, editor.note
                        )] = "[sound:%s]" % dialog.selected_pronunciation.audio
                except FieldNotFoundException:
                    showWarning(
                        "Couldn't find field '%s' for adding the audio string. Please create a field with this name or change it in the config for the note type id %s"
                        % (audio_field, str(note_type_id)), editor.widget)
                if not editor.addMode:
                    editor.note.flush()
                editor.loadNote()
Esempio n. 3
0
def paste_definitions(editor: Editor) -> None:

    note = editor.note

    try:
        word = note[CONFIG["WORD_FIELD"]]
    except KeyError:
        showdialog(f"Field '{CONFIG['WORD_FIELD']}' doesn't exist.")
        return
    logging.debug(f"Field text: {word}")

    word = word.lower()

    source_language = CONFIG["SOURCE_LANGUAGE"]
    target_language = CONFIG["TARGET_LANGUAGE"]
    abrv_source = CONFIG["LANG_SOURCE_ABRV"]
    abrv_target = CONFIG["LANG_TARGET_ABRV"]
    abrv_country = CONFIG["COUNTRY_TARGET_ABRV"]

    if editor.dic == 'cambridge':
        results = cambridge.search(word)
    if editor.dic == 'collins':
        results = collins.search(word)
    elif editor.dic == 'macmillan':
        results = macmillan.search(word)
    elif editor.dic == 'babla':
        results = babla.search(word, abrv_target, source_language,
                               target_language)
    elif editor.dic == 'pons':
        results = pons.search(word, source_language, target_language)
    elif editor.dic == 'linguee':
        results = linguee.search(word, source_language, target_language)
    elif editor.dic == 'freedic':
        results = freedic.search(word, abrv_target, abrv_country)
    elif editor.dic == 'reverso':
        results = reverso.search(word, abrv_target, target_language)
    elif editor.dic == 'wordreference':
        results = wordreference.search(word, abrv_source, abrv_target)

    if len(results) == 0:
        showdialog(f"Word {word} not found.")
    elif results[0] == '' and results[1] == '' and results[
            2] == '' and results[3] == '':
        showdialog(f"Word {word} without results.")

    if len(results) >= 1:
        try:
            if results[0] != '':
                if note[editor.dic + CONFIG["TRANSLATIONS_FIELD"]] == '':
                    note[editor.dic +
                         CONFIG["TRANSLATIONS_FIELD"]] = f'{results[0]}'
        except KeyError:
            showdialog(
                f"Field '{editor.dic}{CONFIG['TRANSLATIONS_FIELD']}' doesn't exist."
            )
            return

    if len(results) >= 2:
        try:
            if results[1] != '':
                note[editor.dic +
                     CONFIG["DEFINITIONS_FIELD"]] = f'{results[1]}'
        except KeyError:
            showdialog(
                f"Field '{editor.dic}{CONFIG['DEFINITIONS_FIELD']}' doesn't exist."
            )
            return

    if len(results) >= 3:
        try:
            if results[2] != '':
                note[editor.dic + CONFIG["IPA_FIELD"]] = f'{results[2]}'
        except KeyError:
            showdialog(
                f"Field '{editor.dic}{CONFIG['IPA_FIELD']}' doesn't exist.")
            return

    if len(results) >= 4:
        try:
            if results[3] != '':
                note[editor.dic + CONFIG["PHRASES_FIELD"]] = f'{results[3]}'
        except KeyError:
            showdialog(
                f"Field '{editor.dic}{CONFIG['PHRASES_FIELD']}' doesn't exist."
            )
            return

    if len(results) >= 5:
        try:
            if results[4] != '':
                note[editor.dic +
                     CONFIG["TRANSLATED_PHRASES_FIELD"]] = f'{results[4]}'
        except KeyError:
            showdialog(
                f"Field '{editor.dic}{CONFIG['TRANSLATED_PHRASES_FIELD']}' doesn't exist."
            )
            return

    if len(results) >= 6:
        try:
            if results[5] != '':
                note[editor.dic +
                     CONFIG["EXPRESSIONS_FIELD"]] = f'{results[5]}'
        except KeyError:
            showdialog(
                f"Field '{editor.dic}{CONFIG['EXPRESSIONS_FIELD']}' doesn't exist."
            )
            return

    # update editor
    editor.loadNote()
    editor.web.setFocus()
    editor.web.eval("focusField(%d);" % editor.currentField)