-
Notifications
You must be signed in to change notification settings - Fork 0
/
make-flashcards.kt
executable file
·204 lines (187 loc) · 7.57 KB
/
make-flashcards.kt
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
//usr/bin/env [ $0 -nt $0.jar ] && kotlinc -d $0.jar $0; [ $0.jar -nt $0 ] && java -cp $CLASSPATH:$0.jar Make_flashcardsKt "$@"; exit 0
val usage = """
usage: make-flashcards.kt [ help | test ]
reads from stdin
lines containing a journal header start a new piece
lines starting with == start a new section
each line describes a flashcard with the question and answer separated by a colon
blank lines are ignored
writes to xxx.png, where xxx is the flashcard sequence number
"""
val fields = arrayOf(
arrayOf("structure", "metre", "tempo", "tonic"),
arrayOf("lyrics", "rhythm", "melody", "mechanics", "dynamics"),
arrayOf("lyrics-variation", "rhythm-variation", "melody-variation"))
val headerRegex = Regex("^[0-9A-Z_]{13} \\|.*$")
val separatorRegex = Regex(":[^ ]*")
data class Card(
val question: String,
val answer: String,
)
fun main(args: Array<String>) {
if (args.isEmpty()) {
println("Ready")
processStdin()
} else {
when (args[0]) {
"test" -> test()
"help" -> print(usage)
else -> print(usage)
}
}
}
fun processStdin() {
var song = ""
var songs = 0
var lines = 0
var section = ""
var sections = 0
System.`in`.bufferedReader().lines().forEach { line ->
if (line.matches(headerRegex)) {
song = line.drop(17).takeWhile { it != '/' && it != '@' }.trim().replace(" ", "-")
songs++
sections = 0
} else if (line.startsWith("==")) {
section = line.drop(2).lowercase()
sections++
lines = 0
} else if (line.isNotBlank()) {
lines++
/* one flashcard per field */
line.parseUnlabelledCards().forEachIndexed { i, card ->
if (card.answer.isNotBlank()) {
val field = fields[sections - 1][i]
val dir = "cards" //00.$song" // "$sections$i.$field"
//val seq = "99.%s.%d%d%02d".format(song, sections, i, lines)
val seq = "%s.%d%02d%d".format(song.take(4), sections, lines, i)
mkdir(dir)
makeTextFlashcards(card, song, field, dir, seq)
}
}
/* one flashcard per line
val question = line.takeWhile { it != ':' }
val answer = line.drop(question.length + 1)
val dir = "$sections.$section"
val seq = "00%d%02d%02d".format(sections, songs, lines)
mkdir(dir)
makeFlashcard(Card(question, answer), song, section, "$dir/$seq.$song.png")
*/
}
}
}
fun def_parseUnlabelledCards() {
"".parseUnlabelledCards() returns listOf<Card>()
"foo: bar".parseUnlabelledCards() returns listOf(Card("foo", "bar"))
"foo : bar".parseUnlabelledCards() returns listOf(Card("foo", "bar"))
"foo : bar : baz".parseUnlabelledCards() returns
listOf(Card("foo", "bar"), Card("foo : bar", "baz"))
"foo : bar : baz : zap".parseUnlabelledCards() returns
listOf(Card("foo", "bar"), Card("foo : bar", "baz"), Card("foo : bar : baz", "zap"))
}
fun String.parseUnlabelledCards(): List<Card> {
val parts = split(":")
if (parts.size < 2) {
return emptyList<Card>()
} else {
var result = mutableListOf<Card>()
var question = StringBuilder(parts[0].trim())
parts.drop(1).forEach {
val answer = it.trim()
result.add(Card(question.toString(), answer))
question.append(" : ").append(answer)
}
return result
}
}
fun def_parseLabelledCards() {
"".parseLabelledCards() returns listOf<Card>()
"foo: bar".parseLabelledCards() returns listOf(Card("foo", "bar"))
"foo : bar".parseLabelledCards() returns listOf(Card("foo", "bar"))
"foo :label bar".parseLabelledCards() returns listOf(Card("foo :label", "bar"))
"foo:label bar".parseLabelledCards() returns listOf(Card("foo :label", "bar"))
"foo : bar : baz".parseLabelledCards() returns
listOf(Card("foo :1", "bar"), Card("foo :2", "baz"))
"foo: bar :label baz".parseLabelledCards() returns
listOf(Card("foo :1", "bar"), Card("foo :label", "baz"))
"foo : bar :label baz".parseLabelledCards() returns
listOf(Card("foo :1", "bar"), Card("foo :label", "baz"))
"foo :label bar : baz".parseLabelledCards() returns
listOf(Card("foo :label", "bar"), Card("foo :2", "baz"))
}
fun String.parseLabelledCards(): List<Card> {
val separators = separatorRegex.findAll(this).map { it.range }.toList()
if (separators.isEmpty()) {
return emptyList<Card>()
} else {
val baseQuestion = take(separators[0].first).trim() + " "
return separators.mapIndexed { i, range ->
val question = baseQuestion + if (range.count() > 1) {
drop(range.first).take(range.count())
} else if (separators.size > 1) {
":" + (i + 1)
} else {
""
}
val answer = if (i == separators.lastIndex) {
drop(range.last + 1)
} else {
drop(range.last + 1).take(separators[i + 1].first - range.last - 1)
}
Card(question.trim(), answer.trim())
}
}
}
fun mkdir(dir: String) = java.io.File(dir).mkdir()
fun String.escape() = replace("\\", "\\\\")
// export a record as a png flashcard suitable for nokia phones
fun makeFlashcard(card: Card, heading: String, field: String, filename: String) {
val question = "$heading\n$field\n${card.question.wrap(15)}".escape()
val answer = card.answer.wrap(15).escape()
Runtime.getRuntime().exec(arrayOf(
"convert", "-size", "240x320", "xc:black",
"-font", "FreeMono-Bold", "-pointsize", "24",
"-fill", "white", "-annotate", "+12+24", question,
"-fill", "yellow", "-annotate", "+12+185", answer,
"$filename"))
}
// export a record as a text flashcard suitable for nokia phones
fun makeTextFlashcards(card: Card, heading: String, field: String, dir: String, seq: String) {
val question = "$heading\n${card.question}\n[$field]".replace(" : ", "\n")
val answer = "$heading\n${card.question}\n${card.answer}".replace(" : ", "\n")
java.io.File(dir + "/${seq}A.txt").writeText(question)
java.io.File(dir + "/${seq}B.00.txt").writeText(answer)
}
val TEXT_FLASHCARD_PAGE_SIZE = 160
val EM_SPACE = '\u2003'
fun def_wrap() {
"12345".wrap(1) returns "1\n2\n3\n4\n5"
"12345".wrap(2) returns "12\n34\n5"
"12345".wrap(5) returns "12345"
"12345".wrap(6) returns "12345"
"1\n2345".wrap(2) returns "1\n23\n45"
"12\n345".wrap(2) returns "12\n34\n5"
"12\n345".wrap(3) returns "12\n345"
}
fun String.wrap(width: Int): String {
var i = 0
return asSequence().fold(StringBuilder()) { acc, ch ->
if (i > 0 && i % width == 0 && ch != '\n') acc.append("\n")
if (ch == '\n') i = 0 else i++
acc.append(ch)
}.toString()
}
// simple test functions, since kotlin.test is not on the default classpath
fun test(klass: Class<*> = ::test.javaClass.enclosingClass, prefix: String = "def_") {
klass.declaredMethods.filter { it.name.startsWith(prefix) }.forEach { it(null) }
}
infix fun Any?.returns(result: Any?) {
if (this != result) throw AssertionError("Expected: $result, got $this")
}
infix fun (() -> Any).throws(ex: kotlin.reflect.KClass<out Throwable>) {
try {
invoke()
throw AssertionError("Exception expected: $ex")
} catch (e: Throwable) {
if (!ex.java.isAssignableFrom(e.javaClass)) throw AssertionError("Expected: $ex, got $e")
}
}