-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmusicxml2ly.py
More file actions
executable file
·3534 lines (3025 loc) · 127 KB
/
Copy pathmusicxml2ly.py
File metadata and controls
executable file
·3534 lines (3025 loc) · 127 KB
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
#!/usr/bin/env python3 -tt
# -*- coding: utf-8 -*-
from rational import Rational
import musicexp
import musicxml
import musicxml2ly_conversion
import utilities
import lilylib as ly
import gettext
import optparse
import sys
import re
import os
import codecs
import zipfile
import tempfile
import io
import warnings
from pprint import pprint
from functools import reduce
"""
This generic code used for all python scripts.
The quotes are to ensure that the source .py file can still be
run as a python script, but does not include any sys.path handling.
Otherwise, the lilypond-book calls inside the build
might modify installed .pyc files.
"""
for d in ['/usr/local/share/lilypond/2.21.2',
'/usr/local/lib/lilypond/2.21.2']:
sys.path.insert(0, os.path.join(d, 'python'))
# dynamic relocation, for GUB binaries.
bindir = os.path.abspath(os.path.dirname(sys.argv[0]))
for p in ['share', 'lib']:
datadir = os.path.abspath(bindir + '/../%s/lilypond/current/python/' % p)
sys.path.insert(0, datadir)
# Python scripts executed during 'make test' and 'make test-baseline'
# must use their own versions of the scripts and the files loaded by
# those scripts. Assume to be in such a situation if the path to the
# script ends with 'scripts/out'.
if bindir.endswith(r'/scripts/out'):
# only works for in-tree builds
sys.path.insert(0, bindir + r'/../../python')
# build in separate dir, but incorrect.
sys.path.insert(0, bindir + r'/../../python/out')
"""
"""
# Load translation and install _() into Python's builtins namespace.
gettext.install(
'lilypond', '/usr/local/share/locale')
lilypond_version = "2.20.0"
# Store command-line options in a global variable, so we can access them everywhere
options = None
class Conversion_Settings:
def __init__(self):
self.ignore_beaming = False
self.convert_stem_directions = False
self.convert_rest_positions = True
conversion_settings = Conversion_Settings()
# Use a global variable to store the setting needed inside a \layout block.
# whenever we need to change a setting or add/remove an engraver, we can access
# this layout and add the corresponding settings
layout_information = musicexp.Layout()
# Use a global variable to store the setting needed inside a \paper block.
paper = musicexp.Paper()
needed_additional_definitions = []
additional_definitions = {
"tuplet-note-wrapper": """ % a formatter function, which is simply a wrapper around an existing
% tuplet formatter function. It takes the value returned by the given
% function and appends a note of given length.
# (define-public ((tuplet-number::append-note-wrapper function note) grob)
(let* ((txt (if function (function grob) #f)))
(if txt
(markup txt #:fontsize -5 #:note note UP)
(markup #:fontsize -5 #:note note UP)
)
)
)""",
"tuplet-non-default-denominator": """#(define ((tuplet-number::non-default-tuplet-denominator-text denominator) grob)
(number->string (if denominator
denominator
(ly:event-property (event-cause grob) 'denominator))))
""",
"tuplet-non-default-fraction": """#(define ((tuplet-number::non-default-tuplet-fraction-text denominator numerator) grob)
(let* ((ev (event-cause grob))
(den (if denominator denominator (ly:event-property ev 'denominator)))
(num (if numerator numerator (ly:event-property ev 'numerator))))
(format #f "~a:~a" den num)))
""",
}
def round_to_two_digits(val):
return round(val * 100) / 100
def extract_paper_information(score_partwise):
defaults = score_partwise.get_maybe_exist_named_child('defaults')
if not defaults:
return None
tenths = -1
scaling = defaults.get_maybe_exist_named_child('scaling')
default_tenths_to_millimeters_ratio = 0.175
default_staff_size = 20
if scaling:
mm = scaling.get_named_child('millimeters')
mm = float(mm.get_text())
tn = scaling.get_maybe_exist_named_child('tenths')
tn = float(tn.get_text())
# The variable 'tenths' is actually a ratio, NOT the value of <tenths>.
# TODO: rename and replace.
tenths = mm / tn
ratio = tenths / default_tenths_to_millimeters_ratio
staff_size = default_staff_size * ratio
if 1 < staff_size < 100:
paper.global_staff_size = staff_size
else:
msg = "paper.global_staff_size %s is too large, using defaults=20" % staff_size
warnings.warn(msg)
paper.global_staff_size = 20
# We need the scaling(i.e. the size of staff tenths for everything!
if tenths < 0:
return None
def from_tenths(txt):
return round_to_two_digits(float(txt) * tenths / 10)
def set_paper_variable(varname, parent, element_name):
el = parent.get_maybe_exist_named_child(element_name)
if el: # Convert to cm from tenths
setattr(paper, varname, from_tenths(el.get_text()))
pagelayout = defaults.get_maybe_exist_named_child('page-layout')
if pagelayout:
# TODO: How can one have different margins for even and odd pages???
set_paper_variable("page_height", pagelayout, 'page-height')
set_paper_variable("page_width", pagelayout, 'page-width')
if conversion_settings.convert_page_margins:
pmargins = pagelayout.get_named_children('page-margins')
for pm in pmargins:
set_paper_variable("left_margin", pm, 'left-margin')
set_paper_variable("right_margin", pm, 'right-margin')
set_paper_variable("bottom_margin", pm, 'bottom-margin')
set_paper_variable("top_margin", pm, 'top-margin')
systemlayout = defaults.get_maybe_exist_named_child('system-layout')
if systemlayout:
sl = systemlayout.get_maybe_exist_named_child('system-margins')
if sl:
set_paper_variable("system_left_margin", sl, 'left-margin')
set_paper_variable("system_right_margin", sl, 'right-margin')
set_paper_variable("system_distance", systemlayout, 'system-distance')
set_paper_variable("top_system_distance",
systemlayout, 'top-system-distance')
stafflayout = defaults.get_named_children('staff-layout')
for sl in stafflayout:
nr = getattr(sl, 'number', 1)
dist = sl.get_named_child('staff-distance')
# TODO: the staff distance needs to be set in the Staff context!!!
# TODO: Finish appearance?, music-font?, word-font?, lyric-font*, lyric-language*
appearance = defaults.get_named_child('appearance')
if appearance:
lws = appearance.get_named_children('line-width')
for lw in lws:
# Possible types are: beam, bracket, dashes,
# enclosure, ending, extend, heavy barline, leger,
# light barline, octave shift, pedal, slur middle, slur tip,
# staff, stem, tie middle, tie tip, tuplet bracket, and wedge
tp = lw.type
w = from_tenths(lw.get_text())
# TODO: Do something with these values!
nss = appearance.get_named_children('note-size')
for ns in nss:
# Possible types are: cue, grace and large
tp = ns.type
sz = from_tenths(ns.get_text())
# TODO: Do something with these values!
# <other-appearance> elements have no specified meaning
rawmusicfont = defaults.get_named_child('music-font')
if rawmusicfont:
# TODO: Convert the font
pass
rawwordfont = defaults.get_named_child('word-font')
if rawwordfont:
# TODO: Convert the font
pass
rawlyricsfonts = defaults.get_named_children('lyric-font')
for lyricsfont in rawlyricsfonts:
# TODO: Convert the font
pass
return paper
credit_dict = {
None: None,
'': None,
'page number': None, # TODO: what is it used for ?
'title': 'title',
'subtitle': 'subtitle',
'composer': 'composer',
'arranger': 'arranger',
'lyricist': 'poet',
'rights': 'copyright'
}
# score information is contained in the <work>, <identification> or <movement-title> tags
# extract those into a hash, indexed by proper lilypond header attributes
def extract_score_information(tree):
header = musicexp.Header()
def set_if_exists(field, value):
if value:
header.set_field(field, utilities.escape_ly_output_string(value))
header.set_field('tagline', utilities.escape_ly_output_string(''))
movement_title = tree.get_maybe_exist_named_child('movement-title')
movement_number = tree.get_maybe_exist_named_child('movement-number')
if movement_title:
set_if_exists('title', movement_title.get_text())
if movement_number:
set_if_exists('movementnumber', movement_number.get_text())
# set_if_exists('piece', movement_number.get_text()) # the movement number should be visible in the score.
work = tree.get_maybe_exist_named_child('work')
if work:
work_number = work.get_work_number()
work_title = work.get_work_title()
# Overwrite the title from movement-title with work->title
set_if_exists('title', work.get_work_title())
# set_if_exists('opus', work.get_work_number())
# Use movement-title as subtitle
# if movement_title:
# set_if_exists('subtitle', movement_title.get_text())
# TODO: Translation of opus element. Not to be confused with opus in LilyPond. MusicXML opus is a document element for opus DTD
identifications = tree.get_named_children('identification')
for ids in identifications:
# set_if_exists('copyright', ids.get_rights())
# set_if_exists('composer', ids.get_composer())
# set_if_exists('arranger', ids.get_arranger())
# set_if_exists('editor', ids.get_editor())
# set_if_exists('poet', ids.get_poet())
# set_if_exists('encodingsoftware', ids.get_encoding_software())
# set_if_exists('encodingdate', ids.get_encoding_date())
# set_if_exists('encoder', ids.get_encoding_person())
# set_if_exists('encodingdescription', ids.get_encoding_description())
# set_if_exists('source', ids.get_source())
# <miscellaneous><miscellaneous-field name="description"> ... becomes
# \header { texidoc = ...
# set_if_exists('texidoc', ids.get_file_description());
# Finally, apply the required compatibility modes
# Some applications created wrong MusicXML files, so we need to
# apply some compatibility mode, e.g. ignoring some features/tags
# in those files
software = ids.get_encoding_software_list()
# Case 1: "Sibelius 5.1" with the "Dolet 3.4 for Sibelius" plugin
# is missing all beam ends => ignore all beaming information
ignore_beaming_software = {
"Dolet 4 for Sibelius, Beta 2": "Dolet 4 for Sibelius, Beta 2",
"Dolet 3.5 for Sibelius": "Dolet 3.5 for Sibelius",
"Dolet 3.4 for Sibelius": "Dolet 3.4 for Sibelius",
"Dolet 3.3 for Sibelius": "Dolet 3.3 for Sibelius",
"Dolet 3.2 for Sibelius": "Dolet 3.2 for Sibelius",
"Dolet 3.1 for Sibelius": "Dolet 3.1 for Sibelius",
"Dolet for Sibelius 1.3": "Dolet for Sibelius 1.3",
"Noteworthy Composer": "Noteworthy Composer's nwc2xm[",
}
for s in software:
app_description = ignore_beaming_software.get(s, False)
if app_description:
conversion_settings.ignore_beaming = True
ly.warning(_("Encountered file created by %s, containing "
"wrong beaming information. All beaming "
"information in the MusicXML file will be "
"ignored") % app_description)
credits = tree.get_named_children('credit')
has_composer = False
for cred in credits:
type = credit_dict.get(cred.get_type())
if(type == None):
type = credit_dict.get(cred.find_type(credits))
if(type == 'composer'):
if(has_composer):
type = 'poet'
else:
has_composer = True
set_if_exists(type, cred.get_text())
elif(type == 'title'):
if(not(work) and not(movement_title)):
set_if_exists('title', cred.get_text())
# elif(not(movement_title)): #bullshit!
# set_if_exists('subtitle', cred.get_text()) #bullshit! otherwise both title and subtitle show the work-title.
elif(type == None):
pass
else:
pass
set_if_exists(type, cred.get_text())
# TODO: Check for other unsupported features
return header
class PartGroupInfo:
def __init__(self):
self.start = {}
self.end = {}
def is_empty(self):
return len(self.start) + len(self.end) == 0
def add_start(self, g):
self.start[getattr(g, 'number', "1")] = g
def add_end(self, g):
self.end[getattr(g, 'number', "1")] = g
def print_ly(self, printer):
ly.warning(_("Unprocessed PartGroupInfo %s encountered") % self)
def ly_expression(self):
ly.warning(_("Unprocessed PartGroupInfo %s encountered") % self)
return ''
def staff_attributes_to_string_tunings(mxl_attr):
details = mxl_attr.get_maybe_exist_named_child('staff-details')
if not details:
return []
lines = 6
staff_lines = details.get_maybe_exist_named_child('staff-lines')
if staff_lines:
lines = int(staff_lines.get_text())
tunings = [musicexp.Pitch()] * lines
staff_tunings = details.get_named_children('staff-tuning')
for i in staff_tunings:
p = musicexp.Pitch()
line = 0
try:
line = int(i.line) - 1
except ValueError:
pass
tunings[line] = p
step = i.get_named_child('tuning-step')
step = step.get_text().strip()
p.step = musicxml2ly_conversion.musicxml_step_to_lily(step)
octave = i.get_named_child('tuning-octave')
octave = octave.get_text().strip()
p.octave = int(octave) - 4
alter = i.get_named_child('tuning-alter')
if alter:
p.alteration = int(alter.get_text().strip())
# lilypond seems to use the opposite ordering than MusicXML...
tunings.reverse()
return tunings
def staff_attributes_to_lily_staff(mxl_attr):
if not mxl_attr:
return musicexp.Staff()
(staff_id, attributes) = list(mxl_attr.items())[0]
# distinguish by clef:
# percussion(percussion and rhythmic), tab, and everything else
clef_sign = None
clef = attributes.get_maybe_exist_named_child('clef')
if clef:
sign = clef.get_maybe_exist_named_child('sign')
if sign:
clef_sign = {"percussion": "percussion",
"TAB": "tab"}.get(sign.get_text(), None)
lines = 5
details = attributes.get_named_children('staff-details')
for d in details:
staff_lines = d.get_maybe_exist_named_child('staff-lines')
if staff_lines:
lines = int(staff_lines.get_text())
# TODO: Handle other staff attributes like staff-space, etc.
staff = None
if clef_sign == "percussion" and lines == 1:
staff = musicexp.RhythmicStaff()
elif clef_sign == "percussion":
staff = musicexp.DrumStaff()
# staff.drum_style_table = ???
elif clef_sign == "tab":
staff = musicexp.TabStaff()
staff.string_tunings = staff_attributes_to_string_tunings(attributes)
# staff.tablature_format = ???
else:
staff = musicexp.Staff()
# TODO: Handle case with lines != 5!
if lines != 5:
staff.add_context_modification(
"\\override StaffSymbol #'line-count = #%s" % lines)
return staff
def extract_instrument_sound(score_part):
score_instrument = score_part.get_maybe_exist_named_child(
'score-instrument')
if not score_instrument:
return None
sound = score_instrument.get_maybe_exist_named_child('instrument-sound')
if sound:
return utilities.musicxml_sound_to_lilypond_midi_instrument(sound.get_text())
def extract_score_structure(part_list, staffinfo):
score = musicexp.Score()
structure = musicexp.StaffGroup(None)
score.set_contents(structure)
if not part_list:
return structure
def read_score_part(el):
if not isinstance(el, musicxml.Score_part):
return
# Depending on the attributes of the first measure, we create different
# types of staves(Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
staff = staff_attributes_to_lily_staff(staffinfo.get(el.id, None))
if not staff:
return None
staff.id = el.id
partname = el.get_maybe_exist_named_child('part-name')
# Finale gives unnamed parts the name "MusicXML Part" automatically!
if partname and partname.get_text() != "MusicXML Part":
staff.instrument_name = partname.get_text()
# part-name-display overrides part-name!
partname = el.get_maybe_exist_named_child("part-name-display")
if partname:
staff.instrument_name = extract_display_text(partname)
if hasattr(options, 'midi') and options.midi:
staff.sound = extract_instrument_sound(el)
if staff.instrument_name:
paper.indent = max(paper.indent, len(staff.instrument_name))
paper.instrument_names.append(staff.instrument_name)
partdisplay = el.get_maybe_exist_named_child('part-abbreviation')
if partdisplay:
staff.short_instrument_name = partdisplay.get_text()
# part-abbreviation-display overrides part-abbreviation!
partdisplay = el.get_maybe_exist_named_child(
"part-abbreviation-display")
if partdisplay:
staff.short_instrument_name = extract_display_text(partdisplay)
# TODO: Read in the MIDI device / instrument
if staff.short_instrument_name:
paper.short_indent = max(
paper.short_indent, len(staff.short_instrument_name))
return staff
def read_score_group(el):
if not isinstance(el, musicxml.Part_group):
return
group = musicexp.StaffGroup()
if hasattr(el, 'number'):
id = el.number
group.id = id
# currentgroups_dict[id] = group
# currentgroups.append(id)
if el.get_maybe_exist_named_child('group-name'):
group.instrument_name = el.get_maybe_exist_named_child(
'group-name').get_text()
if el.get_maybe_exist_named_child('group-abbreviation'):
group.short_instrument_name = el.get_maybe_exist_named_child(
'group-abbreviation').get_text()
if el.get_maybe_exist_named_child('group-symbol'):
group.symbol = el.get_maybe_exist_named_child(
'group-symbol').get_text()
if el.get_maybe_exist_named_child('group-barline'):
group.spanbar = el.get_maybe_exist_named_child(
'group-barline').get_text()
return group
parts_groups = part_list.get_all_children()
# the start/end group tags are not necessarily ordered correctly and groups
# might even overlap, so we can't go through the children sequentially!
# 1) Replace all Score_part objects by their corresponding Staff objects,
# also collect all group start/stop points into one PartGroupInfo object
staves = []
group_info = PartGroupInfo()
for el in parts_groups:
if isinstance(el, musicxml.Score_part):
if not group_info.is_empty():
staves.append(group_info)
group_info = PartGroupInfo()
staff = read_score_part(el)
if staff:
staves.append(staff)
elif isinstance(el, musicxml.Part_group):
if el.type == "start":
group_info.add_start(el)
elif el.type == "stop":
group_info.add_end(el)
if not group_info.is_empty():
staves.append(group_info)
# 2) Now, detect the groups:
group_starts = []
pos = 0
while pos < len(staves):
el = staves[pos]
if isinstance(el, PartGroupInfo):
prev_start = 0
if len(group_starts) > 0:
prev_start = group_starts[-1]
elif len(el.end) > 0: # no group to end here
el.end = {}
if len(el.end) > 0: # closes an existing group
ends = list(el.end.keys())
prev_started = list(staves[prev_start].start.keys())
grpid = None
intersection = [x for x in prev_started if x in ends]
if len(intersection) > 0:
grpid = intersection[0]
else:
# Close the last started group
grpid = list(staves[prev_start].start.keys())[0]
# Find the corresponding closing tag and remove it!
j = pos + 1
foundclosing = False
while j < len(staves) and not foundclosing:
if isinstance(staves[j], PartGroupInfo) and grpid in staves[j].end:
foundclosing = True
del staves[j].end[grpid]
if staves[j].is_empty():
del staves[j]
j += 1
grpobj = staves[prev_start].start[grpid]
group = read_score_group(grpobj)
# remove the id from both the start and end
if grpid in el.end:
del el.end[grpid]
del staves[prev_start].start[grpid]
if el.is_empty():
del staves[pos]
# replace the staves with the whole group
for j in staves[(prev_start + 1):pos]:
group.append_staff(j)
del staves[(prev_start + 1):pos]
staves.insert(prev_start + 1, group)
# reset pos so that we continue at the correct position
pos = prev_start
# remove an empty start group
if staves[prev_start].is_empty():
del staves[prev_start]
group_starts.remove(prev_start)
pos -= 1
elif len(el.start) > 0: # starts new part groups
group_starts.append(pos)
pos += 1
for i in staves:
structure.append_staff(i)
return score
def musicxml_partial_to_lily(partial_len):
if partial_len > 0:
p = musicexp.Partial()
p.partial = musicxml2ly_conversion.rational_to_lily_duration(
partial_len)
return p
else:
return None
# Detect repeats and alternative endings in the chord event list(music_list)
# and convert them to the corresponding musicexp objects, containing nested
# music
def group_repeats(music_list):
repeat_replaced = True
music_start = 0
i = 0
# Walk through the list of expressions, looking for repeat structure
# (repeat start/end, corresponding endings). If we find one, try to find the
# last event of the repeat, replace the whole structure and start over again.
# For nested repeats, as soon as we encounter another starting repeat bar,
# treat that one first, and start over for the outer repeat.
while repeat_replaced and i < 100:
i += 1
repeat_start = -1 # position of repeat start / end
repeat_end = -1 # position of repeat start / end
repeat_times = 0
ending_start = -1 # position of current ending start
endings = [] # list of already finished endings
pos = 0
last = len(music_list) - 1
repeat_replaced = False
final_marker = 0
while pos < len(music_list) and not repeat_replaced:
e = music_list[pos]
repeat_finished = False
if isinstance(e, musicxml2ly_conversion.RepeatMarker):
if not repeat_times and e.times:
repeat_times = e.times
if e.direction == -1:
if repeat_end >= 0:
repeat_finished = True
else:
repeat_start = pos
repeat_end = -1
ending_start = -1
endings = []
elif e.direction == 1:
if repeat_start < 0:
repeat_start = 0
if repeat_end < 0:
repeat_end = pos
final_marker = pos
elif isinstance(e, musicxml2ly_conversion.EndingMarker):
if e.direction == -1:
if repeat_start < 0:
repeat_start = 0
if repeat_end < 0:
repeat_end = pos
ending_start = pos
elif e.direction == 1:
if ending_start < 0:
ending_start = 0
endings.append([ending_start, pos])
ending_start = -1
final_marker = pos
elif not isinstance(e, musicexp.BarLine):
# As soon as we encounter an element when repeat start and end
# is set and we are not inside an alternative ending,
# this whole repeat structure is finished => replace it
if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
repeat_finished = True
# Finish off all repeats without explicit ending bar(e.g. when
# we convert only one page of a multi-page score with repeats)
if pos == last and repeat_start >= 0:
repeat_finished = True
final_marker = pos
if repeat_end < 0:
repeat_end = pos
if ending_start >= 0:
endings.append([ending_start, pos])
ending_start = -1
if repeat_finished:
# We found the whole structure replace it!
r = musicexp.RepeatedMusic()
if repeat_times <= 0:
repeat_times = 2
r.repeat_count = repeat_times
# don't erase the first element for "implicit" repeats(i.e. no
# starting repeat bars at the very beginning)
start = repeat_start + 1
if repeat_start == music_start:
start = music_start
r.set_music(music_list[start:repeat_end])
for(start, end) in endings:
s = musicexp.SequentialMusic()
s.elements = music_list[start + 1:end]
r.add_ending(s)
del music_list[repeat_start:final_marker + 1]
music_list.insert(repeat_start, r)
repeat_replaced = True
pos += 1
# TODO: Implement repeats until the end without explicit ending bar
return music_list
# Extract the settings for tuplets from the <notations><tuplet> and the
# <time-modification> elements of the note:
def musicxml_tuplet_to_lily(tuplet_elt, time_modification):
tsm = musicexp.TimeScaledMusic()
fraction = (1, 1)
if time_modification:
fraction = time_modification.get_fraction()
tsm.numerator = fraction[0]
tsm.denominator = fraction[1]
normal_type = tuplet_elt.get_normal_type()
if not normal_type and time_modification:
normal_type = time_modification.get_normal_type()
if not normal_type and time_modification:
note = time_modification.get_parent()
if note:
normal_type = note.get_duration_info()
if normal_type:
normal_note = musicexp.Duration()
(normal_note.duration_log, normal_note.dots) = normal_type
tsm.normal_type = normal_note
actual_type = tuplet_elt.get_actual_type()
if actual_type:
actual_note = musicexp.Duration()
(actual_note.duration_log, actual_note.dots) = actual_type
tsm.actual_type = actual_note
# Obtain non-default nrs of notes from the tuplet object!
tsm.display_numerator = tuplet_elt.get_normal_nr()
tsm.display_denominator = tuplet_elt.get_actual_nr()
if hasattr(tuplet_elt, 'bracket') and tuplet_elt.bracket == "no":
tsm.display_bracket = None
elif hasattr(tuplet_elt, 'line-shape') and getattr(tuplet_elt, 'line-shape') == "curved":
tsm.display_bracket = "curved"
else:
tsm.display_bracket = "bracket"
display_values = {"none": None, "actual": "actual", "both": "both"}
if hasattr(tuplet_elt, "show-number"):
tsm.display_number = display_values.get(
getattr(tuplet_elt, "show-number"), "actual")
if hasattr(tuplet_elt, "show-type"):
tsm.display_type = display_values.get(
getattr(tuplet_elt, "show-type"), None)
return tsm
def group_tuplets(music_list, events):
"""Collect Musics from
MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
"""
indices = []
brackets = {}
j = 0
for(ev_chord, tuplet_elt, time_modification) in events:
while(j < len(music_list)):
if music_list[j] == ev_chord:
break
j += 1
nr = 0
if hasattr(tuplet_elt, 'number'):
nr = getattr(tuplet_elt, 'number')
if tuplet_elt.type == 'start':
tuplet_object = musicxml_tuplet_to_lily(
tuplet_elt, time_modification)
tuplet_info = [j, None, tuplet_object]
indices.append(tuplet_info)
brackets[nr] = tuplet_info
elif tuplet_elt.type == 'stop':
bracket_info = brackets.get(nr, None)
if bracket_info:
bracket_info[1] = j # Set the ending position to j
del brackets[nr]
new_list = []
last = 0
for(i1, i2, tsm) in indices:
if i1 > i2:
continue
new_list.extend(music_list[last:i1])
seq = musicexp.SequentialMusic()
last = i2 + 1
# At this point music_list[i1:last] encompasses all the notes of the
# tuplet. There might be dynamics following this range, however, which
# apply to the last note of the tuplet. Advance last to include them
# in the range.
while last < len(music_list) and isinstance(music_list[last], musicexp.DynamicsEvent):
last += 1
seq.elements = music_list[i1:last]
tsm.element = seq
new_list.append(tsm)
# TODO: Handle nested tuplets!!!!
new_list.extend(music_list[last:])
return new_list
def musicxml_clef_to_lily(attributes):
change = musicexp.ClefChange()
(change.type, change.position, change.octave) = attributes.get_clef_information()
return change
def musicxml_time_to_lily(attributes):
change = musicexp.TimeSignatureChange()
# time signature function
if hasattr(options, 'shift_meter') and options.shift_meter:
tmp_meter = options.shift_meter.split("/", 1)
sig = [int(tmp_meter[0]), int(tmp_meter[1])]
change.originalFractions = attributes.get_time_signature()
else:
sig = attributes.get_time_signature()
if not sig:
return None
change.fractions = sig
time_elm = attributes.get_maybe_exist_named_child('time')
if time_elm and hasattr(time_elm, 'symbol'):
change.style = {'single-number': "'single-digit",
'cut': None,
'common': None,
'normal': "'()"}.get(time_elm.symbol, "'()")
else:
change.style = "'()"
if getattr(time_elm, 'print-object', 'yes') == 'no':
change.visible = False
# TODO: Handle senza-misura measures
# TODO: What shall we do if the symbol clashes with the sig? e.g. "cut"
# with 3/8 or "single-number" with(2+3)/8 or 3/8+2/4?
return change
def musicxml_key_to_lily(attributes):
key_sig = attributes.get_key_signature()
if not key_sig or not(isinstance(key_sig, list) or isinstance(key_sig, tuple)):
ly.warning(_("Unable to extract key signature!"))
return None
change = musicexp.KeySignatureChange()
if len(key_sig) == 2 and not isinstance(key_sig[0], list):
# standard key signature,(fifths, mode)
(fifths, mode) = key_sig
change.mode = mode
start_pitch = musicexp.Pitch()
start_pitch.octave = 0
try:
(n, a) = {
'major': (0, 0),
'minor': (5, 0),
'ionian': (0, 0),
'dorian': (1, 0),
'phrygian': (2, 0),
'lydian': (3, 0),
'mixolydian': (4, 0),
'aeolian': (5, 0),
'locrian': (6, 0),
}[mode]
start_pitch.step = n
start_pitch.alteration = a
except KeyError:
ly.warning(_("unknown mode %s, expecting 'major' or 'minor' "
"or a church mode!") % mode)
fifth = musicexp.Pitch()
fifth.step = 4
if fifths < 0:
fifths *= -1
fifth.step *= -1
fifth.normalize()
for x in range(fifths):
start_pitch = start_pitch.transposed(fifth)
change.tonic = start_pitch
else:
# Non-standard key signature of the form [[step,alter<,octave>],...]
# MusicXML contains C,D,E,F,G,A,B as steps, lily uses 0-7, so convert
alterations = []
for k in key_sig:
k[0] = musicxml2ly_conversion.musicxml_step_to_lily(k[0])
alterations.append(k)
change.non_standard_alterations = alterations
return change
def musicxml_transpose_to_lily(attributes):
transpose = attributes.get_transposition()
if not transpose:
return None
shift = musicexp.Pitch()
octave_change = transpose.get_maybe_exist_named_child('octave-change')
if octave_change:
shift.octave = int(octave_change.get_text())
chromatic_shift = int(transpose.get_named_child('chromatic').get_text())
chromatic_shift_normalized = chromatic_shift % 12
(shift.step, shift.alteration) = [
(0, 0), (0, 1), (1, 0), (2, -1), (2, 0),
(3, 0), (3, 1), (4, 0), (5, -1), (5, 0),
(6, -1), (6, 0)][chromatic_shift_normalized]
shift.octave += (chromatic_shift - chromatic_shift_normalized) // 12
diatonic = transpose.get_maybe_exist_named_child('diatonic')
if diatonic:
diatonic_step = int(diatonic.get_text()) % 7
if diatonic_step != shift.step:
# We got the alter incorrect!
old_semitones = shift.semitones()
shift.step = diatonic_step
new_semitones = shift.semitones()
shift.alteration += old_semitones - new_semitones
transposition = musicexp.Transposition()
transposition.pitch = musicexp.Pitch().transposed(shift)
return transposition
def musicxml_staff_details_to_lily(attributes):
details = attributes.get_maybe_exist_named_child('staff-details')
if not details:
return None
# TODO: Handle staff-type, staff-lines, staff-tuning, capo, staff-size
ret = []
stafflines = details.get_maybe_exist_named_child('staff-lines')
if stafflines:
lines = int(stafflines.get_text())
lines_event = musicexp.StaffLinesEvent(lines)
ret.append(lines_event)
return ret
def musicxml_attributes_to_lily(attrs):
elts = []
attr_dispatch = {
'clef': musicxml_clef_to_lily,
'time': musicxml_time_to_lily,
'key': musicxml_key_to_lily,
'transpose': musicxml_transpose_to_lily,
'staff-details': musicxml_staff_details_to_lily,
}
for (k, func) in list(attr_dispatch.items()):
children = attrs.get_named_children(k)
if children:
ev = func(attrs)
if isinstance(ev, list):
for e in ev:
elts.append(e)
elif ev:
elts.append(ev)
return elts
def extract_display_text(el):
child = el.get_maybe_exist_named_child("display-text")
if child:
return child.get_text()
else:
return False
def musicxml_print_to_lily(el):
# TODO: Implement other print attributes
# <!ELEMENT print (page-layout?, system-layout?, staff-layout*,
# measure-layout?, measure-numbering?, part-name-display?,
# part-abbreviation-display?)>
# <!ATTLIST print
# staff-spacing %tenths; #IMPLIED
# new-system %yes-no; #IMPLIED
# new-page %yes-no-number; #IMPLIED
# blank-page NMTOKEN #IMPLIED
# page-number CDATA #IMPLIED