-
Notifications
You must be signed in to change notification settings - Fork 405
/
translate.py
1736 lines (1494 loc) · 65 KB
/
translate.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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Name: romanText/translate.py
# Purpose: Translation routines for roman numeral analysis text files
#
# Authors: Christopher Ariza
# Michael Scott Asato Cuthbert
#
# Copyright: Copyright © 2011-2022 Michael Scott Asato Cuthbert
# License: BSD, see license.txt
# ------------------------------------------------------------------------------
'''
Translation routines for roman numeral analysis text files, as defined
and demonstrated by Dmitri Tymoczko. Also used for the ClercqTemperley
format which is similar but a little different.
This module is really only needed for people extending the parser,
for others it's simple to get Harmony, RomanNumeral, Key (or KeySignature)
and other objects out of an rntxt file by running this:
>>> monteverdi = corpus.parse('monteverdi/madrigal.3.1.rntxt')
>>> monteverdi.show('text')
{0.0} <music21.metadata.Metadata object at 0x...>
{0.0} <music21.stream.Part ...>
{0.0} <music21.stream.Measure 1 offset=0.0>
{0.0} <music21.key.KeySignature of 1 flat>
{0.0} <music21.meter.TimeSignature 4/4>
{0.0} <music21.roman.RomanNumeral vi in F major>
{3.0} <music21.roman.RomanNumeral V[no3] in F major>
{4.0} <music21.stream.Measure 2 offset=4.0>
{0.0} <music21.roman.RomanNumeral I in F major>
{3.0} <music21.roman.RomanNumeral IV in F major>
...
Then the stream can be analyzed with something like this, storing
the data to make a histogram of scale degree usage within a key:
>>> degreeDictionary = {}
>>> for el in monteverdi.recurse():
... if isinstance(el, roman.RomanNumeral):
... print(f'{el.figure} {el.key}')
... for p in el.pitches:
... degree, accidental = el.key.getScaleDegreeAndAccidentalFromPitch(p)
... if accidental is None:
... degreeString = str(degree)
... else:
... degreeString = str(degree) + str(accidental.modifier)
... if degreeString not in degreeDictionary:
... degreeDictionary[degreeString] = 1
... else:
... degreeDictionary[degreeString] += 1
... degTuple = (str(p), degreeString)
... print(degTuple)
vi F major
('D5', '6')
('F5', '1')
('A5', '3')
V[no3] F major
('C5', '5')
('G5', '2')
I F major
('F4', '1')
('A4', '3')
('C5', '5')
...
V6 g minor
('F#5', '7#')
('A5', '2')
('D6', '5')
i g minor
('G4', '1')
('B-4', '3')
('D5', '5')
...
Now if we'd like we can get a Histogram of the data.
It's a little complex, but worth seeing in full:
>>> import operator
>>> histogram = graph.primitives.GraphHistogram()
>>> i = 0
>>> data = []
>>> xLabels = []
>>> values = []
>>> ddList = list(degreeDictionary.items())
>>> for deg,value in sorted(ddList, key=operator.itemgetter(1), reverse=True):
... data.append((i, degreeDictionary[deg]), )
... xLabels.append((i+.5, deg), )
... values.append(degreeDictionary[deg])
... i += 1
>>> histogram.data = data
These commands give nice labels for the data; optional:
>>> histogram.setIntegerTicksFromData(values, 'y')
>>> histogram.setTicks('x', xLabels)
>>> histogram.setAxisLabel('x', 'ScaleDegree')
Now generate the histogram:
>>> #_DOCS_HIDE histogram.process()
.. image:: images/romanTranslatePitchDistribution.*
:width: 600
OMIT_FROM_DOCS
>>> x = converter.parse('romantext: m1 a: VI')
>>> [str(p) for p in x[roman.RomanNumeral].first().pitches]
['F5', 'A5', 'C6']
>>> x = converter.parse('romantext: m1 a: vi')
>>> [str(p) for p in x[roman.RomanNumeral].first().pitches]
['F#5', 'A5', 'C#6']
>>> [str(p) for p in
... converter.parse('romantext: m1 a: vio'
... )[roman.RomanNumeral].first().pitches]
['F#5', 'A5', 'C6']
'''
import copy
import textwrap
import traceback
import typing as t
import unittest
from music21 import bar
from music21 import base
from music21 import common
from music21 import exceptions21
from music21 import harmony
from music21 import key
from music21 import metadata
from music21 import meter
from music21 import note
from music21 import repeat
from music21 import roman
from music21 import spanner
from music21 import stream
from music21 import tie
from music21.romanText import rtObjects
from music21 import environment
environLocal = environment.Environment('romanText.translate')
ROMANTEXT_VERSION = 1.0
USE_RN_CACHE = False
# Not currently using rnCache because of problems with PivotChords,
# See mail from Dmitri, 30 September 2014
# ------------------------------------------------------------------------------
class RomanTextTranslateException(exceptions21.Music21Exception):
pass
class RomanTextUnprocessedToken(base.ElementWrapper):
pass
class RomanTextUnprocessedMetadata(base.Music21Object):
def __init__(self, tag='', data=''):
super().__init__()
self.tag = tag
self.data = data
def _reprInternal(self) -> str:
return f'{self.tag}: {self.data}'
def _copySingleMeasure(rtTagged, p, kCurrent):
'''
Given a RomanText token, a Part used as the current container,
and the current Key, return a Measure copied from the past of the Part.
This is used in cases of definitions such as:
m23=m21
'''
m = None
# copy from a past location; need to change key
# environLocal.printDebug(['calling _copySingleMeasure()'])
targetNumber, unused_targetRepeat = rtTagged.getCopyTarget()
if len(targetNumber) > 1: # pragma: no cover
# this is an encoding error
raise RomanTextTranslateException(
'a single measure cannot define a copy operation for multiple measures')
# TODO: ignoring repeat letters
target = targetNumber[0]
for mPast in p.getElementsByClass(stream.Measure):
if mPast.number == target:
try:
m = copy.deepcopy(mPast)
except TypeError: # pragma: no cover
raise RomanTextTranslateException(
f'Failed to copy measure {mPast.number}:'
+ ' did you perhaps parse an RTOpus object with romanTextToStreamScore '
+ 'instead of romanTextToStreamOpus?')
m.number = rtTagged.number[0]
# update all keys
for rnPast in m.getElementsByClass(roman.RomanNumeral):
if kCurrent is None: # pragma: no cover
# should not happen
raise RomanTextTranslateException(
'attempting to copy a measure but no past key definitions are found')
if rnPast.editorial.get('followsKeyChange'):
kCurrent = rnPast.key
elif rnPast.pivotChord is not None:
kCurrent = rnPast.pivotChord.key
else:
rnPast.key = kCurrent
if rnPast.secondaryRomanNumeral is not None:
newRN = roman.RomanNumeral(rnPast.figure, kCurrent)
newRN.duration = copy.deepcopy(rnPast.duration)
newRN.lyrics = copy.deepcopy(rnPast.lyrics)
m.replace(rnPast, newRN)
break
return m, kCurrent
def _copyMultipleMeasures(rtMeasure: rtObjects.RTMeasure,
p: stream.Part,
kCurrent: t.Optional[key.Key]):
'''
Given a RomanText token for a RTMeasure, a
Part used as the current container, and the current Key,
return a Measure range copied from the past of the Part.
This is used for cases such as:
m23-25 = m20-22
'''
# the key provided needs to be the current key
# environLocal.printDebug(['calling _copyMultipleMeasures()'])
targetNumbers, unused_targetRepeat = rtMeasure.getCopyTarget()
if len(targetNumbers) == 1: # pragma: no cover
# this is an encoding error
raise RomanTextTranslateException('a multiple measure range cannot copy a single measure')
# TODO: ignoring repeat letters
targetStart = targetNumbers[0]
targetEnd = targetNumbers[1]
if rtMeasure.number[1] - rtMeasure.number[0] != targetEnd - targetStart: # pragma: no cover
raise RomanTextTranslateException(
'both the source and destination sections need to have the same number of measures')
if rtMeasure.number[0] < targetEnd: # pragma: no cover
raise RomanTextTranslateException(
'the source section cannot overlap with the destination section')
measures = []
for mPast in p.getElementsByClass(stream.Measure):
if mPast.number in range(targetStart, targetEnd + 1):
try:
m = copy.deepcopy(mPast)
except TypeError: # pragma: no cover
raise RomanTextTranslateException(
'Failed to copy measure {0} to measure range {1}-{2}: '.format(
mPast.number, targetStart, targetEnd)
+ 'did you perhaps parse an RTOpus object with romanTextToStreamScore '
+ 'instead of romanTextToStreamOpus?')
m.number = rtMeasure.number[0] + mPast.number - targetStart
measures.append(m)
# update all keys
allRNs = list(m.getElementsByClass(roman.RomanNumeral))
for rnPast in allRNs:
if kCurrent is None: # pragma: no cover
# should not happen
raise RomanTextTranslateException(
'attempting to copy a measure but no past key definitions are found')
if rnPast.editorial.get('followsKeyChange'):
kCurrent = rnPast.key
elif rnPast.pivotChord is not None:
kCurrent = rnPast.pivotChord.key
else:
rnPast.key = kCurrent
if rnPast.secondaryRomanNumeral is not None:
newRN = roman.RomanNumeral(rnPast.figure, kCurrent)
newRN.duration = copy.deepcopy(rnPast.duration)
newRN.lyrics = copy.deepcopy(rnPast.lyrics)
m.replace(rnPast, newRN)
if mPast.number == targetEnd:
break
return measures, kCurrent
def _getKeyAndPrefix(rtKeyOrString):
'''Given an RTKey specification, return the Key and a string prefix based
on the tonic:
>>> romanText.translate._getKeyAndPrefix('c')
(<music21.key.Key of c minor>, 'c: ')
>>> romanText.translate._getKeyAndPrefix('F#')
(<music21.key.Key of F# major>, 'F#: ')
>>> romanText.translate._getKeyAndPrefix('Eb')
(<music21.key.Key of E- major>, 'E-: ')
>>> romanText.translate._getKeyAndPrefix('Bb')
(<music21.key.Key of B- major>, 'B-: ')
>>> romanText.translate._getKeyAndPrefix('bb')
(<music21.key.Key of b- minor>, 'b-: ')
>>> romanText.translate._getKeyAndPrefix('b#')
(<music21.key.Key of b# minor>, 'b#: ')
>>> romanText.translate._getKeyAndPrefix('Bbb')
(<music21.key.Key of B-- major>, 'B--: ')
'''
if isinstance(rtKeyOrString, str):
rtKeyOrString = key.convertKeyStringToMusic21KeyString(rtKeyOrString)
k = key.Key(rtKeyOrString)
else:
k = rtKeyOrString.getKey()
tonicName = k.tonic.name
if k.mode == 'minor':
tonicName = tonicName.lower()
prefix = tonicName + ': '
return k, prefix
# Cache each of the created keys so that we don't recreate them.
_rnKeyCache: t.Dict[t.Tuple[str, str], roman.RomanNumeral] = {}
class PartTranslator:
'''
A refactoring of the previously massive romanTextToStreamScore function
to allow for more fine-grained testing (eventually), and to
get past the absurdly high number of nested blocks (the previous translator
was written under severe time constraints).
'''
def __init__(self, md=None):
if md is None:
md = metadata.Metadata()
self.md = md # global metadata object
self.p = stream.Part()
self.romanTextVersion = ROMANTEXT_VERSION
# ts indication are found in header, and also found elsewhere
self.tsCurrent = meter.TimeSignature('4/4') # create default 4/4
self.tsAtTimeOfLastChord = self.tsCurrent
self.tsSet = False # store if set to a measure
self.lastMeasureToken = None
self.lastMeasureNumber = 0
self.previousRn = None
self.keySigCurrent = None
self.setKeySigFromFirstKeyToken = True # set a keySignature
self.foundAKeySignatureSoFar = False
self.kCurrent, unused_prefixLyric = _getKeyAndPrefix('C') # default if none defined
self.prefixLyric = ''
self.sixthMinor = roman.Minor67Default.CAUTIONARY
self.seventhMinor = roman.Minor67Default.CAUTIONARY
self.repeatEndings = {}
# reset for each measure
self.currentMeasureToken = None
self.previousChordInMeasure = None
self.pivotChordPossible = False
self.numberOfAtomsInCurrentMeasure = 0
self.setKeyChangeToken = False
self.currentOffsetInMeasure = 0.0
def translateTokens(self, tokens):
for token in tokens:
try:
self.translateOneLineToken(token)
except Exception: # pylint: disable=broad-except
tracebackMessage = traceback.format_exc()
raise RomanTextTranslateException(
f'At line {token.lineNumber} for token {token}, '
+ f'an exception was raised: \n{tracebackMessage}')
p = self.p
p.coreElementsChanged()
fixPickupMeasure(p)
p.makeBeams(inPlace=True)
p.makeAccidentals(inPlace=True)
_addRepeatsFromRepeatEndings(p, self.repeatEndings) # 1st and second endings...
return p
def translateOneLineToken(self, lineToken: rtObjects.RTTagged):
# noinspection SpellCheckingInspection
'''
Translates one line token and set the current settings.
A token in this case consists of an entire line's worth.
It might be a token such as 'Title: Neko Funjatta' or
a composite token such as 'm23 b4 IV6'
'''
md = self.md
# environLocal.printDebug(['token', t])
# most common case first...
if lineToken.isMeasure():
if t.TYPE_CHECKING:
assert isinstance(lineToken, rtObjects.RTMeasure)
self.translateMeasureLineToken(lineToken)
elif lineToken.isTitle():
md.add('title', lineToken.data)
elif lineToken.isWork():
md.add('alternativeTitle', lineToken.data)
elif lineToken.isPiece():
md.add('alternativeTitle', lineToken.data)
elif lineToken.isComposer():
md.add('composer', lineToken.data)
elif lineToken.isMovement():
md.add('movementNumber', lineToken.data)
elif lineToken.isAnalyst():
md.add('analyst', lineToken.data)
elif lineToken.isProofreader():
md.add('proofreader', lineToken.data)
elif lineToken.isTimeSignature():
try:
self.tsCurrent = meter.TimeSignature(lineToken.data)
self.tsSet = False
except exceptions21.Music21Exception: # pragma: no cover
environLocal.warn(f'Could not parse TimeSignature tag: {lineToken.data!r}')
# environLocal.printDebug(['tsCurrent:', tsCurrent])
elif lineToken.isKeySignature():
self.parseKeySignatureTag(lineToken)
elif lineToken.isSixthMinor() or lineToken.isSeventhMinor():
self.setMinorRootParse(lineToken)
elif lineToken.isVersion():
try:
self.romanTextVersion = float(lineToken.data)
except ValueError: # pragma: no cover
environLocal.warn(f'Could not parse RTVersion tag: {lineToken.data!r}')
elif isinstance(lineToken, rtObjects.RTTagged):
otherMetadata = RomanTextUnprocessedMetadata(lineToken.tag, lineToken.data)
self.p.append(otherMetadata)
else: # pragma: no cover
unprocessed = RomanTextUnprocessedToken(lineToken)
self.p.append(unprocessed)
def setMinorRootParse(self, rtTagged: rtObjects.RTTagged):
'''
Set Roman Numeral parsing standards from a token.
>>> pt = romanText.translate.PartTranslator()
>>> pt.sixthMinor
<Minor67Default.CAUTIONARY: 2>
>>> tag = romanText.rtObjects.RTTagged('SixthMinor: Flat')
>>> tag.isSixthMinor()
True
>>> pt.setMinorRootParse(tag)
>>> pt.sixthMinor
<Minor67Default.FLAT: 4>
Harmonic sets to FLAT for sixth and SHARP for seventh
>>> for config in 'flat sharp quality cautionary harmonic'.split():
... tag = romanText.rtObjects.RTTagged('Seventh Minor: ' + config)
... pt.setMinorRootParse(tag)
... print(pt.seventhMinor)
Minor67Default.FLAT
Minor67Default.SHARP
Minor67Default.QUALITY
Minor67Default.CAUTIONARY
Minor67Default.SHARP
>>> tag = romanText.rtObjects.RTTagged('Sixth Minor: harmonic')
>>> pt.setMinorRootParse(tag)
>>> print(pt.sixthMinor)
Minor67Default.FLAT
Unknown settings raise a `RomanTextTranslateException`
>>> tag = romanText.rtObjects.RTTagged('Seventh Minor: asdf')
>>> pt.setMinorRootParse(tag)
Traceback (most recent call last):
music21.romanText.translate.RomanTextTranslateException:
Cannot parse setting vi or vii parsing: 'asdf'
'''
tData = rtTagged.data.lower()
if tData == 'flat':
tEnum = roman.Minor67Default.FLAT
elif tData == 'sharp':
tEnum = roman.Minor67Default.SHARP
elif tData == 'quality':
tEnum = roman.Minor67Default.QUALITY
elif tData in ('courtesy', 'cautionary'):
tEnum = roman.Minor67Default.CAUTIONARY
elif tData == 'harmonic':
if rtTagged.isSixthMinor():
tEnum = roman.Minor67Default.FLAT
else:
tEnum = roman.Minor67Default.SHARP
else:
raise RomanTextTranslateException(
f'Cannot parse setting vi or vii parsing: {tData!r}')
if rtTagged.isSixthMinor():
self.sixthMinor = tEnum
else:
self.seventhMinor = tEnum
def translateMeasureLineToken(self, measureLineToken: rtObjects.RTMeasure):
'''
Translate a measure token consisting of a single line such as::
m21 b3 V b4 C: IV
Or it might be a variant measure, or a copy instruction.
'''
p = self.p
skipsPriorMeasures = ((measureLineToken.number[0] > self.lastMeasureNumber + 1)
and (self.previousRn is not None))
isSingleMeasureCopy = (len(measureLineToken.number) == 1
and measureLineToken.isCopyDefinition)
isMultipleMeasureCopy = (len(measureLineToken.number) > 1)
# environLocal.printDebug(['handling measure token:', measureLineToken])
# if measureLineToken.number[0] % 10 == 0:
# print('at number ' + str(measureLineToken.number[0]))
if measureLineToken.variantNumber is not None:
# TODO(msc): parse variant numbers
# environLocal.printDebug([f' skipping variant: {measureLineToken}'])
return
if measureLineToken.variantLetter is not None:
# TODO(msc): parse variant letters
# environLocal.printDebug([f' skipping variant letter: {measureLineToken}'])
return
# if this measure number is more than 1 greater than the last
# defined measure number, and the previous chord is not None,
# then fill with copies of the last-defined measure
if skipsPriorMeasures:
self.fillToMeasureToken(measureLineToken)
# create a new measure or copy a past measure
if isSingleMeasureCopy: # if not a range
p.coreElementsChanged()
m, self.kCurrent = _copySingleMeasure(measureLineToken, p, self.kCurrent)
p.coreAppend(m)
self.lastMeasureNumber = m.number
self.lastMeasureToken = measureLineToken
romans = m.getElementsByClass(roman.RomanNumeral)
if romans:
self.previousRn = romans[-1]
elif isMultipleMeasureCopy:
p.coreElementsChanged()
measures, self.kCurrent = _copyMultipleMeasures(measureLineToken, p, self.kCurrent)
p.append(measures) # appendCore does not work with list
self.lastMeasureNumber = measures[-1].number
self.lastMeasureToken = measureLineToken
romans = measures[-1].getElementsByClass(roman.RomanNumeral)
if romans:
self.previousRn = romans[-1]
else:
m = self.translateSingleMeasure(measureLineToken)
p.coreAppend(m)
def fillToMeasureToken(self, measureToken: rtObjects.RTMeasure):
'''
Create a series of measures which extend the previous RN until the measure number
implied by `measureToken`.
'''
p = self.p
for i in range(self.lastMeasureNumber + 1, measureToken.number[0]):
mFill = stream.Measure()
mFill.number = i
if self.previousRn is not None:
newRn = copy.deepcopy(self.previousRn)
newRn.lyric = ''
# set to entire bar duration and tie
newRn.duration = copy.deepcopy(self.tsAtTimeOfLastChord.barDuration)
if self.previousRn.tie is None:
self.previousRn.tie = tie.Tie('start')
else:
self.previousRn.tie.type = 'continue'
# set to stop for now; may extend on next iteration
newRn.tie = tie.Tie('stop')
self.previousRn = newRn
mFill.append(newRn)
appendMeasureToRepeatEndingsDict(self.lastMeasureToken,
mFill,
self.repeatEndings, i)
p.coreAppend(mFill)
self.lastMeasureNumber = measureToken.number[0] - 1
self.lastMeasureToken = measureToken
def parseKeySignatureTag(self, rtTagged: rtObjects.RTTagged):
'''
Parse a key signature tag which has already been determined to
be a key signature.
>>> tag = romanText.rtObjects.RTTagged('KeySignature: -4')
>>> tag.isKeySignature()
True
>>> tag.data
'-4'
>>> pt = romanText.translate.PartTranslator()
>>> pt.keySigCurrent is None
True
>>> pt.setKeySigFromFirstKeyToken
True
>>> pt.foundAKeySignatureSoFar
False
>>> pt.parseKeySignatureTag(tag)
>>> pt.keySigCurrent
<music21.key.KeySignature of 4 flats>
>>> pt.setKeySigFromFirstKeyToken
False
>>> pt.foundAKeySignatureSoFar
True
>>> tag = romanText.rtObjects.RTTagged('KeySignature: xyz')
>>> pt.parseKeySignatureTag(tag)
Traceback (most recent call last):
music21.romanText.translate.RomanTextTranslateException:
Cannot parse key signature: 'xyz'
'''
data = rtTagged.data
if data == '':
self.keySigCurrent = key.KeySignature(0)
elif data == 'Bb':
self.keySigCurrent = key.KeySignature(-1)
else:
try:
dataVal = int(data)
self.keySigCurrent = key.KeySignature(dataVal)
except ValueError:
raise RomanTextTranslateException(f'Cannot parse key signature: {data!r}')
self.setKeySigFromFirstKeyToken = False
# environLocal.printDebug(['keySigCurrent:', keySigCurrent])
self.foundAKeySignatureSoFar = True
def translateSingleMeasure(self, measureToken):
'''
Given a measureToken, return a `stream.Measure` object with
the appropriate atoms set.
'''
self.currentMeasureToken = measureToken
m = stream.Measure()
m.number = measureToken.number[0]
appendMeasureToRepeatEndingsDict(measureToken, m, self.repeatEndings)
self.lastMeasureNumber = measureToken.number[0]
self.lastMeasureToken = measureToken
if not self.tsSet:
m.timeSignature = self.tsCurrent
self.tsSet = True # only set when changed
if not self.setKeySigFromFirstKeyToken and self.keySigCurrent is not None:
m.insert(0, self.keySigCurrent)
self.setKeySigFromFirstKeyToken = True # only set when changed
self.currentOffsetInMeasure = 0.0 # start offsets at zero
self.previousChordInMeasure = None
self.pivotChordPossible = False
self.numberOfAtomsInCurrentMeasure = len(measureToken.atoms)
# first RomanNumeral object after a key change should have this set to True
self.setKeyChangeToken = False
for i, a in enumerate(measureToken.atoms):
isLastAtomInMeasure = (i == self.numberOfAtomsInCurrentMeasure - 1)
self.translateSingleMeasureAtom(a, m, isLastAtomInMeasure=isLastAtomInMeasure)
# may need to adjust duration of last chord added
if self.tsCurrent is not None:
self.previousRn.quarterLength = (self.tsCurrent.barDuration.quarterLength
- self.currentOffsetInMeasure)
m.coreElementsChanged()
return m
def translateSingleMeasureAtom(self, a, m, *, isLastAtomInMeasure=False):
'''
Translate a single atom in a measure token.
`a` is the Atom
`m` is a `stream.Measure` object.
Uses coreInsert and coreAppend methods, so must have `m.coreElementsChanged()`
called afterwards.
'''
if (isinstance(a, rtObjects.RTKey)
or (self.foundAKeySignatureSoFar is False
and isinstance(a, rtObjects.RTAnalyticKey))):
self.setAnalyticKey(a)
# insert at beginning of measure if at beginning
# -- for things like pickups.
if m.number <= 1:
m.coreInsert(0, self.kCurrent)
else:
m.coreInsert(self.currentOffsetInMeasure, self.kCurrent)
self.foundAKeySignatureSoFar = True
elif isinstance(a, rtObjects.RTKeySignature):
try: # this sets the keysignature but not the prefix text
thisSig = a.getKeySignature()
except (exceptions21.Music21Exception, ValueError): # pragma: no cover
raise RomanTextTranslateException(
f'cannot get key from {a.src} in line {self.currentMeasureToken.src}')
# insert at beginning of measure if at beginning
# -- for things like pickups.
if m.number <= 1:
m.coreInsert(0, thisSig)
else:
m.coreInsert(self.currentOffsetInMeasure, thisSig)
self.foundAKeySignatureSoFar = True
elif isinstance(a, rtObjects.RTAnalyticKey):
self.setAnalyticKey(a)
elif isinstance(a, rtObjects.RTBeat):
# set new offset based on beat
try:
newOffset = a.getOffset(self.tsCurrent)
except ValueError: # pragma: no cover
raise RomanTextTranslateException(
'cannot properly get an offset from '
+ f'beat data {a.src}'
+ 'under timeSignature {0} in line {1}'.format(
self.tsCurrent,
self.currentMeasureToken.src))
if (self.previousChordInMeasure is None
and self.previousRn is not None
and newOffset > 0):
# setting a new beat before giving any chords
firstChord = copy.deepcopy(self.previousRn)
firstChord.quarterLength = newOffset
firstChord.lyric = ''
if self.previousRn.tie is None:
self.previousRn.tie = tie.Tie('start')
else:
self.previousRn.tie.type = 'continue'
firstChord.tie = tie.Tie('stop')
self.previousRn = firstChord
self.previousChordInMeasure = firstChord
m.coreInsert(0, firstChord)
self.pivotChordPossible = False
self.currentOffsetInMeasure = newOffset
elif isinstance(a, rtObjects.RTNoChord):
# use source to evaluation roman
self.tsAtTimeOfLastChord = self.tsCurrent
cs = harmony.NoChord()
m.coreInsert(self.currentOffsetInMeasure, cs)
rn = note.Rest()
if self.pivotChordPossible is False:
# probably best to find duration
if self.previousChordInMeasure is None:
pass # use default duration
else: # update duration of previous chord in Measure
oPrevious = self.previousChordInMeasure.getOffsetBySite(m)
newQL = self.currentOffsetInMeasure - oPrevious
if newQL <= 0: # pragma: no cover
raise RomanTextTranslateException(
f'too many notes in this measure: {self.currentMeasureToken.src}')
self.previousChordInMeasure.quarterLength = newQL
self.prefixLyric = ''
m.coreInsert(self.currentOffsetInMeasure, rn)
self.previousChordInMeasure = rn
self.previousRn = rn
self.pivotChordPossible = False
elif isinstance(a, rtObjects.RTChord):
self.processRTChord(a, m, self.currentOffsetInMeasure)
elif isinstance(a, rtObjects.RTRepeat):
if isinstance(a, rtObjects.RTRepeatStop) and isLastAtomInMeasure:
# This condition needs to be moved here because it is possible
# and indeed likely that an end repeat will have an offset of
# 0 in the case that there is 0 or 1 harmonies in the measure.
# Is it ok, however, that this condition will match if self.tsCurrent
# is None? Previously, that case was excluded below.
m.rightBarline = bar.Repeat(direction='end')
elif self.currentOffsetInMeasure == 0:
if isinstance(a, rtObjects.RTRepeatStart):
m.leftBarline = bar.Repeat(direction='start')
else:
rtt = RomanTextUnprocessedToken(a)
m.coreInsert(self.currentOffsetInMeasure, rtt)
elif (self.tsCurrent is not None
and self.tsCurrent.barDuration.quarterLength == self.currentOffsetInMeasure):
if isinstance(a, rtObjects.RTRepeatStop):
m.rightBarline = bar.Repeat(direction='end')
else:
rtt = RomanTextUnprocessedToken(a)
m.coreInsert(self.currentOffsetInMeasure, rtt)
else: # mid-measure repeat signs
rtt = RomanTextUnprocessedToken(a)
m.coreInsert(self.currentOffsetInMeasure, rtt)
else:
rtt = RomanTextUnprocessedToken(a)
m.coreInsert(self.currentOffsetInMeasure, rtt)
# environLocal.warn(f' Got an unknown token: {a}')
def processRTChord(self, a, m, currentOffset):
'''
Process a single RTChord atom.
'''
# use source to evaluation roman
self.tsAtTimeOfLastChord = self.tsCurrent
try:
aSrc = a.src
# if kCurrent.mode == 'minor':
# if aSrc.lower().startswith('vi'): # vi or vii w/ or w/o o
# if aSrc.upper() == a.src: # VI or VII to bVI or bVII
# aSrc = 'b' + aSrc
cacheTuple = (aSrc, self.kCurrent.tonicPitchNameWithCase)
if USE_RN_CACHE and cacheTuple in _rnKeyCache: # pragma: no cover
# print('Got a match: ' + str(cacheTuple))
# Problems with Caches not picking up pivot chords...
# Not faster, see below.
rn = copy.deepcopy(_rnKeyCache[cacheTuple])
else:
# print('No match for: ' + str(cacheTuple))
rn = roman.RomanNumeral(aSrc,
copy.deepcopy(self.kCurrent),
sixthMinor=self.sixthMinor,
seventhMinor=self.seventhMinor,
)
_rnKeyCache[cacheTuple] = rn
# surprisingly, not faster... and more dangerous
# rn = roman.RomanNumeral(aSrc, kCurrent)
# # SLOWEST!!!
# rn = roman.RomanNumeral(aSrc, kCurrent.tonicPitchNameWithCase)
# >>> from timeit import timeit as t
# >>> t('roman.RomanNumeral("IV", "c#")',
# ... 'from music21 import roman', number=1000)
# 45.75
# >>> t('roman.RomanNumeral("IV", k)',
# ... 'from music21 import roman, key; k = key.Key("c#")',
# ... number=1000)
# 16.09
# >>> t('roman.RomanNumeral("IV", copy.deepcopy(k))',
# ... 'from music21 import roman, key; import copy;
# ... k = key.Key("c#")', number=1000)
# 22.49
# # key cache, does not help much...
# >>> t('copy.deepcopy(r)', 'from music21 import roman; import copy;
# ... r = roman.RomanNumeral("IV", "c#")', number=1000)
# 19.01
if self.setKeyChangeToken is True:
rn.editorial.followsKeyChange = True
self.setKeyChangeToken = False
else:
rn.editorial.followsKeyChange = False
except (roman.RomanNumeralException,
exceptions21.Music21CommonException): # pragma: no cover
# environLocal.printDebug(f' cannot create RN from: {a.src}')
rn = note.Note() # create placeholder
if self.pivotChordPossible is False:
# probably best to find duration
if self.previousChordInMeasure is None:
pass # use default duration
else: # update duration of previous chord in Measure
oPrevious = self.previousChordInMeasure.getOffsetBySite(m)
newQL = currentOffset - oPrevious
if newQL <= 0: # pragma: no cover
raise RomanTextTranslateException(
f'too many notes in this measure: {self.currentMeasureToken.src}')
self.previousChordInMeasure.quarterLength = newQL
rn.addLyric(self.prefixLyric + a.src)
self.prefixLyric = ''
m.coreInsert(currentOffset, rn)
self.previousChordInMeasure = rn
self.previousRn = rn
self.pivotChordPossible = True
else:
self.previousChordInMeasure.lyric += '//' + self.prefixLyric + a.src
self.previousChordInMeasure.pivotChord = rn
self.prefixLyric = ''
self.pivotChordPossible = False
def setAnalyticKey(self, a):
'''
Indicates a change in the analyzed key, not a change in anything
else, such as the keySignature.
'''
try: # this sets the key and the keysignature
self.kCurrent, pl = _getKeyAndPrefix(a)
self.prefixLyric += pl
except: # pragma: no cover
raise RomanTextTranslateException(
f'cannot get analytic key from {a.src} in line {self.currentMeasureToken.src}')
self.setKeyChangeToken = True
def romanTextToStreamScore(rtHandler, inputM21=None):
'''
The main processing module for single-movement RomanText works.
Given a romanText handler or string, return or fill a Score Stream.
'''
# accept a string directly; mostly for testing
if isinstance(rtHandler, str):
rtf = rtObjects.RTFile()
tokenedRtHandler = rtf.readstr(rtHandler) # return handler, processes tokens
else:
tokenedRtHandler = rtHandler
# this could be just a Stream, but b/c we are creating metadata,
# perhaps better to match presentation of other scores.
if inputM21 is None:
s = stream.Score()
else:
s = inputM21
# metadata can be first
md = metadata.Metadata()
s.insert(0, md)
partTrans = PartTranslator(md)
p = partTrans.translateTokens(tokenedRtHandler.tokens)
s.insert(0, p)
return s
letterToNumDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8}
def appendMeasureToRepeatEndingsDict(rtMeasureObj: rtObjects.RTMeasure,
m: stream.Measure,
repeatEndings: t.Dict,
measureNumber=None):
# noinspection PyShadowingNames
'''
Takes an RTMeasure object (which might represent one or more
measures; but currently only one) and a music21 stream.Measure object and
store it as a tuple in the repeatEndings dictionary to mark where the
translator should later mark for adding endings.
If the optional measureNumber is specified, we use that rather than the
token number to add to the dict.
This does not yet work for skipped measures.
>>> rtm = romanText.rtObjects.RTMeasure('m15a V6 b1.5 V6/5 b2 I b3 viio6')
>>> rtm.repeatLetter
['a']
>>> rtm2 = romanText.rtObjects.RTMeasure('m15b V6 b1.5 V6/5 b2 I')
>>> rtm2.repeatLetter
['b']
>>> repeatEndings = {}
>>> m1 = stream.Measure()
>>> m2 = stream.Measure()
>>> romanText.translate.appendMeasureToRepeatEndingsDict(rtm, m1, repeatEndings)
>>> repeatEndings
{1: [(15, <music21.stream.Measure 0a offset=0.0>)]}
>>> romanText.translate.appendMeasureToRepeatEndingsDict(rtm2, m2, repeatEndings)
>>> repeatEndings[1], repeatEndings[2]
([(15, <music21.stream.Measure 0a offset=0.0>)],
[(15, <music21.stream.Measure 0b offset=0.0>)])
>>> repeatEndings[2][0][1] is m2
True
'''
if not rtMeasureObj.repeatLetter:
return
m.numberSuffix = rtMeasureObj.repeatLetter[0]
for rl in rtMeasureObj.repeatLetter:
if rl is None or rl == '':
continue
if rl not in letterToNumDict: # pragma: no cover
raise RomanTextTranslateException(f'Improper repeat letter: {rl}')
repeatNumber = letterToNumDict[rl]
if repeatNumber not in repeatEndings:
repeatEndings[repeatNumber] = []
if measureNumber is None:
measureTuple = (rtMeasureObj.number[0], m)
else:
measureTuple = (measureNumber, m)
repeatEndings[repeatNumber].append(measureTuple)