示例#1
0
def DeckGen(name, file_path, shuffle_card, word_notes, kanji_notes):
    my_deck = genanki.Deck(random.randrange(1 << 30, 1 << 31), name)

    if shuffle_card:

        def shuffle_dict(dictionary):
            tmp = list(dictionary.items())
            random.shuffle(tmp)
            return dict(tmp)

        word_notes = shuffle_dict(word_notes)
        kanji_notes = shuffle_dict(kanji_notes)

    notes = []
    for word_note in word_notes:
        for c in word_note:
            if c in kanji_notes:
                notes.append(kanji_notes.pop(c))
        notes.append(word_notes[word_note])

    # Remaining kanji
    for kanji_note in kanji_notes:
        notes.insert(random.randrange(0, len(notes)), kanji_notes[kanji_note])

    counter = 0
    for note in notes:
        note.fields[0] = str(counter)
        counter = counter + 1
        my_deck.add_note(note)
    if len(notes) > 0:
        genanki.Package(my_deck).write_to_file(file_path)
示例#2
0
    def __call__(self, **kwargs):
        db = kwargs[self.plugin_config["in"]]
        only_kanjis = kwargs[self.plugin_config["only"]]

        model = genanki.Model(
            1607392319,
            "Simple Model",
            fields=[
                {
                    "name": "Question"
                },
                {
                    "name": "Answer"
                },
            ],
            templates=[{
                "name": "Card 1",
                "qfmt": "{{Question}}",
                "afmt": '{{FrontSide}}<hr id="answer">{{Answer}}',
            }],
        )

        deck = genanki.Deck(int(self.plugin_config["deck_id"]),
                            self.plugin_config["title"])

        notes = [generate_note(_, db.get(_, None), model) for _ in only_kanjis]
        for _ in notes:
            deck.add_note(_)

        genanki.Package(deck).write_to_file(self.plugin_config["output"])
示例#3
0
 def write_to_file_anki(self, file_name: str):
     """
     Write the anki file to a specific file
     :param file_name: The file name (Without `.apkg`)
     """
     my_package = genanki.Package(self.deck)
     # Copy files from other paths into the current directory
     files_to_delete = set()
     for file in self.files:
         for remove_file_path in remove_file_paths:
             if remove_file_path in file:
                 file_to_delete_later = file \
                     .replace(remove_file_path + '/', '')
                 copyfile(file, file_to_delete_later)
                 files_to_delete.add(file_to_delete_later)
                 self.files.remove(file)
                 self.files.add(file_to_delete_later)
     if debug:
         print("Package the following media files:", self.files)
     my_package.media_files = list(self.files)
     my_package.write_to_file(file_name + '.apkg')
     # Delete copied files
     if debug:
         print("files_to_delete", files_to_delete)
     for delete_file in files_to_delete:
         os.remove(delete_file)
示例#4
0
文件: main.py 项目: geofflittle/anki
def write_deck_to_file(path):
    basename = os.path.basename(path)
    name = os.path.splitext(basename)[0]
    deck_name = name.replace("_", " ").title()
    deck = genanki.Deck(hash(deck_name), deck_name)
    with open(path) as f:
        notes = yaml.load(f, Loader=yaml.FullLoader)
        seen = set()
        for note_data in notes:
            note_id = note_data["id"]
            note_cloze = note_data["cloze"]
            note_tags = note_data["tags"]
            if note_id in seen:
                sys.exit("duplicate id {} found".format(note_id))
            if not cloze_note_regex.match(note_cloze):
                sys.exit(
                    "note id {} with cloze '{}' doesn't match expected format".
                    format(note_id, note_cloze))
            print(note_data)
            note = genanki.Note(guid=genanki.guid_for(note_id),
                                fields=[note_cloze],
                                tags=note_tags,
                                model=genanki.CLOZE_MODEL)
            deck.add_note(note)
            seen.add(note_id)
    genanki.Package(deck).write_to_file("{}.apkg".format(name))
示例#5
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')
示例#6
0
def main():

    # read in the input json data (a flat array of objects) for our cards
    with open("resources/cards.sealang.json") as json_data:
        cards = json.load(json_data)
    # read in the mapping of card's source property to the anki collection
    # this allows for hierarchical categories in the generated deck
    with open("resources/source-map.json") as json_data:
        source_map = json.load(json_data)
    with open("resources/cards.css") as cssData:
        card_style = cssData.read()

    # defines how to use card's source property to look up the collection name in the source-map file
    # you'll probably need to rewrite this function for your specific data.
    def cardGroupFunction(card):
        prefix = card['source'].split("-")[0]
        return source_map[prefix]["source"]

    cardsBySource = itertools.groupby(cards, cardGroupFunction)
    decks = []
    model = get_model(card_style)
    for source, cards in cardsBySource:
        if source == "SKIP":
            continue
        # :: has special meaning in Anki card names: it nests decks.
        deck_name = "Thai::" + source
        print("creating... " + deck_name)
        deck = new_deck(deck_name)
        for card in distinct(cards):
            card = new_card(model, card['thai'], card['english'])
            deck.add_note(card)
        decks.append(deck)
    genanki.Package(decks).write_to_file('dist/thai.apkg')
