示例#1
0
def generate_cards_basic(english_meaning, kanji, reading):
    try:
        is_audio = proces_forvo(kanji, english_meaning)
        audio_name = 'sound{0}.mp3'.format(english_meaning)

        front = genanki.Note(model=english_to_kanji,
                             fields=[english_meaning, kanji, reading])

        reverse = genanki.Note(model=kanji_to_english_card,
                               fields=[
                                   kanji + '[sound:{0}]'.format(audio_name),
                                   english_meaning, reading
                               ])

        result = []

        if is_audio:
            print(audio_name)
            pronaunciation = genanki.Note(model=sound_card,
                                          fields=[
                                              '[sound:{0}]'.format(audio_name),
                                              english_meaning, reading
                                          ])
            result.append(pronaunciation)
        result.append(front)
        result.append(reverse)
        return result

    except Exception as e:
        print(e)
示例#2
0
def make_noun_note(de, ru):
    singular, *plurals = [s.strip() for s in de.split(',')]

    if not plurals:
        return genanki.Note(model=noun_without_plurals_model,
                            fields=(
                                colorize(singular),
                                ru,
                            ))

    singular_without_article = singular.split()[-1]
    processed_plurals = []

    for plural in plurals:
        if plural == '=':  # same except article
            processed_plurals.append('die {}'.format(singular_without_article))
        elif plural.startswith('-'):  # change article and append suffix
            processed_plurals.append('die {}{}'.format(
                singular_without_article, plural[1:]))
        else:
            processed_plurals.append(plural)

    return genanki.Note(model=noun_with_plurals_model,
                        fields=(colorize(singular),
                                ', '.join(processed_plurals), ru))
示例#3
0
    def gen_deck(self, csv_filename):
        name = os.path.splitext(os.path.basename(csv_filename))[0]
        deck = genanki.Deck(int(abs(hash(name)) / 100000000), name)
        media_files = []
        with open(csv_filename) as csv_file:
            i = 0
            for row in csv.reader(csv_file):
                if len(row) != 3:
                    continue
                q = row[0].strip()
                q_tts = row[1].strip()
                a = row[2].strip()
                if len(q) == 0 or len(a) == 0:
                    continue

                i += 1
                if q.startswith("* "):
                    q = q.replace("* ", str(i) + ". ")
                audio = self._tts.generate(q_tts)
                if audio is not None:
                    audio_name = os.path.basename(audio)
                    note = genanki.Note(model=self._model["tts"],
                                        fields=[q, a, f"[sound:{audio_name}]"])
                    media_files.append(audio)
                else:
                    note = genanki.Note(model=self._model["default"],
                                        fields=[q, a])
                deck.add_note(note)

        return deck, media_files
def test_builtin_models():
    my_deck = genanki.Deck(1598559905, 'Country Capitals')

    my_deck.add_note(
        genanki.Note(model=genanki.BASIC_MODEL,
                     fields=['Capital of Argentina', 'Buenos Aires']))

    my_deck.add_note(
        genanki.Note(model=genanki.BASIC_AND_REVERSED_CARD_MODEL,
                     fields=['Costa Rica', 'San José']))

    my_deck.add_note(
        genanki.Note(model=genanki.BASIC_OPTIONAL_REVERSED_CARD_MODEL,
                     fields=['France', 'Paris', 'y']))

    my_deck.add_note(
        genanki.Note(model=genanki.BASIC_TYPE_IN_THE_ANSWER_MODEL,
                     fields=['Taiwan', 'Taipei']))

    my_deck.add_note(
        genanki.Note(model=genanki.CLOZE_MODEL,
                     fields=['{{c1::Rome}} is the capital of {{c2::Italy}}']))

    # Just try writing the note to a .apkg file; if there is no Exception, we assume things are good.
    fnode, fpath = tempfile.mkstemp()
    os.close(fnode)
    my_deck.write_to_file(fpath)

    os.unlink(fpath)
