-
Notifications
You must be signed in to change notification settings - Fork 0
/
p_a_lilypond.py
323 lines (250 loc) · 10.1 KB
/
p_a_lilypond.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import os
import subprocess
import p_a_constants as cst
from p_a_scales_and_triads import SPEEDS, Exercises
TRANSLATIONS = {
"0": "^\\Nf",
"1": "^\\If",
"2": "^\\Mf",
"3": "^\\Rf",
"4": "^\\Pf",
"t": "^\\Tf",
"-": "",
"B": '\\clef "bass_8"\n',
"T": '\\clef "tenor_8"\n',
"V": '\\clef "violin_8"\n',
"G": '_\\Gstring ',
"D": '_\\Dstring ',
"A": '_\\Astring ',
"E": '_\\Estring ',
}
HEAD = f"""\\version "{cst.LILYPOND_VERSION}"
\\language "english"
\\include "./../lilypond/commons.ly"
"""
class Staff:
def __init__(self):
self.list = []
self.source = ''
self.has_changed = True
def append(self, t: str):
self.list.append(t)
self.has_changed = True
def concatenate(self, t: str):
self.source += t
self.has_changed = True
def add_triplets(self) -> None:
triplet_is_open = False
for i in range(len(self.list) - 1):
if i % 3 == 0 and not triplet_is_open:
self.list[i] = " \\tuplet 3/2 {" + self.list[i]
triplet_is_open = True
if i % 3 == 2 and triplet_is_open:
self.list[i] += "}"
triplet_is_open = False
if triplet_is_open:
self.list[-1] += "}"
def add_slurs(self, tempo) -> None:
slur_is_open = False
i = 0
for i, t in enumerate(self.list[:-1]):
if i % tempo == 0 and i < len(self.list) - 1 and not slur_is_open:
self.list[i] += "\\("
slur_is_open = True
if slur_is_open and (i % tempo == tempo - 1 or self.list[i + 1].startswith("r")):
self.list[i] += "\\)"
slur_is_open = False
if slur_is_open:
self.list[i] += '\\)'
def collect_rests(self):
# clean up and combination of rests
while ' ' in self.source:
self.source = self.source.replace(' ', ' ')
self.source = self.source.replace('\\tuplet 3/2 {r8 r8 r8}', 'r4')
# the replacements are done from back to front
rs = ['61r', '8r', '4r', '2r', '1r']
replaced_something = True
while replaced_something:
replaced_something = False
for n, r in zip(rs[:-1], rs[1:]):
new = self.source[::-1].replace(f'{n} {n} ', f'{r} ')[::-1]
if new != self.source:
replaced_something = True
self.source = new
break
# remove slurs without length, easier to clean than to care for while setting them, ;-)
self.source = self.source.replace('\\(\\)', '')
class Staves:
def __init__(self, exercise):
self.exercise = exercise
self.piano = Staff()
self.metronome = Staff()
@property
def has_changed(self):
return self.piano.has_changed or self.metronome.has_changed
def append(self, p_t: str, m_t: str):
self.piano.append(p_t)
self.metronome.append(m_t)
def concatenate(self, p_t: str, m_t: str):
self.piano.concatenate(p_t)
self.metronome.concatenate(m_t)
def tones_list(self, data, speed_value, current_clef):
# n_o_events is the number of music/midi events per bar
# note_value is the one of 16 = 'sixteenth', 8 = 'eights', etc.
# in most cases n_o_events=note_values but for triples
# these values are different, e.g. 12 and 8 will give triplets of eights
n_o_events, note_value = SPEEDS[speed_value]
durations = [[]]
# two lists to collect the lilypond code for two staves
# piano is for the music and metronome records events for indicating the speed at the beginning,
# in general four beats on a woodblock
staves = Staves(self.exercise)
for ton, finger, clef, string in zip(
data['pitches'], data['fingers'], data['clefs'], data['strings']):
if current_clef != clef and clef != '-':
current_clef = clef
else:
clef = '-'
if ton != "R":
ff = ""
if self.exercise.show_fingerings:
for f in finger:
ff += TRANSLATIONS[f]
else:
string = '-'
text = f"{TRANSLATIONS[clef]}{ton}{note_value}{ff}{TRANSLATIONS[string]}"
staves.append(text, f"r{note_value}")
durations[-1].append(48 // n_o_events)
else:
staves.append(f"r{note_value}", f"r{note_value}")
durations.append([-48 // n_o_events, ])
while sum([sum([abs(_d) for _d in d]) for d in durations]) % 48 != 0:
staves.append(f"r{note_value}", f"r{note_value}")
durations[-1].append(-48 // n_o_events)
durations.append([])
if len(durations[-1]) == 0:
durations.pop(-1)
if self.exercise.show_slurs:
staves.piano.add_slurs(n_o_events)
if n_o_events == 12:
staves.piano.add_triplets()
for v, m in zip(staves.piano.list, staves.metronome.list):
staves.concatenate(f" {v} ", f" {m} ")
return staves, durations
def update(self):
current_clef = 'B'
# start of each staff definition
self.piano.source = 'piano = \\new Staff \\with {midiInstrument = "acoustic grand" } {\n'
self.metronome.source = 'metronome = \\new Staff \\with {midiInstrument = "woodblock" } {\n'
text = self.exercise.music_key.replace(" ", " \\").lower()
self.piano.concatenate(' \\accidentalStyle modern-cautionary\n'
' \\tupletDown\n'
' \\override TextScript.staff-padding = # 3\n')
self.piano.concatenate(f' \\key {text}\n'
f' {TRANSLATIONS[current_clef]}'
f' \\tempo 4={self.exercise.tempo} \n'
'r1')
self.metronome.concatenate("c4 c4 c4 c4 \n")
durations = [[12, 12, 12, 12]]
# ---------------------------------------------------------------------
data = self.exercise.get_data()
bar = ''
for speed in sorted(self.exercise.speeds):
staves, _durations = self.tones_list(data, speed, current_clef)
durations += _durations
self.concatenate(bar, bar)
self.concatenate(staves.piano.source, staves.metronome.source)
bar = ' \\bar "||"\n'
if self.exercise.loop:
bar = " \\set Score.repeatCommands = #'(end-repeat) \n"
else:
bar = ' \\bar "|."\n'
self.concatenate(bar, bar)
# ---------------------------------------------------------------------
# finally:
self.concatenate("\n}\n", "\n}\n")
self.piano.collect_rests()
return durations
class Lilypond:
def __init__(self, basename: str, exercise: Exercises):
self.basename = basename
self.exercise = exercise
self.durations = None
self.footer: str = ""
self.staves = Staves(self.exercise)
self._svg_source: str = ''
self._mid_source: str = ''
self._source: str = ''
self._destination = ''
# ToDo:
# recalculate only if necessary
# @property
# def is_valid(self):
# return self._is_valid and not self.exercise.has_changed
@property
def total_duration(self):
s = [sum([abs(_d) for _d in d]) for d in self.durations]
s = sum(s)
return s
@property
def destination(self):
return self._destination
@destination.setter
def destination(self, dest):
if dest != self._destination:
self._destination = dest
self._update_footer()
@property
def source(self):
if self.staves.has_changed:
self.durations = self.staves.update()
source = HEAD
source += self.staves.piano.source
source += self.staves.metronome.source
source += self.footer
return source
def _update_footer(self) -> None:
self.footer = f'\n\\book {{\n \\bookOutputName "{self.destination}_{self.basename}"\n'
self.footer += ' \\header{ tagline = "" }\n \\score {\n'
if self.destination == 'svg':
self.footer += ' << \\piano >>\n'
self.footer += ' \\layout{ indent = 0 }\n'
if self.destination == 'midi':
self.footer += ' <<\n \\piano\n \\metronome\n >>\n \\midi { }\n'
self.footer += ' }\n}'
@staticmethod
def final_touches(output):
# not really necessary but makes the lilypond code look a bit nicer to read
output = output.replace('\n', ' ')
while ' ' in output:
output = output.replace(' ', ' ')
# put back some line breaks
output = output.replace('}', '}\n')
output = output.replace('\\new', '\n\\new')
output = output.replace('\\relative', '\n\\relative')
output = output.replace('\\key', '\n\\key')
output = output.replace('>>', '>>\n')
output = output.replace('\\bar "||"', '\\bar "||"\n')
output = output.replace('\\bar "|."', '\\bar "|."\n')
return output
def compile(self, destination='svg'):
self.destination = destination
file_name = f'./.lilypond/{destination}_{self.basename}.ly'
with open(file_name, 'w') as file:
file.write(self.source)
dest = ''
if destination == 'svg':
dest = '--svg'
subprocess.run(
['lilypond', '--silent', '-dno-point-and-click', dest, '--output=./.lilypond',
file_name])
# os.remove(file_name)
def prepare(self):
#if not self.practice.has_changed:
# return
self.compile('svg')
# trim svg
subprocess.run(
['inkscape',
f'./.lilypond/svg_{self.basename}.svg', f'--export-filename=./.assets/{self.basename}.svg',
'--export-area-drawing'])