示例#7
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")
示例#8
0
def create_deck(csv_path, language, deck_name, deck_id=None, model_id=None):
    language = language

    df = pandas.read_csv(csv_path, sep="\t")
    df.iloc[:, 0].apply(text_to_speech, language=language, path="data/audio")

    field_names = list(df)
    my_model = generate_model(model_name=language,
                              field_names=field_names,
                              identifier=model_id)
    my_deck = generate_deck(name=deck_name, identifier=deck_id)

    df.loc[:, "audiofile"] = df.iloc[:, 0].apply(text_to_filename,
                                                 prefix=f"{language}_",
                                                 suffix=".mp3")
    df.apply(lambda row: my_deck.add_note(generate_note(my_model, row.values)),
             axis=1)

    my_package = genanki.Package(my_deck)
    my_package.media_files = [
        f"data/audio/{file}" for file in list(df.audiofile)
    ]
    package_path = f"{text_to_filename(deck_name)}.apkg"
    my_package.write_to_file(package_path)
    print(f'Generated deck "{deck_name}" in "{package_path}"')
示例#9
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'}
示例#10
0
def make_anki_deck_from_srt_file(srt_file: Path, *, name: str,
                                 output_dir: Path) -> Path:
    srt_file = srt_file.absolute()
    deck = genanki.Deck(1, name)
    model = genanki.Model(
        1,
        "Simple Model",
        fields=[
            {
                "name": "Question"
            },
            {
                "name": "Answer"
            },
        ],
        templates=[{
            "name": "Card 1",
            "qfmt": "{{Question}}",
            "afmt": "{{Answer}}",
        }],
    )

    cards = make_cards_from_srt_file(srt_file)
    for card in cards:
        note = genanki.Note(model=model, fields=[card.front, card.back])
        deck.add_note(note)

    output_path = (output_dir / f"{name}.apkg").absolute()
    genanki.Package(deck).write_to_file(output_path)

    return output_path
示例#11
0
 def write_to_file(self, fn):
     if len(fn) < 6 or fn[-5:] != '.apkg':
         fn += '.apkg'
     package = genanki.Package(self.deck)
     print("Adding media files: ", self.media_files)
     package.media_files = self.media_files
     package.write_to_file(fn)
示例#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 go(deck_filename: str, url: str):
    """ Pull it all together and write the deck to a file. """
    html = get_html(url)
    soup = get_soup(html)
    methods = get_methods(soup)
    deck = make_anki_deck(methods, deck_filename)
    genanki.Package(deck).write_to_file(deck_filename + '.apkg')
示例#14
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)
示例#15
0
def main():
    '''Main function.'''

    parser = argparse.ArgumentParser()

    parser.add_argument('--regs', action='store_true')
    parser.add_argument('--prefs', action='store_true')
    parser.add_argument('--caps', action='store_true')
    parser.add_argument('--all', action='store_true')

    args = parser.parse_args()

    if args.regs:
        process_regions()

    if args.prefs:
        process_prefectures()

    if args.caps:
        process_capitals()

    if args.all:
        # To get the statistics and indices of the regions right we need
        # all the information from the prefectures first! This is written
        # to a JSON file only, use preprocess to stop the Anki output!
        process_prefectures(preprocess=True)
        process_regions()
        process_prefectures()  # Fix the indices according to the regions
        process_capitals()

    genanki.Package(PREF_DECK).write_to_file('output.apkg')
示例#16
0
    def make_notes(self,
                   rawNoteDict,
                   deck_name,
                   out_path,
                   tag,
                   include_sound=False):
        deck = genanki.Deck(2051337110, deck_name)

        self.printOrLog(
            "\nNote maker is now gathering enrichment data for the words, this may take a while, especially if you are including audio files. The scanner will update progress here every 25 words..."
        )
        i = 0
        media_paths = []
        for simp in rawNoteDict:
            if self.thread_obj != None and self.thread_obj.interrupt_and_quit == True:
                break
            i += 1
            if i % 25 == 0:
                self.printOrLog(f"{i} words enriched")
            note, media_path = self.enrich_word(rawNoteDict[simp],
                                                include_sound)
            media_paths.append(media_path)
            deck.add_note(genanki.Note(self.note_model, note, tags=[tag]))

        if self.thread_obj != None and self.thread_obj.interrupt_and_quit == True:
            return
        self.printOrLog("Note maker is making a package")
        apkg = genanki.Package(deck)
        if include_sound == True:
            apkg.media_files = media_paths
        apkg.write_to_file(out_path)
        self.printOrLog(
            f"Note maker wrote {len(rawNoteDict)} new notes to to {join(dirname(realpath(__file__)),out_path)}"
        )
