This repository has been archived by the owner on Feb 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pycards.py
301 lines (252 loc) · 9.62 KB
/
pycards.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# -*- coding: utf-8 -*-
import sqlite3
import time
import logging
import os
__version__ = '0.4'
LEITNER_BOXES = 5
def setup_logger(logfile, loglevel):
"""Setup the logger
arguments:
logfile - file to log to, None for stdout
loglevel - level to log in
"""
f = '%(levelno)s\t%(lineno)d\t%(asctime)s\t%(message)s'
loglevel = {'INFO': logging.INFO, 'DEBUG': logging.DEBUG}.get(
loglevel, logging.WARNING)
if logfile is None:
logging.basicConfig(format=f, level=loglevel)
else:
logging.basicConfig(format=f, filename=logfile, level=loglevel)
logging.debug('Logger initialized')
def get_db(database):
"""Helper function to start the database and initialize if necessary
arguments:
database - filepath for the sqlite databasae file
returns: (sqlite-object, sqlite-cursor)
"""
try:
os.makedirs(os.path.dirname(database))
except OSError as e:
if e.errno != 17:
raise e
sq = sqlite3.connect(database)
logging.debug('Connected with database at {}'.format(database))
c = sq.cursor()
q = 'CREATE TABLE IF NOT EXISTS decks (date TEXT, name TEXT UNIQUE)'
logging.info('Creating decks table')
logging.debug('With query: {}'.format(q))
c.execute(q)
return sq, sq.cursor()
def close_db(database):
database.commit()
database.close()
def get_word_db(name):
return '"words_{}"'.format(name)
def get_stat_db(name):
return '"stat_{}"'.format(name)
def list_decks(database, deckname):
"""List the decks optionally with their entries
arguments:
database - filepath for the sqlite database file
deckname - list of decknames to list. If empty all decks are listed.
returns: [deck]
where deck = {name, date_added, entries}
where entries = [(a, b, times, times_correct, box)]
"""
logging.info('list decks... with names: {}'.format(deckname))
sq, c = get_db(database)
decks = []
q = 'SELECT rowid, name, date FROM decks'
logging.info('getting deck information')
logging.debug('with query: {}'.format(q))
datenames = list(c.execute(q))
for id_, name, date in datenames:
if not deckname or name in deckname:
decks.append({'name': name, 'date_added': float(date),
'entries': []})
q = 'SELECT * FROM {}'.format(get_word_db(id_))
logging.info('getting entries information')
logging.debug('with query: {}'.format(q))
for entry in c.execute(q):
decks[-1]['entries'].append(entry)
close_db(sq)
return decks
def load_from_file(lines, database, deckname):
"""Import a deck from a file
arguments:
lines - generator for lines of input
database - filepath for the sqlite database file
deckname - name of the deck to load in in
"""
logging.info('load from file...')
sq, c = get_db(database)
q = 'INSERT OR IGNORE INTO decks (date, name) values(?,?)'
logging.info('inserting info in deck table')
logging.debug('with query: {}'.format(q))
c.execute(q, (time.time(), deckname))
lastrowid = c.lastrowid
dbname = get_word_db(lastrowid)
q = 'CREATE TABLE IF NOT EXISTS {} (a TEXT, b TEXT,'\
'times INTEGER, times_correct INTEGER, box INTEGER)'.format(dbname)
logging.info('creating deck table')
logging.debug('with query: {}'.format(q))
c.execute(q)
dbname2 = get_stat_db(lastrowid)
q = ('CREATE TABLE IF NOT EXISTS {} (date INTEGER, correct INTEGER, '
'grade TEXT, finished INTEGER)').format(dbname2)
logging.info('creating statistics table')
logging.debug('with query: {}'.format(q))
c.execute(q)
logging.info('inserting from {}'.format(lines))
for line in lines:
if line[0] != '#':
splits = line.strip().split('\t')
if len(splits) < 2:
logging.warning('line doesn\'t consist of two tab separated '
'fields... Skipping')
continue
if len(splits) > 2:
logging.warning(
'line has more columns... discarding extra columns...')
q = ('INSERT OR IGNORE INTO {} (a, b, times, times_correct, box) '
'values(?,?,0,0,1)').format(dbname)
logging.debug('inserting entry\nwith query: {}'.format(q))
c.execute(q, splits[:2])
sq.commit()
sq.close()
def remove_deck(database, deckname):
"""Remove a deck from the database
arguments:
database - filepath for the sqlite database file
deckname - name of the deck to load in in
returns: number of decks removed
"""
logging.info('remove deck...')
sq, c = get_db(database)
q = 'SELECT rowid FROM decks WHERE name = ?'
logging.info('finding matching tables')
logging.info('with query: {}'.format(q))
num = 0
for (id_,) in list(c.execute(q, (deckname,))):
q = 'DROP TABLE {}'.format(get_word_db(id_))
logging.info('removing deck table: {}'.format(id_))
logging.debug('with query: {}'.format(q))
c.execute(q)
q = 'DROP TABLE {}'.format(get_stat_db(id_))
logging.info('removing statistics table: {}'.format(id_))
logging.debug('with query: {}'.format(q))
c.execute(q)
q = 'DELETE FROM decks WHERE rowid={}'.format(id_)
logging.info('removing deck entry: {}'.format(id_))
logging.debug('with query: {}'.format(q))
c.execute(q)
num += 1
sq.commit()
sq.close()
return num
def export_deck(database, deckname):
"""Export a deck from the database
arguments:
database - filepath for the sqlite database file
deckname - name of the deck to load in in
yields: lines
"""
logging.info('exporting deck...')
sq, c = get_db(database)
logging.info('getting deck information')
decks = list_decks(database, [deckname])
if not decks:
logging.warning('deck not found')
else:
for entry in decks[0]['entries']:
if entry:
s = '{}\t{}\n'.format(entry[0], entry[1])
logging.debug('yielding: {}'.format(s))
yield s
class Session:
def __init__(self, database, inverse, random, leitner, deckname):
self.sq, self.c = get_db(database)
self.entries = []
self.cur = None
q = 'SELECT rowid FROM decks WHERE name = ?'
logging.info('finding deck with name: {}'.format(deckname))
logging.debug('with query: {}'.format(q))
deck = list(self.c.execute(q, (deckname,)))
logging.info('found: {}'.format(deck))
times = 0
if not deck:
logging.warning('No deck with that name')
return
else:
rowid = deck[0][0]
self.deckdb = get_word_db(rowid)
self.statdb = get_stat_db(rowid)
q = 'SELECT rowid, {}, times, times_correct, box FROM {}'.format(
'b, a' if inverse else 'a, b', self.deckdb)
if leitner:
q += ' WHERE box = 0'
for i in range(1, 5):
if times % i == 0:
q += ' OR box = {}'.format(i)
if random:
logging.info('randomize questions...')
q += ' ORDER BY Random()'
logging.debug('with query: {}'.format(q))
self.entries += list(self.c.execute(q))
logging.debug('entries testing: {}'.format(self.entries))
self.all_answers = len(self.entries)
self.correct_answers = 0
def __iter__(self):
return self
def __next__(self):
if self.entries:
self.cur = self.entries.pop(0)
return self.cur[1]
else:
logging.info('no entries left, writing stats')
raise StopIteration
def answer_current(self, answer):
if self.cur is None:
logging.warning('Nothing to be answered, nothing has been asked')
self.answer = self.cur[2]
logging.info('comparing "{}" with "{}"'.format(answer, self.answer))
correct = answer == self.answer
if correct:
p = (self.cur[3]+1, self.cur[4]+1,
min(self.cur[5]+1, LEITNER_BOXES), self.cur[0])
self.correct_answers += 1
else:
p = (self.cur[3]+1, self.cur[4],
max(self.cur[5]-1, 0), self.cur[0])
logging.info('updating word')
q = 'UPDATE {} SET times=?, times_correct=?, box=? WHERE rowid=?'.\
format(self.deckdb)
logging.debug('with query: {}'.format(q))
self.c.execute(q, p)
self.cur = None
return correct
def write_stats(self, total=True):
logging.debug('writing statistics')
mark = float((self.correct_answers/float(self.all_answers))*100.0)
logging.debug('closing db')
q = ('INSERT OR IGNORE INTO {} (date, correct, grade, finished) '
'values(?,?,?,?)').format(self.statdb)
logging.info('added statistics row in deck table')
logging.debug('with query: {}'.format(q))
self.c.execute(q, (time.time(), self.correct_answers, str(mark),
1 if total else 0))
close_db(self.sq)
return mark
def session(database, deckname, inverse, random, leitner):
"""Start a session
arguments:
database - filepath for the sqlite database file
deckname - name of the deck to list, if None all decks are shown
inverse - flag for inversing question and answer
random - flag for randomizing questions
leitner - flag for using leitner system.
returns: Session object
"""
logging.info('starting session')
return Session(database, inverse, random, leitner, deckname)