/
chant.py
585 lines (474 loc) · 17.8 KB
/
chant.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: chant.py
# Purpose: Classes and Tools for converting Music21 Streams to Gregorio .gabc
#
# Authors: Michael Scott Cuthbert
#
# Copyright: Copyright © 2009-2012, 15 Michael Scott Cuthbert and the music21 Project
# License: LGPL or BSD, see license.txt
#-------------------------------------------------------------------------------
'''
``ALPHA MODULE``: Not directly supported by cuthbertLab.
Classes and Tools for converting Music21 Streams to Gregorio .gabc
Requires the amazing Gregoio library: http://gregorio-project.github.io , which itself
requires LaTeX. (MacTeX, etc.; I suggest Basic TeX instead of the full MacTeX for this,
since it's only 100MB instead of 2.5GB)
'''
import re
import unittest
import os.path
from music21 import clef
from music21 import common
from music21 import exceptions21
from music21 import note
from music21 import stream
from music21 import environment
_MOD = "chant.py"
environLocal = environment.Environment(_MOD)
def fromStream(inputStream):
if inputStream.metadata is not None:
incipit = inputStream.metadata.title
else:
incipit = "Benedicamus Domino"
out = ''
out += 'name: ' + incipit + ';\n'
out += "%%\n"
return out
class GregorianStream(stream.Stream):
r'''
>>> s = alpha.chant.GregorianStream()
>>> s.append(clef.AltoClef())
>>> n = alpha.chant.GregorianNote("C4")
>>> l = note.Lyric("Po")
>>> l.syllabic = "start"
>>> n.lyrics.append(l)
>>> n.oriscus = True
>>> s.append(n)
>>> s.toGABCText()
'(c3) Po(ho)\n'
'''
def toGABCText(self):
currentClef = None
outLine = ""
startedSyllable = False
for e in self:
if hasattr(e, 'isNote') and e.isNote is True:
if e.lyrics and e.lyrics[0] != "":
if startedSyllable:
outLine += ")"
startedSyllable = False
if e.lyrics[0].syllabic in ['begin', 'single']:
outLine += " "
outLine += e.lyrics[0].text
outLine += "("
startedSyllable = True
outLine += e.toGABC(useClef=currentClef)
elif 'Clef' in e.classes:
if startedSyllable:
outLine += ") "
startedSyllable = False
currentClef = e
outLine += self.clefToGABC(e) + ' '
if startedSyllable:
outLine += ")\n"
return outLine
def clefToGABC(self, clefIn):
'''
>>> s = alpha.chant.GregorianStream()
>>> c = clef.AltoClef()
>>> s.clefToGABC(c)
'(c3)'
'''
return "(" + clefIn.sign.lower() + str(clefIn.line) + ")"
class GregorianNote(note.Note):
'''
A GregorianNote is a subclass of :class:`~music21.note.Note` that
contains extra attributes which represent the interpretation or
graphical representation of the note.
Most of the attributes default to False. Exceptions are noted below.
Example: a very special note.
>>> n = alpha.chant.GregorianNote("C4")
>>> n.liquescent = True
>>> n.quilisma = True
>>> n.basicShape = 'virga' # default: punctus
>>> n.breakNeume = True # don't connect to the next note in a neume.
>>> n.stropha = True
>>> n.inclinatum = True
>>> n.debilis = True # small note
>>> n.episema = True
>>> n.punctumMora = True
>>> n.fill = 'cavum' #
'''
liquescent = False
quilisma = False
oriscus = False
basicShape = 'punctus'
breakNeume = False
stropha = False
inclinatum = False
debilis = False
nextNote = None
episema = False
punctumMora = False
_fill = 'solid'
fillDic = {'solid': '',
'cavum': 'r',
'linea': 'R',
'linea-cavum': 'r0',
'accentus': 'r1',
'reversed-accentus': 'r2',
'circulus': 'r3',
'semi-circulus': 'r4',
'reversed-semi-circulus': 'r5'}
polyphonic = False
choralSign = False
def __init__(self, *arguments, **keywords):
super().__init__(*arguments, **keywords)
def toGABC(self, useClef=None, nextNote=None):
letter = self.toBasicGABC(useClef)
if self.debilis:
letter = "-" + letter
if self.inclinatum:
letter = letter.upper()
if self.fill != 'solid':
if self.fill in self.fillDic:
letter += self.fillDic[self.fill]
else:
raise ChantException('cannot use filltype %s' % self.fill)
if self.oriscus:
letter += 'o'
elif self.quilisma:
letter += 'w'
elif self.stropha:
letter += 's'
if self.liquescent != False:
#if nextNote is not None:
# if nextNote.diatonicNoteNum > self.diatonicNoteNum:
# letter += '<'
# else:
# letter += '>'
if self.liquescent == 'ascending':
letter += '<'
elif self.liquescent == 'descending':
letter += '<'
else:
letter += '~'
if self.punctumMora != False:
if self.punctumMora == 1:
letter += '.'
elif self.punctumMora == 2:
letter += '..'
else:
raise ChantException('unable to do punctumMora with more than two notes')
if self.episema != False:
if self.episema == 'vertical':
letter += '\''
elif self.episema == 'below':
letter += '_0'
else:
letter += '_'
if self.breakNeume != False:
letter += "!"
if self.choralSign != False:
letter += "[cs:" + self.choralSign + "]"
if self.polyphonic:
letter = "{" + letter + "}"
return letter
def toBasicGABC(self, useClef=None):
'''
returns the character representing inNote in the given clef (default = AltoClef)
see http://home.gna.org/gregorio/gabc/ for more details. 'd' = lowest line
>>> n = alpha.chant.GregorianNote("C4")
>>> c = clef.AltoClef()
>>> n.toBasicGABC(c)
'h'
>>> c2 = clef.SopranoClef()
>>> n.toBasicGABC(c2)
'd'
'''
inNote = self
usedDefaultClef = False
if useClef is None:
useClef = clef.AltoClef()
usedDefaultClef = True
asciiD = 100
asciiA = 97
asciiM = 109
if not hasattr(useClef, 'lowestLine'):
raise ChantException(
"useClef has to define the diatonicNoteNum representing the lowest line")
stepsAboveLowestLine = inNote.pitch.diatonicNoteNum - useClef.lowestLine
asciiNote = stepsAboveLowestLine + asciiD
if asciiNote < asciiA:
if usedDefaultClef is True:
raise ChantException(
"note is too low for the default clef (AltoClef), choose a lower one")
else:
raise ChantException(
"note is too low for the clef (%s), choose a lower one" % str(useClef))
elif asciiNote > asciiM:
if usedDefaultClef is True:
raise ChantException(
"note is too high for the default clef (AltoClef), choose a higher one")
else:
raise ChantException(
"note is too high for the clef (%s), choose a higher one" % str(useClef))
else:
return chr(asciiNote)
def _getFill(self):
return self._fill
def _setFill(self, value):
if value not in self.fillDic:
raise ChantException("Cannot set fill to value %s." % value)
self._fill = value
fill = property(_getFill, _setFill, doc='''Sets the
fill for the note, for teaching purposes, representing
polyphony, etc. Acceptable values are:
* solid (default)
* cavum (void)
* linea (lines around it; technically not a fill)
* linea-cavum (both of the previous)
* accentus
* reversed-accentus
* circulus
* semi-circulus
* reversed-semi-circulus
See the docs for Gregorio for graphical representations of these figures.
>>> n = alpha.chant.GregorianNote("D3")
>>> n.fill
'solid'
>>> n.fill = 'cavum'
>>> n.fill
'cavum'
''')
class BaseScoreConverter:
'''
Converter for all Score objects.
'''
samplePiece = r'''
style: modern;
% Then, when gregorio encounters the following line (%%),
% it switches to the score, where you input the notes
%%
% The syntax in this part is called gabc.
% Please refer to http://home.gna.org/gregorio/gabc/#basis
Pó(c3eh)pu(g)lus(h) Si(hi)on,(hgh.) *(;) ec(hihi)ce(e.) Dó(e.f!gwhhi)mi(h){n}us(h)
vé(hi)ni(ig//ih)et(h.) (,) ad(iv./hig) sal(fe)ván(ghg)das(fg) gen(e_f_e_)tes(e.) :(:)
et(e) au(eh)dí(hhi)tam(i) fá(kjki)ci(i)et(i) Dó(ij)mi(ihi)nus(iv./hiHF)
(,) gló(h!i'j)ri(ji!kvJI)am(ij) vo(j.i!jwk)cis(ji) su(i_j_i_)æ,(i.) (;)
in(e) læ(e)tí(e!f'h)ti(h)a(hi!jVji)
cor(gh!ijI'H<)dis(ihhf!gwh) ve(e_f_e_)stri.(e) Ps.(::) Qui(ehg)
re(hi)gis(i) I(i)sra(i)el,(hj) in(j)tén(ji)de(ij..) :*(:) qui(ig) de(hi)dú(i)cis(i)
vel(i)ut(i!jwk) o(i')vem(h) Jo(hhh)seph.(fe..) (::) Gló(ehg)ri(hi)a(i)
Pa(i)tri.(i) (:) E(i) u(i!jwk) o(i) u(h) a(hhh) e(fe..) (::)
'''
def __init__(self):
self.environLocal = environLocal
self.gregorioConverter = '/usr/local/bin/gregorio'
self.gregorioOptions = ""
self.gregorioCommand = None
self.latexConverter = '/usr/texbin/lualatex'
self.latexOptions = '--interaction=nonstopmode'
self.score = ""
self.incipit = ""
self.mode = ""
self.paperType = None
def writeFile(self, text=None):
'''
>>> bsc = alpha.chant.BaseScoreConverter()
>>> filePath = bsc.writeFile('hello')
>>> assert(filePath.endswith('.gabc')) #_DOCS_HIDE
>>> filePath = '/var/folders/k9/T/music21/tmpekHFCr.gabc' #_DOCS_HIDE
>>> filePath
'/var/folders/k9/T/music21/tmpekHFCr.gabc'
'''
if text is None or text == "":
raise ChantException('Cannot write file if there is no data')
fp = self.environLocal.getTempFile('.gabc')
f = open(fp, 'w')
f.write(text)
f.close()
return fp
def launchGregorio(self, fp=None):
'''
converts a .gabc file to LaTeX using the
gregorio converter. Returns the filename with .tex substituted for .gabc
>>> bsc = alpha.chant.BaseScoreConverter()
>>> fn = '~cuthbert/Library/Gregorio/examples/Populas.gabc'
>>> #_DOCS_SHOW newFp = bsc.launchGregorio(fn)
>>> #_DOCS_SHOW bsc.gregorioCommand
>>> 'open -a"/usr/local/bin/gregorio" ' + fn #_DOCS_HIDE
'open -a"/usr/local/bin/gregorio" ~cuthbert/Library/Gregorio/examples/Populas.gabc'
More often, you'll want to write a textfile from writeFile:
'''
platform = common.getPlatform()
fpApp = self.gregorioConverter
options = self.gregorioOptions
if platform == 'win': # note extra set of quotes!
cmd = '""%s" %s "%s""' % (fpApp, options, fp)
elif platform == 'darwin':
cmd = '%s %s %s' % (fpApp, options, fp)
elif platform == 'nix':
cmd = '%s %s %s' % (fpApp, options, fp)
self.gregorioCommand = cmd
os.system(cmd)
newfp = re.sub(r'\.gabc', '.tex', fp)
return newfp
def launchLaTeX(self, fp=None):
'''
converts a .tex file to pdf using lulatex
Returns the filename with .pdf substituted for .tex
'''
platform = common.getPlatform()
fpApp = self.latexConverter
options = self.latexOptions
fpDir = os.path.dirname(fp)
options += ' --output-dir="' + fpDir + '"'
if platform == 'win': # note extra set of quotes!
cmd = '""%s" %s "%s""' % (fpApp, options, fp)
elif platform == 'darwin':
cmd = '%s %s %s' % (fpApp, options, fp)
elif platform == 'nix':
cmd = '%s %s %s' % (fpApp, options, fp)
self.gregorioCommand = cmd
os.system(cmd)
newfp = re.sub(r'\.tex', '.pdf', fp)
return newfp
class DefaultTeXWrapper:
def __init__(self):
self.baseWrapper = '''% !TEX TS-program = lualatex
% !TEX encoding = UTF-8
% This is a simple template for a LuaLaTeX document using gregorio scores.
\\documentclass[11pt]{article} % use larger type; default would be 10pt
% usual packages loading:
\\usepackage{luatextra}
\\usepackage{graphicx} % support the \\includegraphics command and options
\\usepackage{geometry} % See geometry.pdf to learn the layout options. There are lots.
\\geometry{PAPERTYPEGOESHERE} % a4paper or letterpaper (US) or a5paper or other
\\usepackage{gregoriotex} % for gregorio score inclusion
\\usepackage{fullpage} % to reduce the margins
% choose the language of the document here
\\usepackage[latin]{babel}
% use the two following package for using normal TeX fonts
\\usepackage[T1]{fontenc}
\\usepackage[utf8]{luainputenc}
% If you use usual TeX fonts, here is a starting point:
\\usepackage{times}
% to change the font to something better, you can install the kpfonts package (if not already installed). To do so
% go open the "TeX Live Manager" in the Menu Start->All Programs->TeX Live 2010
% here we begin the document
\\begin{document}
% The title:
\\begin{center}\\begin{huge}\\textsc{INCIPITGOESHERE}\\end{huge}\\end{center}
% Here we set the space around the initial.
% Please report to http://home.gna.org/gregorio/gregoriotex/details for more details and options
\\setspaceafterinitial{2.2mm plus 0em minus 0em}
\\setspacebeforeinitial{2.2mm plus 0em minus 0em}
% Here we set the initial font. Change 43 if you want a bigger initial.
\\def\\greinitialformat#1{%
{\\fontsize{43}{43}\\selectfont #1}%
}
% We set red lines here, comment it if you want black ones.
\\redlines
% We set Mode above the initial.
\\gresetfirstlineaboveinitial{\\small \\textsc{\\textbf{MODEGOESHERE}}}{\\small \\textsc{\\textbf{MODEGOESHERE}}}
% We type a text in the top right corner of the score:
\\commentary{{\\small \\emph{Cf. Is. 30, 19 . 30 ; Ps. 79}}}
% and finally we include the score.
SCOREGOESHERE
'''
def substituteInfo(self, converter):
r'''
Puts the correct information into the TeXWrapper for the document
>>> wrapper = alpha.chant.DefaultTeXWrapper()
>>> class Converter():
... score = r'\note{C}' + "\n" + r'\endgregorioscore %' + "\n" + r'\endinput %'
... incipit = 'Gaudeamus Omnes'
... mode = 'VII'
... paperType = None
>>> c = Converter()
>>> print(wrapper.substituteInfo(c))
% !TEX TS-program = lualatex
% !TEX encoding = UTF-8
...
\geometry{letterpaper} % a4paper or letterpaper (US) or a5paper or other
...
% The title:
\begin{center}\begin{huge}\textsc{Gaudeamus Omnes}\end{huge}\end{center}
...
% We set Mode above the initial.
\gresetfirstlineaboveinitial{\small \textsc{\textbf{VII}}}{\small \textsc{\textbf{VII}}}
...
% and finally we include the score.
\note{C}
\endgregorioscore %
\end{document}
\endinput %...
'''
score = converter.score
incipit = converter.incipit
mode = converter.mode
paperType = converter.paperType
if paperType is None:
paperType = 'letterpaper'
wrapper = self.baseWrapper
wrapper = wrapper.replace(r'SCOREGOESHERE', score)
wrapper = re.sub(r'INCIPITGOESHERE', incipit, wrapper)
wrapper = re.sub(r'MODEGOESHERE', mode, wrapper)
wrapper = re.sub(r'PAPERTYPEGOESHERE', paperType, wrapper)
wrapper = re.sub(r'\\endinput %', r'\\end{document}' + "\n" + r'\\endinput %', wrapper)
return wrapper
class ChantException(exceptions21.Music21Exception):
pass
class Test(unittest.TestCase):
pass
def runTest(self):
pass
class TestExternal(unittest.TestCase): # pragma: no cover
pass
def runTest(self):
pass
def testSimpleFile(self):
s = GregorianStream()
s.append(clef.AltoClef())
n = GregorianNote("C4")
l = note.Lyric("Po")
l.syllabic = "start"
n.lyrics.append(l)
n.oriscus = True
s.append(n)
n2 = GregorianNote("D4")
s.append(n2)
n3 = GregorianNote("C4")
n3.stropha = True
s.append(n3)
n4 = GregorianNote("B3")
n4.stropha = True
s.append(n4)
gabcText = s.toGABCText()
bsc = BaseScoreConverter()
bsc.score = gabcText
bsc.incipit = "Populus"
bsc.mode = 'VII'
fn = bsc.writeFile("style: modern;\n\n%%\n" + gabcText)
texfn = bsc.launchGregorio(fn)
texfh = open(texfn)
texcontents = texfh.read()
texfh.close()
bsc.score = texcontents
dtw = DefaultTeXWrapper()
newgabcText = dtw.substituteInfo(bsc)
texfh2 = open(texfn, 'w')
texfh2.write(newgabcText)
texfh2.close()
pdffn = bsc.launchLaTeX(texfn)
os.system('open %s' % pdffn)
#-------------------------------------------------------------------------------
# define presented order in documentation
_DOC_ORDER = []
if __name__ == "__main__":
import music21
music21.mainTest(Test)
#------------------------------------------------------------------------------
# eof