示例#17
0
def main():
    '''Main function.'''

    parser = argparse.ArgumentParser()

    parser.add_argument('--regs', action='store_true')
    parser.add_argument('--states', action='store_true')
    # parser.add_argument('--caps', action='store_true')
    parser.add_argument('--all', action='store_true')

    args = parser.parse_args()

    if args.regs:
        process_regions()

    if args.states:
        process_states()

    # if args.caps:
    #     process_capitals()

    if args.all:
        process_states(preprocess=True)
        process_regions()
        process_states()
        # process_capitals()

    genanki.Package(STATE_DECK).write_to_file('states_us.apkg')
示例#18
0
def main():
    # find courses
    for kurs in [f.path for f in os.scandir(".") if f.is_dir()]:
        decks = []
        kursName = kurs[2:]
        if kursName.startswith("."):
            continue
        # find unit
        for einheit in [f.path for f in os.scandir(kurs) if f.is_dir()]:
            kursEinheit = einheit[len(kursName) + 3:]
            if kursEinheit.startswith("."):
                continue
            if kursEinheit.startswith("images"):
                generateGraphviz(kursName + "/images")
                continue
            # generate deck
            decks.append(generateDeck(kursName, kursEinheit))

        # pack decks to one project
        anki = genanki.Package(decks)
        # add images to project
        if os.path.isdir(kursName + "/images"):
            anki.media_files = [
                f.path for f in os.scandir(kursName + "/images")
                if f.is_file()
            ]

        try:
            anki.write_to_file(kursName + ".apkg")
            printSuccess("Deck {} successfully created.".format(kursName))
        except IOError:
            printError("A problem occured while creating "
                       "file: {}".format(kursName + ".apkg"))
示例#19
0
def main(args):
    video = args.video
    sub = args.sub
    styles = args.styles
    apkg = args.apkg
    name = args.name
    offset = args.offset
    crop = args.crop

    video_path = Path(video)
    subs_path = Path(sub or video_path.with_suffix(".ass"))
    apkg_path = Path(apkg or video_path.with_suffix(".apkg"))
    name = name or str(video_path.with_suffix("").name)
    tmp_path = video_path.with_suffix("")

    if not tmp_path.is_dir():
        tmp_path.mkdir()

    subs = pysubs2.load(subs_path)
    notes, media_files = create_notes(subs, video_path, tmp_path, styles,
                                      offset, crop)

    deck = genanki.Deck(deck_id=random.randrange(1 << 30, 1 << 31), name=name)

    for note in notes:
        deck.add_note(note)
    apkg = genanki.Package(deck)
    apkg.media_files = media_files
    apkg.write_to_file(apkg_path)
示例#20
0
def create_deck(source, first: str, second: str, name: str,
                header: bool, output: str):
    """Creates a new anki deck from a csv file."""

    if not os.path.exists(source):
        source = Path('../').resolve().joinpath(source)

    df: pd.DataFrame
    if header is False:
        df = pd.read_csv(source, header=None)
    else:
        df = pd.read_csv(source)

    if first.isnumeric():
        first = int(first)

    if second.isnumeric():
        second = int(second)

    output = Path(output).resolve()

    engine = DeckGenerator(model=simple_flashcard, df=df,
                           word=first, answer=second)
    my_deck = engine.generate_cards().get_deck(name)
    if name is None:
        name = 'output'
    anki.Package(my_deck).write_to_file(f'{output}/{name}.apkg')

    click.echo(f'Done creating new deck {name} at {output}.')
示例#21
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())
示例#22
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
示例#23
0
def generate_decks(token: str, output_filename: str) -> None:
    """
    Scrapes the Notion table bank, and converts them into Anki decks ready for importing.
    """
    decks = {
        BankCategory.VOCABULARY: genanki.Deck(
            deck_id=1854703173,  # Hard-coded value selected by me
            name="German::Vocabulary",
        ),
        BankCategory.PHRASE: genanki.Deck(
            deck_id=1568577201,  # Hard-coded value selected by me
            name="German::Phrases",
        ),
    }

    for german_bank_item in GermanBankNotionClient(token).load_bank_items():
        if isinstance(german_bank_item, BankWord):
            deck = decks[BankCategory.VOCABULARY]
        elif isinstance(german_bank_item, Phrase):
            deck = decks[BankCategory.PHRASE]
        else:
            raise ValueError(f"Unexpected bank item {german_bank_item}")

        german_note = GermanNote.from_german_model(german_bank_item)
        deck.add_note(german_note)

    genanki.Package(decks.values()).write_to_file(output_filename)
    click.echo(f"Complete! Now import {output_filename} to Anki, fix any changes, and sync Anki to AnkiCloud.")
