Skip to content
This repository has been archived by the owner on Aug 14, 2024. It is now read-only.

Commit

Permalink
anki: Implement anki convertor PoC
Browse files Browse the repository at this point in the history
  • Loading branch information
MatejKastak committed Dec 23, 2019
1 parent 8e872f7 commit 1c5dc7d
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 2 deletions.
65 changes: 65 additions & 0 deletions orglearn/anki/anki_convertor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import logging
import os
import random

import orgparse
import genanki

TEST_MODEL = genanki.Model(
random.randrange(1 << 30, 1 << 31),
'foomodel',
fields=[
{
'name': 'AField',
},
{
'name': 'BField',
},
],
templates=[
{
'name': 'card1',
'qfmt': '{{AField}}',
'afmt': '{{FrontSide}}'
'<hr id="answer">'
'{{BField}}',
}
],
)


class AnkiConvertor():

ANKI_EXT = '.apkg'

def __init__(self, o_file, f_list, append=False):
# TODO(mato): Implement append
self.o_file = o_file
self.f_list = f_list

# Try to deteremine output file if none was specified
if o_file is None:
root, ext = os.path.splitext(os.path.basename(f_list[0]))
o_file = root + AnkiConvertor.ANKI_EXT

# Parse the org files into 1 tree
cards = []
for f in f_list:
cur_file = orgparse.load(f)
self._get_cards(cur_file, cards)

self.anki(o_file, cards)

def anki(self, anki_out_path, cards):
my_deck = genanki.Deck(random.randrange(1 << 30, 1 << 31), anki_out_path)

for c in cards:
my_deck.add_note(c)

genanki.Package(my_deck).write_to_file(anki_out_path)

def _get_cards(self, tree_level, output_list):
for c in tree_level.children:
if not c.children:
output_list.append(genanki.Note(model=TEST_MODEL, fields=[c.heading, c.body]))
self._get_cards(c, output_list)
4 changes: 2 additions & 2 deletions orglearn/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from orglearn.map.map_convertor import MapConvertor
from orglearn.map.backend.backends import Backends
from orglearn.anki.anki_convertor import AnkiConvertor

import click

Expand Down Expand Up @@ -31,8 +32,7 @@ def anki(org_files, append, output):
print('Append specified without output flag.')
return

for f in org_files:
print('Hello, anki {}'.format(f))
c = AnkiConvertor(output, org_files, append=append)

@main.command()
@click.argument('org_files', type=click.Path(exists=True), nargs=-1)
Expand Down
3 changes: 3 additions & 0 deletions orglearn/map/backend/backend.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import abc

# TODO(mato): Consider moving changing this to Convertor base class
# it will have similiar interface, but it will output to the specified
# stream
class Backend(abc.ABC):

@abc.abstractmethod
Expand Down

0 comments on commit 1c5dc7d

Please sign in to comment.