-
Notifications
You must be signed in to change notification settings - Fork 0
/
flashcards.py
executable file
·243 lines (190 loc) · 7.97 KB
/
flashcards.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
#!/opt/local/bin/python2.7
'''
Make pdf flashcards for printing on Moo MiniCards.
'''
# 2017-07-25 - Shaun L. Cloherty <[email protected]>
import os, sys, csv;
from reportlab.pdfgen import canvas;
from reportlab.lib.units import mm;
from reportlab.pdfbase import pdfmetrics;
from reportlab.pdfbase.ttfonts import TTFont;
from reportlab.lib.colors import Color;
from argparse import ArgumentParser;
import argparse;
import logging;
class MooMini(object):
# Moo MiniCard dimensions are as follows:
#
# bleed: 74x32mm
# trim: 72x30mm (i.e., finished size)
# safe: 66x24mm
#
# Min. line thickness is 0.5pt.
def __init__(self,filename):
self.filename = filename;
self.width = 74.0; # mm
self.height = 32.0;
self.margin = 4.0; # mm
self.showBleed = False;
# create the canvas object
self.canvas = canvas.Canvas(filename,pagesize=(self.width*mm,self.height*mm));
self.canvas.translate(self.margin*mm,self.margin*mm);
def drawBleed(self):
# draw bleed boundary
red15 = Color(1.0,0.0,0.0,alpha = 0.15);
self.canvas.saveState();
self.canvas.translate(-1*self.margin*mm,-1*self.margin*mm);
self.canvas.setStrokeColor(red15);
self.canvas.setLineWidth(self.margin*mm);
self.canvas.rect(0.5*self.margin*mm,0.5*self.margin*mm,(self.width-self.margin)*mm,(self.height-self.margin)*mm,stroke=1,fill=0);
self.canvas.restoreState();
def save(self):
self.draw();
self.canvas.save();
class FlashCard(MooMini):
# Class for creating a flashcard suitable for printing on Moo MiniCards
def __init__(self,filename,txt,head = [],foot = []):
super(FlashCard,self).__init__(filename);
self.txt = txt;
self.head = head;
self.foot = foot;
self.gray = Color(0.7,0.7,0.7);
self.fontSize = 24;
def drawHeader(self,head):
self.canvas.saveState();
self.canvas.translate(0+1,(self.height-2*self.margin)*mm);
self.canvas.setFont("Helvetica-Italic",10);
self.canvas.setFillColor(self.gray);
self.canvas.drawString(0,-10,head);
self.canvas.restoreState();
def drawFooter(self,foot):
self.canvas.saveState();
self.canvas.translate((self.width-2*self.margin)*mm-1,0.0);
self.canvas.setFont("Helvetica-Italic",10);
self.canvas.setFillColor(self.gray);
self.canvas.drawRightString(0,0,foot);
self.canvas.restoreState();
def drawText(self,txt):
self.canvas.saveState();
self.canvas.translate((0.5*self.width-self.margin)*mm,(0.5*self.height-self.margin)*mm);
self.canvas.setFont("Helvetica-Bold",self.fontSize);
self.canvas.drawCentredString(0,-8,txt);
self.canvas.restoreState();
def draw(self):
self.drawHeader(self.head);
self.drawText(self.txt);
self.drawFooter(self.foot);
if self.showBleed:
self.drawBleed();
self.canvas.showPage();
class ZigZag(MooMini):
def __init__(self,filename,label = "",colour = Color(0.5,0.5,0.5)):
super(ZigZag,self).__init__(filename);
self.label = label;
self.colour = colour;
self.lineWidth = 1.5; # pt
self.red = Color();
def draw(self):
# draw the zig-zag pattern
x = int(round(0.5*self.width/5)*5+10);
x = range(-1*x,x,5);
y = [2*(k % 2)-1 for k in x];
y0 = int(round(0.5*self.height))+10;
self.canvas.saveState();
self.canvas.setLineWidth(self.lineWidth);
self.canvas.setLineCap(1); # 1 = round cap, 2 = square cap
self.canvas.setStrokeColor(self.colour);
self.canvas.translate((0.5*self.width-self.margin)*mm,(0.5*self.height-self.margin)*mm); # center
self.canvas.saveState();
self.canvas.translate(0.0,-1*y0*mm); # bottom
for jj in range(0,2*y0,1):
self.canvas.translate(0.0,1.5*mm);
for ii in range(len(x)-1):
self.canvas.line(x[ii]*mm,y[ii]*mm,x[ii+1]*mm,y[ii+1]*mm);
self.canvas.restoreState(); # center
# draw the label
self.canvas.setFillColor(Color(1.0,1.0,1.0)); # white
self.canvas.circle(0.0,0.0,10*mm+2,stroke=0,fill=1);
self.canvas.circle(0.0,0.0,10*mm,stroke=1,fill=1);
self.canvas.setFillColor(self.colour);
self.canvas.circle(0.0,0.0,10*mm-2,stroke=0,fill=1);
self.canvas.setFillColor(Color(1.0,1.0,1.0)); # white
self.canvas.setFont("Helvetica-Italic",12);
self.canvas.drawCentredString(0,-4,self.label);
self.canvas.restoreState();
def main(args):
logging.basicConfig(stream = sys.stderr,
format='%(levelname)s:%(message)s',
level = args.loglevel or logging.INFO);
logging.debug("args = %s", args);
logging.debug("path = %s", getattr(args,"path"));
# register TrueType fonts for embedding... as required by moo.com
# pdfmetrics.registerFont(TTFont('Helvetica','Helvetica.ttf'));
pdfmetrics.registerFont(TTFont('Helvetica-Bold','HelveticaBold.ttf'));
pdfmetrics.registerFont(TTFont('Helvetica-Italic','HelveticaOblique.ttf'));
with getattr(args,'csvfile') as fid:
# import pdb; pdb.set_trace();
logging.info("Reading input from %s...", fid.name);
dialect = 'excel';
# note: cannot seek() on stdin, so don't attempt to
# determine the dialect and just use the default
# 'excel' dialect
if fid is not sys.stdin:
logging.info('Sniffing csv dialect...');
dialect = csv.Sniffer().sniff(fid.read(2*1024));
# dialect.skipinitialspace = True;
# csv.register_dialect(ns,dialect)
fid.seek(0); # reset file pointer?
reader = csv.DictReader(fid,dialect=dialect);
cnt = 0; mx = ""; imx = 0;
for row in reader:
logging.debug("%i:row = %s", cnt, row);
rank = row["Rank:"]; # rank
word = row["Word:"]; # word
if len(rank) == 0:
rank = 0;
fname = "{0}_{1}.pdf".format(rank,word);
fname = os.path.join(getattr(args,'path'),fname);
myCard = FlashCard(fname,word,"",rank);
# myCard.showBleed = True;
myCard.save();
cnt = cnt + 1;
logging.info("Ok. Wrote %i cards.", cnt);
return(0);
if __name__ == "__main__":
prog = os.path.basename(sys.argv[0]);
rev = 0.1; # increment this if modifying the script
version = "%s v%s" % (prog, rev);
p = ArgumentParser(usage = "%(prog)s [options] PATH",
description = __doc__,
conflict_handler = "resolve");
# add arguments here
p.add_argument("--version", action = "version", version = version);
# control debugging output/verbosity
group = p.add_mutually_exclusive_group();
group.add_argument("-v","--verbose",
action = "store_const", const = logging.DEBUG,
dest = "loglevel",
help = "increase verbosity");
group.add_argument("-q","--quiet",
action = "store_const", const = logging.WARN,
dest = "loglevel",
help = "suppress non-error messages");
# optional arguments
p.add_argument("path", action = "store",
help = argparse.SUPPRESS);
# required arguments
p.add_argument("-i","--input",
action = 'store', type = argparse.FileType('r', 0),
default = sys.stdin,
metavar = "FILE",
dest = "csvfile",
help = "read text from FILE in csv format");
# p.add_argument("-o","--output",
# action = 'store',
# default = ".",
# metavar = "PATH",
# dest = "path",
# help = "save output in PATH");
args = p.parse_args();
exit(main(args));