9 from gettext import gettext as _
20 from rational import Rational
24 sys.stderr.write (str + '\n')
27 def error_message (str):
28 sys.stderr.write (str + '\n')
31 # score information is contained in the <work>, <identification> or <movement-title> tags
32 # extract those into a hash, indexed by proper lilypond header attributes
33 def extract_score_information (tree):
34 header = musicexp.Header ()
35 def set_if_exists (field, value):
37 header.set_field (field, musicxml.escape_ly_output_string (value))
39 work = tree.get_maybe_exist_named_child ('work')
41 set_if_exists ('title', work.get_work_title ())
42 set_if_exists ('worknumber', work.get_work_number ())
43 set_if_exists ('opus', work.get_opus ())
45 movement_title = tree.get_maybe_exist_named_child ('movement-title')
47 set_if_exists ('title', movement_title.get_text ())
49 identifications = tree.get_named_children ('identification')
50 for ids in identifications:
51 set_if_exists ('copyright', ids.get_rights ())
52 set_if_exists ('composer', ids.get_composer ())
53 set_if_exists ('arranger', ids.get_arranger ())
54 set_if_exists ('editor', ids.get_editor ())
55 set_if_exists ('poet', ids.get_poet ())
57 set_if_exists ('tagline', ids.get_encoding_software ())
58 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
59 set_if_exists ('encodingdate', ids.get_encoding_date ())
60 set_if_exists ('encoder', ids.get_encoding_person ())
61 set_if_exists ('encodingdescription', ids.get_encoding_description ())
66 def extract_score_layout (part_list):
67 layout = musicexp.StaffGroup (None)
68 currentgroups_dict = {}
73 def insert_into_layout (object):
74 if len (currentgroups) > 0:
75 group_to_insert = currentgroups_dict.get (currentgroups [-1], layout)
77 group_to_insert = layout
78 group_to_insert.appendStaff (object)
79 return group_to_insert
81 def read_score_part (el):
82 if not isinstance (el, musicxml.Score_part):
84 staff = musicexp.Staff ()
86 partname = el.get_maybe_exist_named_child ('part-name')
87 # Finale gives unnamed parts the name "MusicXML Part" automatically!
88 if partname and partname.get_text() != "MusicXML Part":
89 staff.instrument_name = partname.get_text ()
90 if el.get_maybe_exist_named_child ('part-abbreviation'):
91 staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
92 # TODO: Read in the MIDI device / instrument
96 parts_groups = part_list.get_all_children ()
97 # the start/end group tags are not necessarily ordered correctly, so
98 # we can't go through the children sequentially!
100 if len (parts_groups) == 1 and isinstance (parts_group[1], musicxml.Score_part):
101 return read_score_part (parts_group[1])
103 for el in parts_groups:
104 if isinstance (el, musicxml.Score_part):
105 staff = read_score_part (el)
106 insert_into_layout (staff)
107 elif isinstance (el, musicxml.Part_group):
108 if el.type == "start":
109 group = musicexp.StaffGroup ()
110 staff_group = insert_into_layout (group)
111 # If we're inserting a nested staffgroup, we need to use InnerStaffGroup
112 if staff_group != layout:
113 group.stafftype = "InnerStaffGroup"
114 if hasattr (el, 'number'):
117 currentgroups_dict[id] = group
118 currentgroups.append (id)
119 if el.get_maybe_exist_named_child ('group-name'):
120 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
121 if el.get_maybe_exist_named_child ('group-abbreviation'):
122 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
123 if el.get_maybe_exist_named_child ('group-symbol'):
124 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
125 if el.get_maybe_exist_named_child ('group-barline'):
126 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
128 elif el.type == "stop":
129 # end the part-group, i.e. simply remove it from the lists
130 if hasattr (el, 'number'):
132 elif len (currentgroups) > 0:
135 del currentgroups_dict[pid]
136 currentgroups.remove (pid)
141 def musicxml_duration_to_lily (mxl_note):
142 d = musicexp.Duration ()
143 # if the note has no Type child, then that method spits out a warning and
144 # returns 0, i.e. a whole note
145 d.duration_log = mxl_note.get_duration_log ()
147 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
148 # Grace notes by specification have duration 0, so no time modification
149 # factor is possible. It even messes up the output with *0/1
150 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
151 d.factor = mxl_note._duration / d.get_length ()
155 def rational_to_lily_duration (rational_len):
156 d = musicexp.Duration ()
157 d.duration_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (rational_len.denominator (), -1)
158 d.factor = Rational (rational_len.numerator ())
159 if d.duration_log < 0:
160 error_message ("Encountered rational duration with denominator %s, "
161 "unable to convert to lilypond duration" %
162 rational_len.denominator ())
163 # TODO: Test the above error message
168 def musicxml_partial_to_lily (partial_len):
170 p = musicexp.Partial ()
171 p.partial = rational_to_lily_duration (partial_len)
176 # Detect repeats and alternative endings in the chord event list (music_list)
177 # and convert them to the corresponding musicexp objects, containing nested
179 def group_repeats (music_list):
180 repeat_replaced = True
183 # Walk through the list of expressions, looking for repeat structure
184 # (repeat start/end, corresponding endings). If we find one, try to find the
185 # last event of the repeat, replace the whole structure and start over again.
186 # For nested repeats, as soon as we encounter another starting repeat bar,
187 # treat that one first, and start over for the outer repeat.
188 while repeat_replaced and i<10:
190 repeat_start = -1 # position of repeat start / end
191 repeat_end = -1 # position of repeat start / end
193 ending_start = -1 # position of current ending start
194 endings = [] # list of already finished endings
196 repeat_replaced = False
198 while pos < len (music_list) and not repeat_replaced:
200 repeat_finished = False
201 if isinstance (e, RepeatMarker):
202 if not repeat_times and e.times:
203 repeat_times = e.times
204 if e.direction == -1:
206 repeat_finished = True
212 elif e.direction == 1:
218 elif isinstance (e, EndingMarker):
219 if e.direction == -1:
224 elif e.direction == 1:
227 endings.append ([ending_start, pos])
230 elif not isinstance (e, musicexp.BarLine):
231 # As soon as we encounter an element when repeat start and end
232 # is set and we are not inside an alternative ending,
233 # this whole repeat structure is finished => replace it
234 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
235 repeat_finished = True
238 # We found the whole structure replace it!
239 r = musicexp.RepeatedMusic ()
240 if repeat_times <= 0:
242 r.repeat_count = repeat_times
243 # don't erase the first element for "implicit" repeats (i.e. no
244 # starting repeat bars at the very beginning)
245 start = repeat_start+1
246 if repeat_start == music_start:
248 r.set_music (music_list[start:repeat_end])
249 for (start, end) in endings:
250 s = musicexp.SequentialMusic ()
251 s.elements = music_list[start+1:end]
253 del music_list[repeat_start:final_marker+1]
254 music_list.insert (repeat_start, r)
255 repeat_replaced = True
257 # TODO: Implement repeats until the end without explicit ending bar
262 def group_tuplets (music_list, events):
265 """Collect Musics from
266 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
273 for (ev_chord, tuplet_elt, fraction) in events:
274 while (j < len (music_list)):
275 if music_list[j] == ev_chord:
278 if tuplet_elt.type == 'start':
279 indices.append ((j, None, fraction))
280 elif tuplet_elt.type == 'stop':
281 indices[-1] = (indices[-1][0], j, indices[-1][2])
285 for (i1, i2, frac) in indices:
289 new_list.extend (music_list[last:i1])
290 seq = musicexp.SequentialMusic ()
292 seq.elements = music_list[i1:last]
294 tsm = musicexp.TimeScaledMusic ()
297 tsm.numerator = frac[0]
298 tsm.denominator = frac[1]
300 new_list.append (tsm)
302 new_list.extend (music_list[last:])
306 def musicxml_clef_to_lily (attributes):
307 change = musicexp.ClefChange ()
308 (change.type, change.position, change.octave) = attributes.get_clef_information ()
311 def musicxml_time_to_lily (attributes):
312 (beats, type) = attributes.get_time_signature ()
314 change = musicexp.TimeSignatureChange()
315 change.fraction = (beats, type)
319 def musicxml_key_to_lily (attributes):
320 start_pitch = musicexp.Pitch ()
321 (fifths, mode) = attributes.get_key_signature ()
328 start_pitch.alteration = a
330 error_message ('unknown mode %s' % mode)
332 fifth = musicexp.Pitch()
339 for x in range (fifths):
340 start_pitch = start_pitch.transposed (fifth)
342 start_pitch.octave = 0
344 change = musicexp.KeySignatureChange()
346 change.tonic = start_pitch
349 def musicxml_attributes_to_lily (attrs):
352 'clef': musicxml_clef_to_lily,
353 'time': musicxml_time_to_lily,
354 'key': musicxml_key_to_lily
356 for (k, func) in attr_dispatch.items ():
357 children = attrs.get_named_children (k)
359 elts.append (func (attrs))
363 class Marker (musicexp.Music):
367 def print_ly (self, printer):
368 sys.stderr.write ("Encountered unprocessed marker %s\n" % self)
370 def ly_expression (self):
372 class RepeatMarker (Marker):
374 Marker.__init__ (self)
376 class EndingMarker (Marker):
379 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
380 # and to RepeatMarker and EndingMarker objects for repeat and
381 # alternatives start/stops
382 def musicxml_barline_to_lily (barline):
383 # retval contains all possible markers in the order:
384 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
386 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
387 repeat_element = barline.get_maybe_exist_named_child ("repeat")
388 ending_element = barline.get_maybe_exist_named_child ("ending")
392 bartype = bartype_element.get_text ()
394 if repeat_element and hasattr (repeat_element, 'direction'):
395 repeat = RepeatMarker ()
396 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
398 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
399 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
401 if hasattr (repeat_element, 'times'):
403 repeat.times = int (repeat_element.times)
406 repeat.event = barline
407 if repeat.direction == -1:
412 if ending_element and hasattr (ending_element, 'type'):
413 ending = EndingMarker ()
414 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
415 ending.event = barline
416 if ending.direction == -1:
422 b = musicexp.BarLine ()
426 return retval.values ()
428 spanner_event_dict = {
429 'slur' : musicexp.SlurEvent,
430 'beam' : musicexp.BeamEvent,
431 'glissando' : musicexp.GlissandoEvent,
432 'pedal' : musicexp.PedalEvent,
433 'wavy-line' : musicexp.TrillSpanEvent,
434 'octave-shift' : musicexp.OctaveShiftEvent,
435 'wedge' : musicexp.HairpinEvent
437 spanner_type_dict = {
450 def musicxml_spanner_to_lily_event (mxl_event):
453 name = mxl_event.get_name()
454 func = spanner_event_dict.get (name)
458 error_message ('unknown span event %s' % mxl_event)
461 type = mxl_event.get_type ()
462 span_direction = spanner_type_dict.get (type)
463 # really check for None, because some types will be translated to 0, which
464 # would otherwise also lead to the unknown span warning
465 if span_direction != None:
466 ev.span_direction = span_direction
468 error_message ('unknown span type %s for %s' % (type, name))
470 ev.set_span_type (type)
471 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
473 # assign the size, which is used for octave-shift, etc.
474 ev.size = mxl_event.get_size ()
478 def musicxml_direction_to_indicator (direction):
479 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
481 def musicxml_fermata_to_lily_event (mxl_event):
482 ev = musicexp.ArticulationEvent ()
484 if hasattr (mxl_event, 'type'):
485 dir = musicxml_direction_to_indicator (mxl_event.type)
487 ev.force_direction = dir
490 def musicxml_tremolo_to_lily_event (mxl_event):
491 ev = musicexp.TremoloEvent ()
492 ev.bars = mxl_event.get_text ()
495 def musicxml_bend_to_lily_event (mxl_event):
496 ev = musicexp.BendEvent ()
497 ev.alter = mxl_event.bend_alter ()
501 def musicxml_fingering_event (mxl_event):
502 ev = musicexp.ShortArticulationEvent ()
503 ev.type = mxl_event.get_text ()
506 def musicxml_accidental_mark (mxl_event):
507 ev = musicexp.MarkupEvent ()
508 contents = { "sharp": "\\sharp",
509 "natural": "\\natural",
511 "double-sharp": "\\doublesharp",
512 "sharp-sharp": "\\sharp\\sharp",
513 "flat-flat": "\\flat\\flat",
514 "flat-flat": "\\doubleflat",
515 "natural-sharp": "\\natural\\sharp",
516 "natural-flat": "\\natural\\flat",
517 "quarter-flat": "\\semiflat",
518 "quarter-sharp": "\\semisharp",
519 "three-quarters-flat": "\\sesquiflat",
520 "three-quarters-sharp": "\\sesquisharp",
521 }.get (mxl_event.get_text ())
523 ev.contents = contents
528 # translate articulations, ornaments and other notations into ArticulationEvents
530 # -) string (ArticulationEvent with that name)
531 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
532 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
533 # TODO: Some translations are missing!
534 articulations_dict = {
535 "accent": (musicexp.ShortArticulationEvent, ">"),
536 "accidental-mark": musicxml_accidental_mark,
537 "bend": musicxml_bend_to_lily_event,
538 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
539 #"caesura": "caesura",
540 #"delayed-turn": "?",
541 #"detached-legato": "",
543 #"double-tongue": "",
544 "down-bow": "downbow",
546 "fingering": musicxml_fingering_event,
550 "harmonic": "flageolet",
552 "inverted-mordent": "prall",
553 "inverted-turn": "reverseturn",
554 "mordent": "mordent",
558 #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
563 #"snap-pizzicato": "",
565 "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
566 "staccato": (musicexp.ShortArticulationEvent, "."),
567 "stopped": (musicexp.ShortArticulationEvent, "+"),
570 "strong-accent": (musicexp.ShortArticulationEvent, "^"),
572 "tenuto": (musicexp.ShortArticulationEvent, "-"),
573 #"thumb-position": "",
576 "tremolo": musicxml_tremolo_to_lily_event,
577 "trill-mark": "trill",
578 #"triple-tongue": "",
583 articulation_spanners = [ "wavy-line" ]
585 def musicxml_articulation_to_lily_event (mxl_event):
586 # wavy-line elements are treated as trill spanners, not as articulation ornaments
587 if mxl_event.get_name () in articulation_spanners:
588 return musicxml_spanner_to_lily_event (mxl_event)
590 tmp_tp = articulations_dict.get (mxl_event.get_name ())
594 if isinstance (tmp_tp, str):
595 ev = musicexp.ArticulationEvent ()
597 elif isinstance (tmp_tp, tuple):
601 ev = tmp_tp (mxl_event)
603 # Some articulations use the type attribute, other the placement...
605 if hasattr (mxl_event, 'type'):
606 dir = musicxml_direction_to_indicator (mxl_event.type)
607 if hasattr (mxl_event, 'placement'):
608 dir = musicxml_direction_to_indicator (mxl_event.placement)
612 def musicxml_dynamics_to_lily_event (dynentry):
613 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
614 "f", "ff", "fff", "ffff", "fffff", "ffffff",
615 "mp", "mf", "sf", "sfp", "sfpp", "fp",
616 "rf", "rfz", "sfz", "sffz", "fz" )
617 if not dynentry.get_name() in dynamics_available:
619 event = musicexp.DynamicsEvent ()
620 event.type = dynentry.get_name ()
623 # Convert single-color two-byte strings to numbers 0.0 - 1.0
624 def hexcolorval_to_nr (hex_val):
626 v = int (hex_val, 16)
633 def hex_to_color (hex_val):
634 res = re.match (r'#([0-9a-f][0-9a-f]|)([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$', hex_val, re.IGNORECASE)
636 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
640 def musicxml_words_to_lily_event (words):
641 event = musicexp.TextEvent ()
642 text = words.get_text ()
643 text = re.sub ('^ *\n? *', '', text)
644 text = re.sub (' *\n? *$', '', text)
647 if hasattr (words, 'default-y'):
648 offset = getattr (words, 'default-y')
650 off = string.atoi (offset)
652 event.force_direction = 1
654 event.force_direction = -1
656 event.force_direction = 0
658 if hasattr (words, 'font-weight'):
659 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
661 event.markup += font_weight
663 if hasattr (words, 'font-size'):
664 size = getattr (words, 'font-size')
666 "xx-small": '\\teeny',
672 "xx-large": '\\bigger\\huge'
675 event.markup += font_size
677 if hasattr (words, 'color'):
678 color = getattr (words, 'color')
679 rgb = hex_to_color (color)
681 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
683 if hasattr (words, 'font-style'):
684 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
686 event.markup += font_style
688 # TODO: How should I best convert the font-family attribute?
690 # TODO: How can I represent the underline, overline and line-through
691 # attributes in Lilypond? Values of these attributes indicate
692 # the number of lines
697 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
699 def musicxml_direction_to_lily (n):
700 # TODO: Handle the <staff> element!
702 dirtype_children = []
703 for dt in n.get_typed_children (musicxml.DirType):
704 dirtype_children += dt.get_all_children ()
706 for entry in dirtype_children:
708 if entry.get_name () == "dynamics":
709 for dynentry in entry.get_all_children ():
710 ev = musicxml_dynamics_to_lily_event (dynentry)
714 if entry.get_name () == "words":
715 ev = musicxml_words_to_lily_event (entry)
719 # octave shifts. pedal marks, hairpins etc. are spanners:
720 if entry.get_name() in direction_spanners:
721 event = musicxml_spanner_to_lily_event (entry)
728 instrument_drumtype_dict = {
729 'Acoustic Snare Drum': 'acousticsnare',
730 'Side Stick': 'sidestick',
731 'Open Triangle': 'opentriangle',
732 'Mute Triangle': 'mutetriangle',
733 'Tambourine': 'tambourine',
734 'Bass Drum': 'bassdrum',
737 def musicxml_note_to_lily_main_event (n):
741 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
744 pitch = musicxml_pitch_to_lily (mxl_pitch)
745 event = musicexp.NoteEvent()
748 acc = n.get_maybe_exist_named_child ('accidental')
750 # let's not force accs everywhere.
751 event.cautionary = acc.editorial
753 elif n.get_maybe_exist_typed_child (musicxml.Rest):
754 # rests can have display-octave and display-step, which are
755 # treated like an ordinary note pitch
756 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
757 event = musicexp.RestEvent()
758 pitch = musicxml_restdisplay_to_lily (rest)
760 elif n.instrument_name:
761 event = musicexp.NoteEvent ()
762 drum_type = instrument_drumtype_dict.get (n.instrument_name)
764 event.drum_type = drum_type
766 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
767 event.drum_type = 'acousticsnare'
770 n.message ("cannot find suitable event")
772 event.duration = musicxml_duration_to_lily (n)
778 def __init__ (self, here, dest):
782 class LilyPondVoiceBuilder:
785 self.pending_dynamics = []
786 self.end_moment = Rational (0)
787 self.begin_moment = Rational (0)
788 self.pending_multibar = Rational (0)
789 self.ignore_skips = False
791 def _insert_multibar (self):
792 r = musicexp.MultiMeasureRest ()
793 r.duration = musicexp.Duration()
794 r.duration.duration_log = 0
795 r.duration.factor = self.pending_multibar
796 self.elements.append (r)
797 self.begin_moment = self.end_moment
798 self.end_moment = self.begin_moment + self.pending_multibar
799 self.pending_multibar = Rational (0)
801 def add_multibar_rest (self, duration):
802 self.pending_multibar += duration
804 def set_duration (self, duration):
805 self.end_moment = self.begin_moment + duration
806 def current_duration (self):
807 return self.end_moment - self.begin_moment
809 def add_music (self, music, duration):
810 assert isinstance (music, musicexp.Music)
811 if self.pending_multibar > Rational (0):
812 self._insert_multibar ()
814 self.elements.append (music)
815 self.begin_moment = self.end_moment
816 self.set_duration (duration)
818 # Insert all pending dynamics right after the note/rest:
819 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
820 for d in self.pending_dynamics:
822 self.pending_dynamics = []
824 # Insert some music command that does not affect the position in the measure
825 def add_command (self, command):
826 assert isinstance (command, musicexp.Music)
827 if self.pending_multibar > Rational (0):
828 self._insert_multibar ()
829 self.elements.append (command)
830 def add_barline (self, barline):
831 # TODO: Implement merging of default barline and custom bar line
832 self.add_music (barline, Rational (0))
833 def add_partial (self, command):
834 self.ignore_skips = True
835 self.add_command (command)
837 def add_dynamics (self, dynamic):
838 # store the dynamic item(s) until we encounter the next note/rest:
839 self.pending_dynamics.append (dynamic)
841 def add_bar_check (self, number):
842 b = musicexp.BarLine ()
843 b.bar_number = number
846 def jumpto (self, moment):
847 current_end = self.end_moment + self.pending_multibar
848 diff = moment - current_end
850 if diff < Rational (0):
851 error_message ('Negative skip %s' % diff)
854 if diff > Rational (0) and not self.ignore_skips:
855 skip = musicexp.SkipEvent()
856 skip.duration.duration_log = 0
857 skip.duration.factor = diff
859 evc = musicexp.EventChord ()
860 evc.elements.append (skip)
861 self.add_music (evc, diff)
863 if diff > Rational (0) and moment == 0:
864 self.ignore_skips = False
866 def last_event_chord (self, starting_at):
870 # if the position matches, find the last EventChord, do not cross a bar line!
871 at = len( self.elements ) - 1
873 not isinstance (self.elements[at], musicexp.EventChord) and
874 not isinstance (self.elements[at], musicexp.BarLine)):
879 and isinstance (self.elements[at], musicexp.EventChord)
880 and self.begin_moment == starting_at):
881 value = self.elements[at]
883 self.jumpto (starting_at)
887 def correct_negative_skip (self, goto):
888 self.end_moment = goto
889 self.begin_moment = goto
890 evc = musicexp.EventChord ()
891 self.elements.append (evc)
893 def musicxml_voice_to_lily_voice (voice):
898 # Needed for melismata detection (ignore lyrics on those notes!):
902 ignore_lyrics = False
904 # TODO: Make sure that the keys in the dict don't get reordered, since
905 # we need the correct ordering of the lyrics stanzas! By default,
906 # a dict will reorder its keys
907 for k in voice.get_lyrics_numbers ():
910 voice_builder = LilyPondVoiceBuilder()
912 for n in voice._elements:
913 if n.get_name () == 'forward':
916 if isinstance (n, musicxml.Partial) and n.partial > 0:
917 a = musicxml_partial_to_lily (n.partial)
919 voice_builder.add_partial (a)
922 if isinstance (n, musicxml.Direction):
923 for a in musicxml_direction_to_lily (n):
924 if a.wait_for_note ():
925 voice_builder.add_dynamics (a)
927 voice_builder.add_command (a)
930 is_chord = n.get_maybe_exist_named_child ('chord')
933 voice_builder.jumpto (n._when)
934 except NegativeSkip, neg:
935 voice_builder.correct_negative_skip (n._when)
936 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
938 if isinstance (n, musicxml.Attributes):
939 if n.is_first () and n._measure_position == Rational (0):
941 number = int (n.get_parent ().number)
945 voice_builder.add_bar_check (number)
947 for a in musicxml_attributes_to_lily (n):
948 voice_builder.add_command (a)
951 if isinstance (n, musicxml.Barline):
952 barlines = musicxml_barline_to_lily (n)
954 if isinstance (a, musicexp.BarLine):
955 voice_builder.add_barline (a)
956 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
957 voice_builder.add_command (a)
960 if not n.__class__.__name__ == 'Note':
961 error_message ('not a Note or Attributes? %s' % n)
964 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
966 and rest.is_whole_measure ()):
968 voice_builder.add_multibar_rest (n._duration)
971 if n.is_first () and n._measure_position == Rational (0):
973 num = int (n.get_parent ().number)
977 voice_builder.add_bar_check (num)
979 main_event = musicxml_note_to_lily_main_event (n)
980 ignore_lyrics = inside_slur or is_tied or is_chord
982 if hasattr (main_event, 'drum_type') and main_event.drum_type:
983 modes_found['drummode'] = True
986 ev_chord = voice_builder.last_event_chord (n._when)
988 ev_chord = musicexp.EventChord()
989 voice_builder.add_music (ev_chord, n._duration)
991 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
994 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
995 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
997 grace_chord = musicexp.EventChord ()
998 ev_chord.append_grace (grace_chord)
999 if hasattr (grace, 'slash'):
1000 # TODO: use grace_type = "appoggiatura" for slurred grace notes
1001 if grace.slash == "yes":
1002 ev_chord.grace_type = "acciaccatura"
1003 elif grace.slash == "no":
1004 ev_chord.grace_type = "grace"
1005 # now that we have inserted the chord into the grace music, insert
1006 # everything into that chord instead of the ev_chord
1007 ev_chord = grace_chord
1008 ev_chord.append (main_event)
1009 ignore_lyrics = True
1011 ev_chord.append (main_event)
1012 # When a note/chord has grace notes (duration==0), the duration of the
1013 # event chord is not yet known, but the event chord was already added
1014 # with duration 0. The following correct this when we hit the real note!
1015 if voice_builder.current_duration () == 0 and n._duration > 0:
1016 voice_builder.set_duration (n._duration)
1018 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
1022 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
1023 # +tied | +slur | +tuplet | glissando | slide |
1024 # ornaments | technical | articulations | dynamics |
1025 # +fermata | arpeggiate | non-arpeggiate |
1026 # accidental-mark | other-notation
1028 if notations.get_tuplet():
1029 tuplet_event = notations.get_tuplet()
1030 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1033 frac = mod.get_fraction ()
1035 tuplet_events.append ((ev_chord, tuplet_event, frac))
1037 slurs = [s for s in notations.get_named_children ('slur')
1038 if s.get_type () in ('start','stop')]
1041 error_message ('more than 1 slur?')
1042 # record the slur status for the next note in the loop
1043 if slurs[0].get_type () == 'start':
1045 elif slurs[0].get_type () == 'stop':
1047 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
1048 ev_chord.append (lily_ev)
1050 mxl_tie = notations.get_tie ()
1051 if mxl_tie and mxl_tie.type == 'start':
1052 ev_chord.append (musicexp.TieEvent ())
1055 fermatas = notations.get_named_children ('fermata')
1057 ev = musicxml_fermata_to_lily_event (a)
1059 ev_chord.append (ev)
1061 arpeggiate = notations.get_named_children ('arpeggiate')
1062 for a in arpeggiate:
1063 ev_chord.append (musicexp.ArpeggioEvent ())
1065 glissandos = notations.get_named_children ('glissando')
1066 for a in glissandos:
1067 ev = musicxml_spanner_to_lily_event (a)
1069 ev_chord.append (ev)
1071 # Articulations can contain the following child elements:
1072 # accent | strong-accent | staccato | tenuto |
1073 # detached-legato | staccatissimo | spiccato |
1074 # scoop | plop | doit | falloff | breath-mark |
1075 # caesura | stress | unstress
1076 # Technical can contain the following child elements:
1077 # up-bow | down-bow | harmonic | open-string |
1078 # thumb-position | fingering | pluck | double-tongue |
1079 # triple-tongue | stopped | snap-pizzicato | fret |
1080 # string | hammer-on | pull-off | bend | tap | heel |
1081 # toe | fingernails | other-technical
1082 # Ornaments can contain the following child elements:
1083 # trill-mark | turn | delayed-turn | inverted-turn |
1084 # shake | wavy-line | mordent | inverted-mordent |
1085 # schleifer | tremolo | other-ornament, accidental-mark
1086 ornaments = notations.get_named_children ('ornaments')
1088 for ch in a.get_named_children ('tremolo'):
1089 ev = musicxml_tremolo_to_lily_event (ch)
1091 ev_chord.append (ev)
1093 ornaments += notations.get_named_children ('articulations')
1094 ornaments += notations.get_named_children ('technical')
1097 for ch in a.get_all_children ():
1098 ev = musicxml_articulation_to_lily_event (ch)
1100 ev_chord.append (ev)
1102 dynamics = notations.get_named_children ('dynamics')
1104 for ch in a.get_all_children ():
1105 ev = musicxml_dynamics_to_lily_event (ch)
1107 ev_chord.append (ev)
1109 # Extract the lyrics
1110 if not rest and not ignore_lyrics:
1111 note_lyrics_processed = []
1112 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1113 for l in note_lyrics_elements:
1114 if l.get_number () < 0:
1115 for k in lyrics.keys ():
1116 lyrics[k].append (l.lyric_to_text ())
1117 note_lyrics_processed.append (k)
1119 lyrics[l.number].append(l.lyric_to_text ())
1120 note_lyrics_processed.append (l.number)
1121 for lnr in lyrics.keys ():
1122 if not lnr in note_lyrics_processed:
1123 lyrics[lnr].append ("\skip4")
1126 mxl_beams = [b for b in n.get_named_children ('beam')
1127 if (b.get_type () in ('begin', 'end')
1128 and b.is_primary ())]
1130 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1132 ev_chord.append (beam_ev)
1135 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1138 frac = mod.get_fraction ()
1140 tuplet_events.append ((ev_chord, tuplet_event, frac))
1142 ## force trailing mm rests to be written out.
1143 voice_builder.add_music (musicexp.EventChord (), Rational (0))
1145 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1146 ly_voice = group_repeats (ly_voice)
1148 seq_music = musicexp.SequentialMusic ()
1150 if 'drummode' in modes_found.keys ():
1151 ## \key <pitch> barfs in drummode.
1152 ly_voice = [e for e in ly_voice
1153 if not isinstance(e, musicexp.KeySignatureChange)]
1155 seq_music.elements = ly_voice
1157 for k in lyrics.keys ():
1158 lyrics_dict[k] = musicexp.Lyrics ()
1159 lyrics_dict[k].lyrics_syllables = lyrics[k]
1162 if len (modes_found) > 1:
1163 error_message ('Too many modes found %s' % modes_found.keys ())
1165 return_value = seq_music
1166 for mode in modes_found.keys ():
1167 v = musicexp.ModeChangingMusicWrapper()
1168 v.element = return_value
1172 return (return_value, lyrics_dict)
1175 def musicxml_id_to_lily (id):
1176 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1177 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1179 for digit in digits:
1180 d = digits.index (digit)
1181 id = re.sub ('%d' % d, digit, id)
1183 id = re.sub ('[^a-zA-Z]', 'X', id)
1187 def musicxml_pitch_to_lily (mxl_pitch):
1188 p = musicexp.Pitch()
1189 p.alteration = mxl_pitch.get_alteration ()
1190 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1191 p.octave = mxl_pitch.get_octave () - 4
1194 def musicxml_restdisplay_to_lily (mxl_rest):
1196 step = mxl_rest.get_step ()
1198 p = musicexp.Pitch()
1199 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1200 octave = mxl_rest.get_octave ()
1202 p.octave = octave - 4
1205 def voices_in_part (part):
1206 """Return a Name -> Voice dictionary for PART"""
1208 part.extract_voices ()
1209 voice_dict = part.get_voices ()
1213 def voices_in_part_in_parts (parts):
1214 """return a Part -> Name -> Voice dictionary"""
1215 return dict([(p, voices_in_part (p)) for p in parts])
1218 def get_all_voices (parts):
1219 all_voices = voices_in_part_in_parts (parts)
1222 for p, name_voice in all_voices.items ():
1225 for n, v in name_voice.items ():
1226 progress ("Converting to LilyPond expressions...")
1227 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1228 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
1230 all_ly_voices[p] = part_ly_voices
1232 return all_ly_voices
1235 def option_parser ():
1236 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1237 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1239 _ ("""This program is free software. It is covered by the GNU General Public
1240 License and you are welcome to change it and/or distribute copies of it
1241 under certain conditions. Invoke as `%s --warranty' for more
1242 information.""") % 'lilypond'
1244 Copyright (c) 2005--2007 by
1245 Han-Wen Nienhuys <hanwen@xs4all.nl> and
1246 Jan Nieuwenhuizen <janneke@gnu.org>
1248 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1249 p.add_option ('-v', '--verbose',
1250 action="store_true",
1252 help=_ ("be verbose"))
1254 p.add_option ('', '--lxml',
1255 action="store_true",
1258 help=_ ("Use lxml.etree; uses less memory and cpu time."))
1260 p.add_option ('-o', '--output',
1266 help=_ ("set output filename to FILE"))
1267 p.add_option_group ('bugs',
1268 description=(_ ("Report bugs via")
1269 + ''' http://post.gmane.org/post.php'''
1270 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1273 def music_xml_voice_name_to_lily_name (part, name):
1274 str = "Part%sVoice%s" % (part.id, name)
1275 return musicxml_id_to_lily (str)
1277 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1278 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1279 return musicxml_id_to_lily (str)
1281 def print_voice_definitions (printer, part_list, voices):
1283 for (part, nv_dict) in voices.items():
1284 part_dict[part.id] = (part, nv_dict)
1286 for part in part_list:
1287 (p, nv_dict) = part_dict.get (part.id, (None, {}))
1288 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1289 k = music_xml_voice_name_to_lily_name (p, name)
1290 printer.dump ('%s = ' % k)
1291 voice.print_ly (printer)
1294 for l in lyrics.keys ():
1295 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1296 printer.dump ('%s = ' %lname )
1297 lyrics[l].print_ly (printer)
1302 return dict ([(elt,1) for elt in l]).keys ()
1304 # format the information about the staff in the form
1307 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1308 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1312 # raw_voices is of the form [(voicename, lyrics)*]
1313 def format_staff_info (part, staff_id, raw_voices):
1315 for (v, lyrics) in raw_voices:
1316 voice_name = music_xml_voice_name_to_lily_name (part, v)
1317 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1318 for l in lyrics.keys ()]
1319 voices.append ([voice_name, voice_lyrics])
1320 return [staff_id, voices]
1322 def update_score_setup (score_structure, part_list, voices):
1323 part_dict = dict ([(p.id, p) for p in voices.keys ()])
1324 final_part_dict = {}
1326 for part_definition in part_list:
1327 part_name = part_definition.id
1328 part = part_dict.get (part_name)
1330 error_message ('unknown part in part-list: %s' % part_name)
1333 nv_dict = voices.get (part)
1334 staves = reduce (lambda x,y: x+ y,
1335 [mxlvoice._staves.keys ()
1336 for (v, mxlvoice) in nv_dict.values ()],
1339 if len (staves) > 1:
1341 staves = uniq_list (staves)
1344 thisstaff_raw_voices = [(voice_name, lyrics)
1345 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1346 if mxlvoice._start_staff == s]
1347 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1349 thisstaff_raw_voices = [(voice_name, lyrics)
1350 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1351 staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1352 score_structure.setPartInformation (part_name, staves_info)
1354 def print_ly_preamble (printer, filename):
1355 printer.dump_version ()
1356 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1358 def read_musicxml (filename, use_lxml):
1362 tree = lxml.etree.parse (filename)
1363 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1366 from xml.dom import minidom, Node
1368 doc = minidom.parse(filename)
1369 node = doc.documentElement
1370 return musicxml.minidom_demarshal_node (node)
1375 def convert (filename, options):
1376 progress ("Reading MusicXML from %s ..." % filename)
1378 tree = read_musicxml (filename, options.use_lxml)
1380 score_structure = None
1381 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1383 score_structure = extract_score_layout (mxl_pl)
1384 part_list = mxl_pl.get_named_children ("score-part")
1386 # score information is contained in the <work>, <identification> or <movement-title> tags
1387 score_information = extract_score_information (tree)
1388 parts = tree.get_typed_children (musicxml.Part)
1389 voices = get_all_voices (parts)
1390 update_score_setup (score_structure, part_list, voices)
1392 if not options.output_name:
1393 options.output_name = os.path.basename (filename)
1394 options.output_name = os.path.splitext (options.output_name)[0]
1395 elif re.match (".*\.ly", options.output_name):
1396 options.output_name = os.path.splitext (options.output_name)[0]
1399 defs_ly_name = options.output_name + '-defs.ly'
1400 driver_ly_name = options.output_name + '.ly'
1402 printer = musicexp.Output_printer()
1403 progress ("Output to `%s'" % defs_ly_name)
1404 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1406 print_ly_preamble (printer, filename)
1407 score_information.print_ly (printer)
1408 print_voice_definitions (printer, part_list, voices)
1413 progress ("Output to `%s'" % driver_ly_name)
1414 printer = musicexp.Output_printer()
1415 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1416 print_ly_preamble (printer, filename)
1417 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1418 score_structure.print_ly (printer)
1423 def get_existing_filename_with_extension (filename, ext):
1424 if os.path.exists (filename):
1426 newfilename = filename + ".xml"
1427 if os.path.exists (newfilename):
1429 newfilename = filename + "xml"
1430 if os.path.exists (newfilename):
1435 opt_parser = option_parser()
1437 (options, args) = opt_parser.parse_args ()
1439 opt_parser.print_usage()
1442 # Allow the user to leave out the .xml or xml on the filename
1443 filename = get_existing_filename_with_extension (args[0], "xml")
1444 if filename and os.path.exists (filename):
1445 voices = convert (filename, options)
1447 progress ("Unable to find input file %s" % args[0])
1449 if __name__ == '__main__':