示例#24
0
def main():

    my_model = genanki.Model(
        1607392328,
        'RuHamTest',
        css="""
            .card { font-family: arial; font-size: 20px; text-align: center; color: black; background-color: white; }
            ul { width: 90%; list-style-type:"A"; margin:auto; padding:0; position:relative; left:5%; }
        """,
        fields=[
            {
                'name': 'idx'
            },
            {
                'name': 'Question'
            },
            {
                'name': 'Choice1'
            },
            {
                'name': 'Choice2'
            },
            {
                'name': 'Choice3'
            },
            {
                'name': 'Choice4'
            },
            {
                'name': 'Answer'
            },
        ],
        templates=[{
            'name':
            'Card 1',
            'qfmt':
            '''
                <h2>Вопрос №{{idx}}</h2><br>
                {{Question}}<br>
                <ul type='a'>
                    <li id="1">{{ Choice1 }}</li>
                    <li id="2">{{ Choice2 }}</li>
                    <li id="3">{{ Choice3 }}</li>
                    <li id="4">{{ Choice4 }}</li>
                </ul>
            ''',
            'afmt':
            '{{FrontSide}}<script> document.getElementById("{{Answer}}").style.backgroundColor = "green"</script> ',
        }])

    my_deck = genanki.Deck(2059400143, 'Ham Test RU')

    for idx, q, c1, c2, c3, c4, a in w_list():
        my_note = genanki.Note(model=my_model,
                               fields=[idx, q, c1, c2, c3, c4, a],
                               sort_field='idx')
        my_deck.add_note(my_note)

    genanki.Package(my_deck).write_to_file('/output/hamtest.apkg')
示例#25
0
def generate_flashcards(book: Book, words: List[Word],
                        with_audio: bool) -> None:
    my_deck = genanki.Deck(2059400110, 'Vocabulary: ' + book.title)
    my_package = genanki.Package(my_deck)
    if with_audio:
        my_package.media_files = [word.audio for word in words if word.audio]

    templates = CardTemplates()

    for word in words:
        word_flashcards = generate_flashcards_from_word(
            word, templates, with_audio)
        for fs in word_flashcards:
            my_deck.add_note(fs)

    genanki.Package(my_deck).write_to_file('./Vocabulary_' + book.title +
                                           '.apkg')
示例#26
0
def insert_cards_to_deck(cards, media_files):
    my_deck = genanki.Deck(2059400201311, 'japanese_vocab')
    my_package = genanki.Package(my_deck)
    my_package.media_files = media_files
    for card in cards:
        my_deck.add_note(card)
    my_package.write_to_file('output.apkg')
    print('Package output.apkg generated')
示例#27
0
 def read_file(self, file_name: str):
     with open(file_name) as f:
         lines = f.readlines()
         for line in lines:
             word, note = line.split(";")
             word = re.sub("\([^ ]*\)", "", word)
             self.add_word_to_deck(word, note)
     genanki.Package(dutch_deck).write_to_file("dutch_deck.apkg")
示例#28
0
    def _package(self) -> genanki.Package:
        deck = genanki.Deck(id(self._title), self._title)
        media = []
        for card in self._cards:
            media += card.media()
            deck.add_note(card.export())

        return genanki.Package(deck, media_files=media)
示例#29
0
    def test_model_with_sort_field_index(self):
        deck = genanki.Deck(332211, 'foodeck')
        note = genanki.Note(TEST_MODEL_WITH_SORT_FIELD_INDEX, ['a', '3.A'])
        deck.add_note(note)

        self.import_package(genanki.Package(deck))

        anki_note = self.col.getNote(self.col.findNotes('')[0])
        assert anki_note.model()['sortf'] == CUSTOM_SORT_FIELD_INDEX
示例#30
0
    def save_anki_package(self, buckets, export_file_name):
        for bucket in buckets:
            self.__add_bucket_to_deck(bucket)

        pack = genanki.Package(self.my_deck)
        pack.media_files = self.list_of_media_files
        Helper.create_folder_if_not_exist(os.path.dirname(export_file_name))
        pack.write_to_file(export_file_name)
        print("ANKI deck saved to", export_file_name)