示例#5
0
def generate_cards_extended(english_meaning, kanji, reading):
    try:

        front = genanki.Note(model=english_to_kanji,
                             fields=[english_meaning, kanji,
                                     ""])  # I should add radical

        reverse = genanki.Note(model=kanji_to_english_card,
                               fields=[kanji, english_meaning,
                                       reading])  # here picturewould be good

        kanji_reading = genanki.Note(model=kanji_to_reading,
                                     fields=[kanji, reading, reading[0]])
        result = []

        audio_name = 'sound{0}.mp3'.format(
            english_meaning)  # should I add one for kanji as well
        if os.path.isfile(audio_name):
            pronaunciation = genanki.Note(model=sound_card,
                                          fields=[
                                              '[sound:{0}]'.format(audio_name),
                                              english_meaning,
                                              english_meaning[0]
                                          ])
            result.append(pronaunciation)

        result.append(front)
        result.append(reverse)
        result.append(kanji_reading)
        return result

    except Exception as e:
        print(e)
def _fix_note(db, cloze_model, non_cloze_model, _note):
    # Turn a sql row to a dict
    note = dict(zip(NOTE_ATTRS, _note))

    field_names = _swap_first_two([x['name'] for x in cloze_model.fields])
    fields = dict(list(zip(field_names, note['flds'].split(ANKI_FIELD_SEP))))
    if is_empty_field(fields['ClozeFront']):
        # A non-cloze note
        fixed_fields = _fix_non_cloze_note_fields(non_cloze_model, fields)
        fixed_note = genanki.Note(
            model=non_cloze_model,
            guid=note['guid'],
            fields=fixed_fields,
            note_id=get_note_id(),
        )
    else:
        n_clozes, sort_field, fields = _fix_cloze_note_fields(cloze_model, note)
        fixed_note = genanki.Note(
            model=cloze_model,
            guid=note['guid'],
            fields=fields,
            sort_field=sort_field,
            note_id=note['id'],
        )
        _fix_cloze_cards(db, note['id'], fixed_note, n_clozes)
    return fixed_note
示例#7
0
  def test_notes_generate_cards_based_on_req__with_hint(self):
    # both of these notes will generate one card
    n1 = genanki.Note(model=TEST_MODEL_WITH_HINT, fields=['capital of California', '', 'Sacramento'])
    n2 = genanki.Note(model=TEST_MODEL_WITH_HINT, fields=['capital of Iowa', 'French for "The Moines"', 'Des Moines'])

    assert len(n1.cards) == 1
    assert n1.cards[0].ord == 0
    assert len(n2.cards) == 1
    assert n2.cards[0].ord == 0
示例#8
0
    def test_notes_generate_cards_based_on_req__cn(self):
        # has 'Simplified' field, will generate a 'Simplified' card
        n1 = genanki.Note(model=TEST_CN_MODEL, fields=['中國', '中国', 'China'])
        # no 'Simplified' field, so it won't generate a 'Simplified' card
        n2 = genanki.Note(model=TEST_CN_MODEL, fields=['你好', '', 'hello'])

        assert len(n1.cards) == 2
        assert n1.cards[0].ord == 0
        assert n1.cards[1].ord == 1

        assert len(n2.cards) == 1
        assert n2.cards[0].ord == 0
示例#9
0
def test_num_fields_less_than_model_raises():
    m = genanki.Model(1894808898,
                      'Test Model',
                      fields=[
                          {
                              'name': 'Question'
                          },
                          {
                              'name': 'Answer'
                          },
                          {
                              'name': 'Extra'
                          },
                      ],
                      templates=[
                          {
                              'name': 'Card 1',
                              'qfmt': '{{Question}}',
                              'afmt':
                              '{{FrontSide}}<hr id="answer">{{Answer}}',
                          },
                      ])

    n = genanki.Note(model=m,
                     fields=['What is the capital of Taiwan?', 'Taipei'])

    with pytest.raises(ValueError):
        n.write_to_db(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(),
                      mock.MagicMock())
示例#10
0
def generate_book_quote_fc(word: str, example: str,
                           model: genanki.Model) -> genanki.Note:
    question = '<i>' + copy(example) + '</i><br><br>' + 'book quote'
    question = question.replace(word, '_' * len(word))
    answer = copy(example)
    answer = answer.replace(word, '<b>' + word + '</b>')
    return genanki.Note(model=model, fields=[question, answer])
