-
Notifications
You must be signed in to change notification settings - Fork 384
/
tsvConverter.py
1372 lines (1178 loc) · 50.1 KB
/
tsvConverter.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/tsvConverter.py
# Purpose: Converter for the DCMLab's tabular format for representing harmonic analysis.
#
# Authors: Mark Gotham
#
# Copyright: Copyright © 2019 Michael Scott Asato Cuthbert
# License: BSD, see license.txt
# ------------------------------------------------------------------------------
'''
Converter for parsing the tabular representations of harmonic analysis such as the
DCMLab's Annotated Beethoven Corpus (Neuwirth et al. 2018).
'''
from __future__ import annotations
import abc
import csv
import fractions
import re
import string
import types
import typing as t
import unittest
from music21 import chord
from music21 import common
from music21 import environment
from music21 import harmony
from music21 import key
from music21 import metadata
from music21 import meter
from music21 import roman
from music21 import spanner
from music21 import stream
environLocal = environment.Environment()
# ------------------------------------------------------------------------------
# V1_HEADERS and V2_HEADERS specify the columns that we process from the DCML
# files, together with the type that the columns should be coerced to (usually
# str)
V1_HEADERS = types.MappingProxyType({
'chord': str,
'altchord': str,
'measure': int,
'beat': float,
'totbeat': str,
'timesig': str,
'length': float,
'global_key': str,
'local_key': str,
'pedal': str,
'numeral': str,
'form': str,
'figbass': str,
'changes': str,
'relativeroot': str,
'phraseend': str,
})
MN_ONSET_REGEX = re.compile(
r'(?P<numer>\d+(?:\.\d+)?)/(?P<denom>\d+(?:\.\d+)?)'
)
def _float_or_frac(value):
# mn_onset in V2 is sometimes notated as a fraction like '1/2'; we need
# to handle such cases
try:
return float(value)
except ValueError:
m = re.match(MN_ONSET_REGEX, value)
return float(m.group('numer')) / float(m.group('denom'))
V2_HEADERS = types.MappingProxyType({
'chord': str,
'mn': int,
'mn_onset': _float_or_frac,
'timesig': str,
'volta': str,
'globalkey': str,
'localkey': str,
'pedal': str,
'numeral': str,
'form': str,
'figbass': str,
'changes': str,
'relativeroot': str,
'phraseend': str,
'label': str,
})
HEADERS = {1: V1_HEADERS, 2: V2_HEADERS}
# Headers for Digital and Cognitive Musicology Lab Standard v1 as in the ABC
# corpus at
# https://github.com/DCMLab/ABC/tree/2e8a01398f8ad694d3a7af57bed8b14ac57120b7
DCML_V1_HEADERS = (
'chord',
'altchord',
'measure',
'beat',
'totbeat',
'timesig',
'op',
'no',
'mov',
'length',
'global_key',
'local_key',
'pedal',
'numeral',
'form',
'figbass',
'changes',
'relativeroot',
'phraseend',
)
# Headers for Digital and Cognitive Musicology Lab Standard v2 as in the ABC
# corpus at
# https://github.com/DCMLab/ABC/tree/65c831a559c47180d74e2679fea49aa117fd3dbb
DCML_V2_HEADERS = (
'mc',
'mn',
'mc_onset',
'mn_onset',
'timesig',
'staff',
'voice',
'volta',
'label',
'globalkey',
'localkey',
'pedal',
'chord',
'special',
'numeral',
'form',
'figbass',
'changes',
'relativeroot',
'cadence',
'phraseend',
'chord_type',
'globalkey_is_minor',
'localkey_is_minor',
'chord_tones',
'added_tones',
'root',
'bass_note',
)
DCML_HEADERS = {1: DCML_V1_HEADERS, 2: DCML_V2_HEADERS}
class TabChordBase(abc.ABC):
'''
Abstract base class for intermediate representation format for moving
between tabular data and music21 chords.
'''
def __init__(self) -> None:
super().__init__()
self.numeral: str = ''
self.relativeroot: str|None = None
self.representationType: str|None = None # Added (not in DCML)
self.extra: dict[str, str] = {}
self.dcml_version = -1
# shared between DCML v1 and v2
self.chord: str = ''
self.timesig: str = ''
self.pedal: str|None = None
self.form: str|None = None
self.figbass: str|None = None
self.changes: str|None = None
self.phraseend: str|None = None
# the following attributes are overwritten by properties in TabChordV2
# because of changed column names in DCML v2
self.local_key: str = ''
self.global_key: str = ''
self.beat: float = 1.0
self.measure: int = 1
@property
def combinedChord(self) -> str:
'''
For easier interoperability with the DCML standards, we now use the
column name 'chord' from the DCML file. But to preserve backwards-
compatibility, we add this property, which is an alias for 'chord'.
>>> tabCd = romanText.tsvConverter.TabChord()
>>> tabCd.chord = 'viio7'
>>> tabCd.combinedChord
'viio7'
>>> tabCd.combinedChord = 'IV+'
>>> tabCd.chord
'IV+'
'''
return self.chord
@combinedChord.setter
def combinedChord(self, value: str):
self.chord = value
def _changeRepresentation(self) -> None:
'''
Converts the representationType of a TabChordBase subclass between the
music21 and DCML conventions.
To demonstrate, let's set up a dummy TabChordV2().
>>> tabCd = romanText.tsvConverter.TabChordV2()
>>> tabCd.global_key = 'F'
>>> tabCd.local_key = 'vi'
>>> tabCd.numeral = 'ii'
>>> tabCd.chord = 'ii%7(6)'
>>> tabCd.representationType = 'DCML'
>>> tabCd.representationType
'DCML'
>>> tabCd.chord
'ii%7(6)'
>>> tabCd._changeRepresentation()
>>> tabCd.representationType
'm21'
>>> tabCd.chord
'iiø7[no5][add6]'
'''
if self.representationType == 'm21':
direction = 'm21-DCML'
self.representationType = 'DCML' # Becomes the case during this function.
elif self.representationType == 'DCML':
direction = 'DCML-m21'
self.representationType = 'm21' # Becomes the case during this function.
else:
raise ValueError("Data source must specify representation type as 'm21' or 'DCML'.")
self.local_key = characterSwaps(self.local_key,
minor=isMinor(self.global_key),
direction=direction)
# previously, '%' (indicating half-diminished) was not being parsed
# properly.
if direction == 'DCML-m21':
self.form = self.form.replace('%', 'ø') if self.form is not None else None
if self.dcml_version == 2:
self.chord = self.chord.replace('%', 'ø')
self.chord = handleAddedTones(self.chord)
# prefix figures for Mm7 chords on degrees other than 'V' with 'd'
if (
self.extra.get('chord_type', '') == 'Mm7'
and self.numeral != 'V'
):
# However, we need to make sure not to match [add13] and
# the like, otherwise we will end up with [addd13]
self.chord = re.sub(
r'''
(\d+) # match one or more digits
(?![\]\d]) # without a digit or a ']' to the right
''',
r'd\1',
self.chord,
flags=re.VERBOSE)
# Local - relative and figure
if isMinor(self.local_key):
if self.relativeroot: # If there's a relative root ...
if isMinor(self.relativeroot): # ... and it's minor too, change it and the figure
self.relativeroot = characterSwaps(self.relativeroot,
minor=True,
direction=direction)
self.numeral = characterSwaps(self.numeral,
minor=True,
direction=direction)
else: # ... rel. root but not minor
self.relativeroot = characterSwaps(self.relativeroot,
minor=False,
direction=direction)
else: # No relative root
self.numeral = characterSwaps(self.numeral,
minor=True,
direction=direction)
else: # local key not minor
if self.relativeroot: # if there's a relativeroot ...
if isMinor(self.relativeroot): # ... and it's minor, change it and the figure
self.relativeroot = characterSwaps(self.relativeroot,
minor=False,
direction=direction)
self.numeral = characterSwaps(self.numeral,
minor=True,
direction=direction)
else: # ... rel. root but not minor
self.relativeroot = characterSwaps(self.relativeroot,
minor=False,
direction=direction)
else: # No relative root
self.numeral = characterSwaps(self.numeral,
minor=False,
direction=direction)
def tabToM21(self) -> harmony.Harmony:
'''
Creates and returns a music21.roman.RomanNumeral() object
from a TabChord with all shared attributes.
NB: call changeRepresentation() first if .representationType is not 'm21'
but you plan to process it with m21 (e.g. moving it into a stream).
>>> tabCd = romanText.tsvConverter.TabChord()
>>> tabCd.numeral = 'vii'
>>> tabCd.global_key = 'F'
>>> tabCd.local_key = 'V'
>>> tabCd.representationType = 'm21'
>>> m21Ch = tabCd.tabToM21()
Now we can check it's a music21 RomanNumeral():
>>> m21Ch.figure
'vii'
'''
if self.representationType == 'DCML':
self._changeRepresentation()
if self.numeral in ('@none', None):
thisEntry: harmony.Harmony = harmony.NoChord()
else:
if self.dcml_version == 2 and self.chord:
combined = self.chord
else:
# previously this code only included figbass in combined if form
# was not falsy, which seems incorrect
combined = ''.join(
attr for attr in (self.numeral, self.form, self.figbass) if attr
)
if self.relativeroot: # special case requiring '/'.
combined += '/' + self.relativeroot
if self.local_key is not None and re.match(
r'.*(i*v|v?i+).*', self.local_key, re.IGNORECASE
):
# if self.local_key contains a roman numeral, express it
# as a pitch, relative to the global key
localKeyNonRoman = getLocalKey(self.local_key, self.global_key)
else:
# otherwise, we assume self.local_key is already a pitch and
# pass it through unchanged
localKeyNonRoman = self.local_key
thisEntry = roman.RomanNumeral(
combined,
localKeyNonRoman,
sixthMinor=roman.Minor67Default.FLAT,
seventhMinor=roman.Minor67Default.FLAT
)
if isinstance(self, TabChord):
# following metadata attributes seem to be missing from
# dcml_version 2 tsv files
thisEntry.editorial.op = self.extra.get('op', '')
thisEntry.editorial.no = self.extra.get('no', '')
thisEntry.editorial.mov = self.extra.get('mov', '')
thisEntry.editorial.pedal = self.pedal
thisEntry.editorial.phraseend = None
# if dcml_version == 2, we need to calculate the quarterLength
# later
thisEntry.quarterLength = 0.0
return thisEntry
def populateFromRow(
self,
row: list[str],
headIndices: dict[str, tuple[int, type]],
extraIndices: dict[int, str]
) -> None:
# To implement without calling setattr we would need to repeat lines
# similar to the following three lines for every attribute (with
# attributes specific to subclasses in their own methods that would
# then call __super__()).
for col_name, (i, type_to_coerce_to) in headIndices.items():
if not hasattr(self, col_name):
pass # would it be appropriate to emit a warning here?
else:
setattr(self, col_name, type_to_coerce_to(row[i]))
self.extra = {
col_name: row[i] for i, col_name in extraIndices.items() if row[i]
}
class TabChord(TabChordBase):
'''
An intermediate representation format for moving between tabular data in
DCML v1 and music21 chords.
'''
def __init__(self) -> None:
# self.numeral and self.relativeroot defined in super().__init__()
super().__init__()
self.altchord: str|None = None
self.totbeat: str|None = None
self.length: fractions.Fraction|float|None = None
self.dcml_version: int = 1
class TabChordV2(TabChordBase):
'''
An intermediate representation format for moving between tabular data in
DCML v2 and music21 chords.
'''
def __init__(self) -> None:
# self.numeral and self.relativeroot defined in super().__init__()
super().__init__()
self.mn: int = 0
self.mn_onset: float = 0.0
self.volta: str = ''
self.globalkey: str = ''
self.localkey: str = ''
self.dcml_version: int = 2
@property
def beat(self) -> float:
'''
'beat' has been removed from DCML v2 in favor of 'mn_onset' and
'mc_onset'. 'mn_onset' is equivalent to 'beat', except that 'mn_onset'
is zero-indexed where 'beat' was 1-indexed, and 'mn_onset' is in
fractions of a whole-note rather than in quarter notes.
>>> tabCd = romanText.tsvConverter.TabChordV2()
>>> tabCd.mn_onset = 0.0
>>> tabCd.beat
1.0
>>> tabCd.mn_onset = 0.5
>>> tabCd.beat
3.0
>>> tabCd.beat = 1.5
>>> tabCd.beat
1.5
'''
# beat is zero-indexed in v2 but one-indexed in v1
# moreover, beat is in fractions of a whole-note in v2
return self.mn_onset * 4.0 + 1.0
@beat.setter
def beat(self, beat: float):
self.mn_onset = (beat - 1.0) / 4.0 if beat is not None else None
@property
def measure(self) -> int:
'''
'measure' has been removed from DCML v2 in favor of 'mn' and 'mc'. 'mn'
is equivalent to 'measure', so this property is provided as an alias.
'''
return int(self.mn)
@measure.setter
def measure(self, measure: int):
self.mn = int(measure) if measure is not None else None
@property
def local_key(self) -> str:
'''
'local_key' has been renamed 'localkey' in DCML v2. This property is
provided as an alias for 'localkey' so that TabChord and TabChordV2 can
be used in the same way.
'''
return self.localkey
@local_key.setter
def local_key(self, k: str):
self.localkey = k
@property
def global_key(self) -> str:
'''
'global_key' has been renamed 'globalkey' in DCML v2. This property is
provided as an alias for 'globalkey' so that TabChord and TabChordV2 can
be used in the same way.
'''
return self.globalkey
@global_key.setter
def global_key(self, k: str):
self.globalkey = k
# ------------------------------------------------------------------------------
class TsvHandler:
'''
Conversion starting with a TSV file.
First we need to get a score. (Don't worry about this bit.)
>>> name = 'tsvEg_v1.tsv'
>>> path = common.getSourceFilePath() / 'romanText' / name
>>> handler = romanText.tsvConverter.TsvHandler(path)
>>> handler.tsvToChords()
These should be TabChords now.
>>> testTabChord1 = handler.chordList[0]
>>> testTabChord1.combinedChord
'.C.I6'
Good. We can make them into music21 Roman-numerals.
>>> m21Chord1 = testTabChord1.tabToM21()
>>> m21Chord1.figure
'I'
And for our last trick, we can put the whole collection in a music21 stream.
>>> out_stream = handler.toM21Stream()
>>> out_stream.parts[0].measure(1)[roman.RomanNumeral][0].figure
'I'
'''
def __init__(self, tsvFile: str, dcml_version: int = 1):
if dcml_version == 1:
self.heading_names = HEADERS[1]
self._tab_chord_cls: type[TabChordBase] = TabChord
elif dcml_version == 2:
self.heading_names = HEADERS[2]
self._tab_chord_cls = TabChordV2
else:
raise ValueError(f'dcml_version {dcml_version} is not in (1, 2)')
self.tsvFileName = tsvFile
self.chordList: list[TabChordBase] = []
self.m21stream: stream.Score|None = None
self._head_indices: dict[str, tuple[int, type|t.Any]] = {}
self._extra_indices: dict[int, str] = {}
self.dcml_version = dcml_version
self.tsvData = self._importTsv() # converted to private
def _get_heading_indices(self, header_row: list[str]) -> None:
'''
Private method to get column name/column index correspondences.
Expected column indices (those in HEADERS, which correspond to TabChord
attributes) are stored in self._head_indices. Others go in
self._extra_indices.
'''
self._head_indices = {}
self._extra_indices = {}
for i, col_name in enumerate(header_row):
if col_name in self.heading_names:
type_to_coerce_col_to = self.heading_names[col_name]
self._head_indices[col_name] = (i, type_to_coerce_col_to)
else:
self._extra_indices[i] = col_name
def _importTsv(self) -> list[list[str]]:
'''
Imports TSV file data for further processing.
'''
fileName = self.tsvFileName
with open(fileName, 'r', encoding='utf-8') as f:
tsvreader = csv.reader(f, delimiter='\t', quotechar='"')
# The first row is the header
self._get_heading_indices(next(tsvreader))
return list(tsvreader)
def _makeTabChord(self, row: list[str]) -> TabChordBase:
'''
Makes a TabChord out of a list imported from TSV data
(a row of the original tabular format -- see TsvHandler.importTsv()).
'''
# this method replaces the previously stand-alone makeTabChord function
thisEntry = self._tab_chord_cls()
thisEntry.populateFromRow(row, self._head_indices, self._extra_indices)
thisEntry.representationType = 'DCML' # Added
return thisEntry
def tsvToChords(self) -> None:
'''
Converts a list of lists (of the type imported by importTsv)
into TabChords (i.e. a list of TabChords).
'''
data = self.tsvData
self.chordList = []
for entry in data:
thisEntry = self._makeTabChord(entry)
if thisEntry is None:
continue
else:
self.chordList.append(thisEntry)
def toM21Stream(self) -> stream.Score:
'''
Takes a list of TabChords (self.chordList, prepared by .tsvToChords()),
converts those TabChords in RomanNumerals
(converting to the music21 representation format as necessary),
creates a suitable music21 stream (by running .prepStream() using data from the TabChords),
and populates that stream with the new RomanNumerals.
'''
if not self.chordList:
self.tsvToChords()
s = self.prepStream()
p = s.parts.first() # Just to get to the part, not that there are several.
if p is None:
# in case stream has no parts
return s
for thisChord in self.chordList:
offsetInMeasure = thisChord.beat - 1 # beats always measured in quarter notes
if isinstance(thisChord, TabChordV2) and thisChord.volta:
measureNumber: str|int = (
f'{thisChord.measure}{string.ascii_lowercase[int(thisChord.volta) - 1]}'
)
else:
measureNumber = thisChord.measure
m21Measure = p.measure(measureNumber)
if m21Measure is None:
raise ValueError('m21Measure should not be None')
thisM21Chord = thisChord.tabToM21() # In either case.
# Store any otherwise unhandled attributes of the chord
thisM21Chord.editorial.update(thisChord.extra)
m21Measure.insert(offsetInMeasure, thisM21Chord)
s.flatten().extendDuration(harmony.Harmony, inPlace=True)
last_harmony = s[harmony.Harmony].last()
if last_harmony is not None:
last_harmony.quarterLength = (
s.quarterLength - last_harmony.activeSite.offset - last_harmony.offset
)
self.m21stream = s
return s
def prepStream(self) -> stream.Score:
'''
Prepares a music21 stream for the harmonic analysis to go into.
Specifically: creates the score, part, and measure streams,
as well as some (the available) metadata based on the original TSV data.
Works like the .template() method,
except that we don't have a score to base the template on as such.
'''
s = stream.Score()
p = stream.Part()
if self.dcml_version == 1:
# This sort of metadata seems to have been removed altogether from the
# v2 files
s.insert(0, metadata.Metadata())
firstEntry = self.chordList[0] # Any entry will do
title = []
if 'op' in firstEntry.extra:
s.metadata.opusNumber = firstEntry.extra['op']
title.append('Op' + s.metadata.opusNumber)
if 'no' in firstEntry.extra:
s.metadata.number = firstEntry.extra['no']
title.append('No' + s.metadata.number)
if 'mov' in firstEntry.extra:
s.metadata.movementNumber = firstEntry.extra['mov']
title.append('Mov' + s.metadata.movementNumber)
if title:
s.metadata.title = '_'.join(title)
startingKeySig = str(self.chordList[0].global_key)
ks = key.Key(startingKeySig)
currentTimeSig = str(self.chordList[0].timesig)
ts = meter.TimeSignature(currentTimeSig)
currentMeasureLength = ts.barDuration.quarterLength
currentOffset: float|fractions.Fraction = 0.0
previousMeasure: int = self.chordList[0].measure - 1 # Covers pickups
previousVolta: str = ''
repeatBracket: t.Optional[spanner.RepeatBracket] = None
for entry in self.chordList:
if isinstance(entry, TabChordV2) and entry.volta != previousVolta:
if entry.volta:
# Should we warn the user that, although we're writing
# repeat brackets, we aren't writing repeat signs since
# the .tsv file doesn't tell us where the forward repeat
# should be?
repeatBracket = spanner.RepeatBracket(number=entry.volta)
# According to the docs at
# https://web.mit.edu/music21/doc/moduleReference/moduleSpanner.html#spanner
# "the convention is to put the spanner at the beginning
# of the innermost Stream that contains all the Spanners"
p.insert(0, repeatBracket)
else:
repeatBracket = None
previousVolta = entry.volta
elif entry.measure == previousMeasure:
# NB we only want to continue here if the 'volta' (ending) has
# not changed, hence the elif
continue
if entry.measure > previousMeasure + 1: # Not every measure has a chord change.
for mNo in range(previousMeasure + 1, entry.measure + 1):
m = stream.Measure(number=mNo)
m.offset = currentOffset + currentMeasureLength
p.insert(m)
currentOffset = m.offset
previousMeasure = mNo
else: # entry.measure <= previousMeasure + 1
if isinstance(entry, TabChordV2) and entry.volta:
measureNumber: str|int = (
f'{entry.measure}{string.ascii_lowercase[int(entry.volta) - 1]}'
)
else:
measureNumber = entry.measure
m = stream.Measure(number=measureNumber)
# 'totbeat' column (containing the current offset) has been
# removed from v2 so instead we calculate the offset directly
# to be portable across versions
currentOffset = m.offset = currentOffset + currentMeasureLength
p.insert(m)
if entry.timesig != currentTimeSig:
newTS = meter.TimeSignature(entry.timesig)
m.insert(entry.beat - 1, newTS)
currentTimeSig = entry.timesig or ''
currentMeasureLength = newTS.barDuration.quarterLength
previousMeasure = entry.measure
if repeatBracket is not None:
repeatBracket.addSpannedElements(m)
s.append(p)
first_measure = s[stream.Measure].first()
if first_measure is not None:
first_measure.insert(0, ks)
first_measure.insert(0, ts)
return s
# ------------------------------------------------------------------------------
class M21toTSV:
'''
Conversion starting with a music21 stream.
Exports to tabular data format and (optionally) writes the file.
>>> bachHarmony = corpus.parse('bach/choraleAnalyses/riemenschneider001.rntxt')
>>> bachHarmony.parts[0].measure(1)[0].figure
'I'
The initialization includes the preparation of a list of lists, so
>>> initial = romanText.tsvConverter.M21toTSV(bachHarmony, dcml_version=2)
>>> tsvData = initial.tsvData
>>> from music21.romanText.tsvConverter import DCML_V2_HEADERS
>>> tsvData[1][DCML_V2_HEADERS.index('chord')]
'I'
'''
def __init__(self, m21Stream: stream.Score, dcml_version: int = 2):
self.version = dcml_version
self.m21Stream = m21Stream
if dcml_version == 1:
self.dcml_headers = DCML_HEADERS[1]
elif dcml_version == 2:
self.dcml_headers = DCML_HEADERS[2]
else:
raise ValueError(f'dcml_version {dcml_version} is not in (1, 2)')
self.tsvData = self.m21ToTsv()
def m21ToTsv(self) -> list[list[str]]:
'''
Converts a list of music21 chords to a list of lists
which can then be written to a tsv file with toTsv(), or processed another way.
'''
if self.version == 1:
return self._m21ToTsv_v1()
return self._m21ToTsv_v2()
def _m21ToTsv_v1(self) -> list[list[str]]:
tsvData = []
# take the global_key from the first item
global_key = next(
self.m21Stream.recurse().getElementsByClass('RomanNumeral')
).key.tonicPitchNameWithCase
for thisRN in self.m21Stream[roman.RomanNumeral]:
relativeroot = None
if thisRN.secondaryRomanNumeral:
relativeroot = thisRN.secondaryRomanNumeral.figure
altChord = None
if thisRN.secondaryRomanNumeral:
if thisRN.secondaryRomanNumeral.key == thisRN.key:
altChord = thisRN.secondaryRomanNumeral.figure
thisEntry = TabChord()
thisEntry.combinedChord = thisRN.figure # NB: slightly different from DCML: no key.
thisEntry.altchord = altChord
thisEntry.measure = thisRN.measureNumber if thisRN.measureNumber is not None else 1
thisEntry.beat = float(thisRN.beat)
thisEntry.totbeat = None
ts = thisRN.getContextByClass(meter.TimeSignature)
if ts is None:
thisEntry.timesig = ''
else:
thisEntry.timesig = ts.ratioString
thisEntry.extra['op'] = self.m21Stream.metadata.opusNumber or ''
thisEntry.extra['no'] = self.m21Stream.metadata.number or ''
thisEntry.extra['mov'] = self.m21Stream.metadata.movementNumber or ''
thisEntry.length = thisRN.quarterLength
thisEntry.global_key = global_key
thisEntry.local_key = thisRN.key.tonicPitchNameWithCase
thisEntry.pedal = None
thisEntry.numeral = thisRN.romanNumeral
thisEntry.form = getForm(thisRN)
# Strip any leading non-digits from figbass (e.g., M43 -> 43)
figbassMatch = re.match(r'^\D*(\d.*|)', thisRN.figuresWritten)
if figbassMatch is not None:
thisEntry.figbass = figbassMatch.group(1)
else:
thisEntry.figbass = ''
thisEntry.changes = None # TODO
thisEntry.relativeroot = relativeroot
thisEntry.phraseend = None
thisInfo = [
getattr(thisEntry, name, thisRN.editorial.get(name, ''))
for name in self.dcml_headers
]
tsvData.append(thisInfo)
return tsvData
def _m21ToTsv_v2(self) -> list[list[str]]:
tsvData: list[list[str]] = []
# take the global_key from the first item
first_rn = self.m21Stream[roman.RomanNumeral].first()
if first_rn is None:
return tsvData
global_key_obj = first_rn.key
global_key = global_key_obj.tonicPitchNameWithCase
for thisRN in self.m21Stream.recurse().getElementsByClass(
[roman.RomanNumeral, harmony.NoChord]
):
thisEntry = TabChordV2()
thisEntry.mn = thisRN.measureNumber
# for a reason I do not understand, thisRN.beat in V2 seems to
# always be beat 1. In neither v1 is thisRN set explicitly;
# the offset/beat seems to be determined by
# m21Measure.insert(offsetInMeasure, thisM21Chord) above. I'm at
# a loss why there is an issue here but using thisRN.offset works
# just fine.
thisEntry.mn_onset = thisRN.offset / 4
timesig = thisRN.getContextByClass(meter.TimeSignature)
if timesig is None:
thisEntry.timesig = ''
else:
thisEntry.timesig = timesig.ratioString
thisEntry.global_key = global_key
if isinstance(thisRN, harmony.NoChord):
thisEntry.numeral = '@none'
thisEntry.chord = '@none'
else:
local_key = localKeyAsRn(thisRN.key, global_key_obj)
relativeroot = None
if thisRN.secondaryRomanNumeral:
relativeroot = thisRN.secondaryRomanNumeral.figure
relativeroot = characterSwaps(
relativeroot, isMinor(local_key), direction='m21-DCML'
)
# We replace the "d" annotation for Mm7 chords on degrees other than
# V because it is not used by the DCML standard
# NB: slightly different from DCML: no key.
thisEntry.chord = thisRN.figure.replace('d', '', 1)
thisEntry.pedal = None
thisEntry.numeral = thisRN.romanNumeral
thisEntry.form = getForm(thisRN)
# Strip any leading non-digits from figbass (e.g., M43 -> 43)
figbassm = re.match(r'^\D*(\d.*|)', thisRN.figuresWritten)
# implementing the following check according to the review
# at https://github.com/cuthbertLab/music21/pull/1267/files/a1ad510356697f393bf6b636af8f45e81ad6ccc8#r936472302 #pylint: disable=line-too-long
# but the match should always exist because either:
# 1. there is a digit in the string, in which case it matches
# because of the left side of the alternation operator
# 2. there is no digit in the string, in which case it matches
# because of the right side of the alternation operator
# (an empty string)
if figbassm is not None:
thisEntry.figbass = figbassm.group(1)
else:
thisEntry.figbass = ''
thisEntry.changes = None
thisEntry.relativeroot = relativeroot
thisEntry.phraseend = None
thisEntry.local_key = local_key
thisInfo = [
getattr(thisEntry, name, thisRN.editorial.get(name, ''))
for name in self.dcml_headers
]
tsvData.append(thisInfo)
return tsvData
def write(self, filePathAndName: str):
'''
Writes a list of lists (e.g. from m21ToTsv()) to a tsv file.
'''
with open(filePathAndName, 'a', newline='', encoding='utf-8') as csvFile:
csvOut = csv.writer(csvFile,
delimiter='\t',
quotechar='"',
quoting=csv.QUOTE_MINIMAL)
csvOut.writerow(self.dcml_headers)
for thisEntry in self.tsvData:
csvOut.writerow(thisEntry)
# ------------------------------------------------------------------------------
def getForm(rn: roman.RomanNumeral) -> str:
'''
Takes a music21.roman.RomanNumeral object and returns the string indicating
'form' expected by the DCML standard.
>>> romanText.tsvConverter.getForm(roman.RomanNumeral('V'))
''
>>> romanText.tsvConverter.getForm(roman.RomanNumeral('viio7'))
'o'
>>> romanText.tsvConverter.getForm(roman.RomanNumeral('IVM7'))
'M'
>>> romanText.tsvConverter.getForm(roman.RomanNumeral('III+'))
'+'
>>> romanText.tsvConverter.getForm(roman.RomanNumeral('IV+M7'))
'+M'
>>> romanText.tsvConverter.getForm(roman.RomanNumeral('viiø7'))
'%'
'''
if 'ø' in rn.figure:
return '%'
if 'o' in rn.figure:
return 'o'
if '+M' in rn.figure:
# Not sure whether there is more than one way for an augmented major seventh to be
# indicated, in which case this condition needs to be updated.
return '+M'
if '+' in rn.figure:
return '+'
if 'M' in rn.figure:
return 'M'
return ''
def handleAddedTones(dcmlChord: str) -> str:
'''
Converts DCML added-tone syntax to music21.
>>> romanText.tsvConverter.handleAddedTones('V(64)')
'Cad64'
>>> romanText.tsvConverter.handleAddedTones('i(4+2)')
'i[no3][add4][add2]'
>>> romanText.tsvConverter.handleAddedTones('Viio7(b4-5)/V')
'Viio7[no3][no5][addb4]/V'
When in root position, 7 does not replace 8:
>>> romanText.tsvConverter.handleAddedTones('vi(#74)')
'vi[no3][add#7][add4]'
When not in root position, 7 does replace 8:
>>> romanText.tsvConverter.handleAddedTones('ii6(11#7b6)')
'ii6[no8][no5][add11][add#7][addb6]'
'0' can be used to indicate root-replacement by 7 in a root-position chord.
We need to change '0' to '7' because music21 changes the 0 to 'o' (i.e.,
a diminished chord).
>>> romanText.tsvConverter.handleAddedTones('i(#0)')
'i[no1][add#7]'
'''
m = re.match(
r'(?P<primary>.*?(?P<figure>\d*(?:/\d+)*))\((?P<added_tones>.*)\)(?P<secondary>/.*)?',
dcmlChord
)
if not m:
return dcmlChord
primary = m.group('primary')
added_tones = m.group('added_tones')
secondary = m.group('secondary') if m.group('secondary') is not None else ''
figure = m.group('figure')
if primary == 'V' and added_tones == '64':