示例#11
0
def generate_example_fc(word: str, example: str, definition: str,
                        model: genanki.Model) -> genanki.Note:
    question = '<i>' + copy(example) + '</i>'
    question = question.replace(word, '<b>' + word + '</b>')
    question += ('<br><br><b>' + word + '</b> int this context means..')
    answer = copy(definition)
    return genanki.Note(model=model, fields=[question, answer])
示例#12
0
def create_deck(words, lang, deckfile):
    name = "Kindle " + lang_names[lang] + " words"
    deck = genanki.Deck(2059400110, name)
    model = genanki.Model(
        1607392319,
        'Word',
        fields=[{
            'name': 'Question'
        }, {
            'name': 'Answer'
        }, {
            'name': 'Usage'
        }],
        templates=[{
            'name':
            'Card 1',
            'qfmt':
            '{{Question}}',
            'afmt':
            '<b>{{FrontSide}}</b>: {{Answer}}<hr id="usage">{{Usage}}'
        }])

    for w in words:
        note = genanki.Note(
            model=model, fields=[w, words[w]['definition'], words[w]['usage']])
        deck.add_note(note)

    genanki.Package(deck).write_to_file(deckfile)
示例#13
0
def create_note(position, situation, hand, action, tag):
    return genanki.Note(model=model,
                        fields=[
                            position, situation, hand,
                            convert_action_to_human_readable(action)
                        ],
                        tags=[tag])
示例#14
0
def add_note_anki_deck(deck, q_text, a_text):
    """Adds a note to a genanki deck object.

    Args:
        deck (genanki Deck)
        q_text (string)
        a_text (string)
    """
    # Basic anki note model
    model_id = random.randrange(1 << 30, 1 << 31)
    my_model = genanki.Model(model_id,
                             'Simple Model',
                             fields=[
                                 {
                                     'name': 'Question'
                                 },
                                 {
                                     'name': 'Answer'
                                 },
                             ],
                             templates=[
                                 {
                                     'name':
                                     'Card 1',
                                     'qfmt':
                                     '{{Question}}',
                                     'afmt':
                                     '{{FrontSide}}<hr id="answer">{{Answer}}',
                                 },
                             ])

    my_note = genanki.Note(model=my_model, fields=[q_text, a_text])
    deck.add_note(my_note)
    print(f'Added note: q_text: {q_text}, a_text: {a_text}')
示例#15
0
def test_ok():
    my_model = genanki.Model(1376484377,
                             'Simple Model',
                             fields=[
                                 {
                                     'name': 'Question'
                                 },
                                 {
                                     'name': 'Answer'
                                 },
                             ],
                             templates=[
                                 {
                                     'name':
                                     'Card 1',
                                     'qfmt':
                                     '{{Question}}',
                                     'afmt':
                                     '{{FrontSide}}<hr id="answer">{{Answer}}',
                                 },
                             ])

    my_note = genanki.Note(model=my_model,
                           fields=['Capital of Argentina', 'Buenos Aires'])

    with pytest.warns(None) as warn_recorder:
        my_note.write_to_db(mock.MagicMock(), mock.MagicMock(),
                            mock.MagicMock(), mock.MagicMock())

    # Should be no warnings issued.
    assert not warn_recorder
示例#16
0
def createKard(Name, Inhalt):
    my_model = genanki.Model(
        random.randrange(1 << 30, 1 << 31),
        'PythonAutomatedCards',
        fields=[
            {'name': 'Definition'},
            {'name': 'Answer'},
        ],
        templates=[
            {
            'name': 'Card 1',
            'qfmt': '{{Question}}',
            'afmt': '{{FrontSide}}<hr id="answer">{{Answer}}',
            },
    ])
    my_deck = genanki.Deck(random.randrange(1 << 30, 1 << 31), Name)

    for i in Inhalt:
        Header = i['Header']
        Text = i['Text']
        # print(Header + " --> " + Text)

        my_note = genanki.Note(
            model=my_model,
            fields=[Header, Text]
        )
        my_deck.add_note(my_note)
    print("Deck: " + Name + " -> " + str(len(Inhalt)) + " Karten erstellt")
    genanki.Package(my_deck).write_to_file(Name + '.apkg')
    pass
示例#17
0
def create_anki_package(output, cards, deck_name):

    # Assign cards to an existing deck name, otherwise
    # generate a new id and persist this into the model
    # dictionary
    if deck_name in deck_id_list:
        pass
    else:
        # TODO: add a new dictionary value with a key
        pass

    deck_id = deck_id_list[deck_name]

    my_deck = genanki.Deck(deck_id, deck_name)

    model_id = model_ids[deck_name]
    model = anki_model(model_id)

    for word in cards:
        note = genanki.Note(sort_field=1,
                            model=model,
                            fields=[word.word, word.pinyin, word.definition])
        my_deck.add_note(note)

    output_location = os.path.join(output, "testOutput.apkg")
    genanki.Package(my_deck).write_to_file(output_location)
示例#18
0
    def as_anki_deck(self):
        model = genanki.Model(
            self.id,
            "{} model".format(self.title),
            fields=[
                {
                    "name": "Question"
                },
                {
                    "name": "Answer"
                },
            ],
            templates=[
                {
                    "name": "Card 1",
                    "qfmt": "{{Question}}",
                    "afmt": '{{FrontSide}}<hr id="answer">{{Answer}}',
                },
            ],
        )

        anki_deck = genanki.Deck(self.id, self.title)

        for card in self.cards:
            note = genanki.Note(model=model,
                                fields=[card.front,
                                        card.render_back()])
            anki_deck.add_note(note)

        return anki_deck
示例#19
0
    def run(self):
        deck = genanki.Deck(1596048154, "Tests DGT")
        pack = genanki.Package(deck)

        for question in Question.select():
            note_question = f'<p>{question.text}</p><ul>'
            for answer in question.answers:
                note_question += f'<li><strong>{answer.letter})</strong> {answer.text}</li>'
            note_question += '</ul>'

            self.logger.info("Creating note: %s", note_question)

            note_answer = f'<p><strong>{question.correct_answer}</strong></p>'

            # Media files should have unique filenames.
            image_media_path = get_crawl_image_media_path(question.image)
            note_image = f'<img src="{os.path.basename(image_media_path)}"/>'
            pack.media_files.append(image_media_path)

            note = genanki.Note(
                model=test_model,
                fields=[
                    note_question,
                    note_answer,
                    note_image,
                ],
            )
            deck.add_note(note)

        self.logger.info("Packing...")
        pack.write_to_file(f"{settings.DATA_PATH}/tests-dgt.apkg")
        self.logger.info("Done")
示例#20
0
    def test_media_files_absolute_paths(self):
        # change to a scratch directory so we can write files
        os.chdir(tempfile.mkdtemp())
        media_dir = tempfile.mkdtemp()

        deck = genanki.Deck(123456, 'foodeck')
        note = genanki.Note(TEST_MODEL, [
            'question [sound:present.mp3] [sound:missing.mp3]',
            'answer <img src="present.jpg"> <img src="missing.jpg">'
        ])
        deck.add_note(note)

        # populate files with data
        present_mp3_path = os.path.join(media_dir, 'present.mp3')
        present_jpg_path = os.path.join(media_dir, 'present.jpg')
        with open(present_mp3_path, 'wb') as h:
            h.write(VALID_MP3)
        with open(present_jpg_path, 'wb') as h:
            h.write(VALID_JPG)

        self.import_package(
            genanki.Package(deck,
                            media_files=[present_mp3_path, present_jpg_path]))

        missing, unused, invalid = self.check_media()
        assert set(missing) == {'missing.mp3', 'missing.jpg'}
示例#21
0
def test_warns_on_invalid_html_tags():
    my_model = genanki.Model(1376484377,
                             'Simple Model',
                             fields=[
                                 {
                                     'name': 'Question'
                                 },
                                 {
                                     'name': 'Answer'
                                 },
                             ],
                             templates=[
                                 {
                                     'name':
                                     'Card 1',
                                     'qfmt':
                                     '{{Question}}',
                                     'afmt':
                                     '{{FrontSide}}<hr id="answer">{{Answer}}',
                                 },
                             ])

    my_note = genanki.Note(model=my_model,
                           fields=['Capital of <$> Argentina', 'Buenos Aires'])

    with pytest.warns(
            UserWarning,
            match='^Field contained the following invalid HTML tags.*$'):
        my_note.write_to_db(mock.MagicMock(), mock.MagicMock(),
                            mock.MagicMock(), mock.MagicMock())
示例#22
0
    def generate(self, freq):
        deck = genanki.Deck(random.randint(100000000, 200000000), self.name)

        for word in list(freq):
            w = self.cur.execute("SELECT * FROM stardict WHERE word = '%s'" %
                                 word).fetchone()
            if not w:
                continue
            idx = w[0]
            word = w[1]
            sw = w[2]
            phonetic = w[3] if w[3] else ""
            definition = w[4] if w[4] else ""
            translation = w[5] if w[5] else ""
            pos = w[6]
            collins = w[7]
            oxford = w[8]
            tag = w[9]
            bnc = w[10]
            frq = w[11]
            exchange = w[12]
            detail = w[13]
            audio = w[14]

            note = genanki.Note(model=self.model,
                                fields=[
                                    word, phonetic,
                                    self.write_html_p(translation),
                                    self.write_html_p(definition)
                                ])
            deck.add_note(note)
        genanki.Package(deck).write_to_file(self.name + '.apkg')
示例#23
0
def test_suppress_warnings(recwarn):
    my_model = genanki.Model(1376484377,
                             'Simple Model',
                             fields=[
                                 {
                                     'name': 'Question'
                                 },
                                 {
                                     'name': 'Answer'
                                 },
                             ],
                             templates=[
                                 {
                                     'name':
                                     'Card 1',
                                     'qfmt':
                                     '{{Question}}',
                                     'afmt':
                                     '{{FrontSide}}<hr id="answer">{{Answer}}',
                                 },
                             ])

    my_note = genanki.Note(model=my_model,
                           fields=['Capital of <$> Argentina', 'Buenos Aires'])

    with pytest.warns(None) as warn_recorder:
        warnings.filterwarnings(
            'ignore',
            message='^Field contained the following invalid HTML tags',
            module='genanki')
        my_note.write_to_db(mock.MagicMock(), mock.MagicMock(),
                            mock.MagicMock(), mock.MagicMock())

    assert not warn_recorder
示例#24
0
def create_definitions_cards(dictionary, text_filename):
    global article_deck
    definition_model = genanki.Model(
        1607392319,
        'Simple Model',
        fields=[
            {
                'name': 'Question'
            },
            {
                'name': 'Answer'
            },
        ],
        templates=[{
            'name': 'Card 1',
            'qfmt': '{{Question}}',
            'afmt': '{{FrontSide}}<hr id="answer">{{Answer}}',
        }, {
            'name': 'Card 2',
            'qfmt': '{{Answer}}',
            'afmt': '{{FrontSide}}<hr id="answer">{{Question}}',
        }])

    for word in dictionary:
        if dictionary[word] != 'rejected!' and dictionary[
                word] != 'alt word form used.':
            my_note = genanki.Note(model=definition_model,
                                   tags=[text_filename],
                                   fields=[
                                       word + ' (' + str(round(time.time())) +
                                       ')', dictionary[word][0]
                                   ])
            article_deck.add_note(my_note)
示例#25
0
def test_num_fields_equals_model_ok():
    m = genanki.Model(1894808898,
                      'Test Model',
                      fields=[
                          {
                              'name': 'Question'
                          },
                          {
                              'name': 'Answer'
                          },
                          {
                              'name': 'Extra'
                          },
                      ],
                      templates=[
                          {
                              'name': 'Card 1',
                              'qfmt': '{{Question}}',
                              'afmt':
                              '{{FrontSide}}<hr id="answer">{{Answer}}',
                          },
                      ])

    n = genanki.Note(
        model=m,
        fields=[
            'What is the capital of Taiwan?', 'Taipei',
            'Taipei was originally inhabitied by the Ketagalan people prior to the arrival of Han settlers in 1709.'
        ])

    n.write_to_db(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(),
                  mock.MagicMock())
示例#26
0
def create_fill_in_the_blank_cards(dictionary, article_text, text_filename):
    global article_deck
    definition_model = genanki.Model(
        1607392320,
        'Simple Model',
        fields=[
            {
                'name': 'Question'
            },
            {
                'name': 'Answer'
            },
        ],
        templates=[{
            'name': 'Card 1',
            'qfmt': '{{Question}}',
            'afmt': '{{FrontSide}}<hr id="answer">{{Answer}}',
        }])

    for word in dictionary:
        if dictionary[word] != 'rejected!' and dictionary[
                word] != 'alt word form used.':
            sentences_with_word = get_words_sentence_from_text(
                dictionary[word][1], article_text, False)
            for sentence in sentences_with_word:
                my_note = genanki.Note(
                    model=definition_model,
                    tags=[text_filename],
                    fields=[
                        sentence + ' (' + str(round(time.time())) + ')',
                        dictionary[word][1]
                    ])
                article_deck.add_note(my_note)
示例#27
0
    def create_deck(self):

        deck = genanki.Deck(2059400110, self.name_entry.get())

        fields = []
        for f in self.columns.keys():  # for each field
            fields.append({'name': f})
        model = genanki.Model(
            1607392319,
            'Word',
            fields=fields,
            templates=[{
                'name':
                'Card 1',
                'qfmt':
                '{{Question}}',
                'afmt':
                '<b>{{FrontSide}}</b>: {{Answer}}<hr id="usage">{{Usage}}'
            }])

        for w in self.parent.words:
            fields = []
            for f in self.columns.keys():  # for each field
                if f == 'Question':
                    fields.append(w)
                else:
                    fields.append(self.parent.words[w][f])
            note = genanki.Note(model=model, fields=fields)
            deck.add_note(note)

        genanki.Package(deck).write_to_file(self.file_entry.get())
示例#28
0
def test_num_fields_more_than_model_raises():
    m = genanki.Model(1894808898,
                      'Test Model',
                      fields=[
                          {
                              'name': 'Question'
                          },
                          {
                              'name': 'Answer'
                          },
                      ],
                      templates=[
                          {
                              'name': 'Card 1',
                              'qfmt': '{{Question}}',
                              'afmt':
                              '{{FrontSide}}<hr id="answer">{{Answer}}',
                          },
                      ])

    n = genanki.Note(
        model=m,
        fields=[
            'What is the capital of Taiwan?', 'Taipei',
            'Taipei was originally inhabitied by the Ketagalan people prior to the arrival of Han settlers in 1709.'
        ])

    with pytest.raises(ValueError):
        n.write_to_db(mock.MagicMock(), mock.MagicMock(), mock.MagicMock(),
                      itertools.count(int(time.time() * 1000)))
示例#29
0
def gen_card(deck, front, back):
    my_model = genanki.Model(1607392319,
                             'Simple Model',
                             fields=[
                                 {
                                     'name': 'Question'
                                 },
                                 {
                                     'name': 'Answer'
                                 },
                             ],
                             templates=[
                                 {
                                     'name':
                                     'Card 1',
                                     'qfmt':
                                     '{{Question}}',
                                     'afmt':
                                     '{{FrontSide}}<hr id="answer">{{Answer}}',
                                 },
                             ])

    my_note = genanki.Note(model=my_model, fields=[front, back])

    deck.add_note(my_note)
    return deck
示例#30
0
def add_img_note_anki_deck(deck, q_file, a_file):
    """adds an image note to a genanki Deck

    Args:
        deck (genanki Deck)
        q_file (string): Path of question image
        a_file (string): Path of answer image
    """
    model_id = random.randrange(1 << 30, 1 << 31)
    my_model = genanki.Model(
        model_id,
        'Simple Model with Media',
        fields=[
            {
                'name': 'QuestionImage'
            },
            {
                'name': 'AnswerImage'
            },
        ],
        templates=[
            {
                'name': 'Card 1',
                'qfmt': '{{QuestionImage}}',
                'afmt': '{{FrontSide}}<hr id="answer">{{AnswerImage}}',
            },
        ])
    my_note = genanki.Note(
        model=my_model,
        fields=[f"<img src={q_file.name}>", f"<img src={a_file.name}>"])
    deck.add_note(my_note)
    print(f'-Added note with q_img: {q_file.name}, a_img: {a_file.name}')