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 last = len (music_list) - 1
197 repeat_replaced = False
199 while pos < len (music_list) and not repeat_replaced:
201 repeat_finished = False
202 if isinstance (e, RepeatMarker):
203 if not repeat_times and e.times:
204 repeat_times = e.times
205 if e.direction == -1:
207 repeat_finished = True
213 elif e.direction == 1:
219 elif isinstance (e, EndingMarker):
220 if e.direction == -1:
225 elif e.direction == 1:
228 endings.append ([ending_start, pos])
231 elif not isinstance (e, musicexp.BarLine):
232 # As soon as we encounter an element when repeat start and end
233 # is set and we are not inside an alternative ending,
234 # this whole repeat structure is finished => replace it
235 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
236 repeat_finished = True
238 # Finish off all repeats without explicit ending bar (e.g. when
239 # we convert only one page of a multi-page score with repeats)
240 if pos == last and repeat_start >= 0:
241 repeat_finished = True
245 if ending_start >= 0:
246 endings.append ([ending_start, pos])
250 # We found the whole structure replace it!
251 r = musicexp.RepeatedMusic ()
252 if repeat_times <= 0:
254 r.repeat_count = repeat_times
255 # don't erase the first element for "implicit" repeats (i.e. no
256 # starting repeat bars at the very beginning)
257 start = repeat_start+1
258 if repeat_start == music_start:
260 r.set_music (music_list[start:repeat_end])
261 for (start, end) in endings:
262 s = musicexp.SequentialMusic ()
263 s.elements = music_list[start+1:end]
265 del music_list[repeat_start:final_marker+1]
266 music_list.insert (repeat_start, r)
267 repeat_replaced = True
269 # TODO: Implement repeats until the end without explicit ending bar
274 def group_tuplets (music_list, events):
277 """Collect Musics from
278 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
285 for (ev_chord, tuplet_elt, fraction) in events:
286 while (j < len (music_list)):
287 if music_list[j] == ev_chord:
290 if tuplet_elt.type == 'start':
291 indices.append ((j, None, fraction))
292 elif tuplet_elt.type == 'stop':
293 indices[-1] = (indices[-1][0], j, indices[-1][2])
297 for (i1, i2, frac) in indices:
301 new_list.extend (music_list[last:i1])
302 seq = musicexp.SequentialMusic ()
304 seq.elements = music_list[i1:last]
306 tsm = musicexp.TimeScaledMusic ()
309 tsm.numerator = frac[0]
310 tsm.denominator = frac[1]
312 new_list.append (tsm)
314 new_list.extend (music_list[last:])
318 def musicxml_clef_to_lily (attributes):
319 change = musicexp.ClefChange ()
320 (change.type, change.position, change.octave) = attributes.get_clef_information ()
323 def musicxml_time_to_lily (attributes):
324 (beats, type) = attributes.get_time_signature ()
326 change = musicexp.TimeSignatureChange()
327 change.fraction = (beats, type)
331 def musicxml_key_to_lily (attributes):
332 start_pitch = musicexp.Pitch ()
333 (fifths, mode) = attributes.get_key_signature ()
340 start_pitch.alteration = a
342 error_message ('unknown mode %s' % mode)
344 fifth = musicexp.Pitch()
351 for x in range (fifths):
352 start_pitch = start_pitch.transposed (fifth)
354 start_pitch.octave = 0
356 change = musicexp.KeySignatureChange()
358 change.tonic = start_pitch
361 def musicxml_attributes_to_lily (attrs):
364 'clef': musicxml_clef_to_lily,
365 'time': musicxml_time_to_lily,
366 'key': musicxml_key_to_lily
368 for (k, func) in attr_dispatch.items ():
369 children = attrs.get_named_children (k)
371 elts.append (func (attrs))
375 class Marker (musicexp.Music):
379 def print_ly (self, printer):
380 sys.stderr.write ("Encountered unprocessed marker %s\n" % self)
382 def ly_expression (self):
384 class RepeatMarker (Marker):
386 Marker.__init__ (self)
388 class EndingMarker (Marker):
391 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
392 # and to RepeatMarker and EndingMarker objects for repeat and
393 # alternatives start/stops
394 def musicxml_barline_to_lily (barline):
395 # retval contains all possible markers in the order:
396 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
398 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
399 repeat_element = barline.get_maybe_exist_named_child ("repeat")
400 ending_element = barline.get_maybe_exist_named_child ("ending")
404 bartype = bartype_element.get_text ()
406 if repeat_element and hasattr (repeat_element, 'direction'):
407 repeat = RepeatMarker ()
408 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
410 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
411 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
413 if hasattr (repeat_element, 'times'):
415 repeat.times = int (repeat_element.times)
418 repeat.event = barline
419 if repeat.direction == -1:
424 if ending_element and hasattr (ending_element, 'type'):
425 ending = EndingMarker ()
426 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
427 ending.event = barline
428 if ending.direction == -1:
434 b = musicexp.BarLine ()
438 return retval.values ()
440 spanner_event_dict = {
441 'slur' : musicexp.SlurEvent,
442 'beam' : musicexp.BeamEvent,
443 'glissando' : musicexp.GlissandoEvent,
444 'pedal' : musicexp.PedalEvent,
445 'wavy-line' : musicexp.TrillSpanEvent,
446 'octave-shift' : musicexp.OctaveShiftEvent,
447 'wedge' : musicexp.HairpinEvent
449 spanner_type_dict = {
462 def musicxml_spanner_to_lily_event (mxl_event):
465 name = mxl_event.get_name()
466 func = spanner_event_dict.get (name)
470 error_message ('unknown span event %s' % mxl_event)
473 type = mxl_event.get_type ()
474 span_direction = spanner_type_dict.get (type)
475 # really check for None, because some types will be translated to 0, which
476 # would otherwise also lead to the unknown span warning
477 if span_direction != None:
478 ev.span_direction = span_direction
480 error_message ('unknown span type %s for %s' % (type, name))
482 ev.set_span_type (type)
483 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
485 # assign the size, which is used for octave-shift, etc.
486 ev.size = mxl_event.get_size ()
490 def musicxml_direction_to_indicator (direction):
491 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
493 def musicxml_fermata_to_lily_event (mxl_event):
494 ev = musicexp.ArticulationEvent ()
496 if hasattr (mxl_event, 'type'):
497 dir = musicxml_direction_to_indicator (mxl_event.type)
499 ev.force_direction = dir
502 def musicxml_tremolo_to_lily_event (mxl_event):
503 ev = musicexp.TremoloEvent ()
504 ev.bars = mxl_event.get_text ()
507 def musicxml_bend_to_lily_event (mxl_event):
508 ev = musicexp.BendEvent ()
509 ev.alter = mxl_event.bend_alter ()
513 def musicxml_fingering_event (mxl_event):
514 ev = musicexp.ShortArticulationEvent ()
515 ev.type = mxl_event.get_text ()
518 def musicxml_accidental_mark (mxl_event):
519 ev = musicexp.MarkupEvent ()
520 contents = { "sharp": "\\sharp",
521 "natural": "\\natural",
523 "double-sharp": "\\doublesharp",
524 "sharp-sharp": "\\sharp\\sharp",
525 "flat-flat": "\\flat\\flat",
526 "flat-flat": "\\doubleflat",
527 "natural-sharp": "\\natural\\sharp",
528 "natural-flat": "\\natural\\flat",
529 "quarter-flat": "\\semiflat",
530 "quarter-sharp": "\\semisharp",
531 "three-quarters-flat": "\\sesquiflat",
532 "three-quarters-sharp": "\\sesquisharp",
533 }.get (mxl_event.get_text ())
535 ev.contents = contents
540 # translate articulations, ornaments and other notations into ArticulationEvents
542 # -) string (ArticulationEvent with that name)
543 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
544 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
545 # TODO: Some translations are missing!
546 articulations_dict = {
547 "accent": (musicexp.ShortArticulationEvent, ">"),
548 "accidental-mark": musicxml_accidental_mark,
549 "bend": musicxml_bend_to_lily_event,
550 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
551 #"caesura": "caesura",
552 #"delayed-turn": "?",
553 #"detached-legato": "",
555 #"double-tongue": "",
556 "down-bow": "downbow",
558 "fingering": musicxml_fingering_event,
562 "harmonic": "flageolet",
564 "inverted-mordent": "prall",
565 "inverted-turn": "reverseturn",
566 "mordent": "mordent",
570 #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
575 #"snap-pizzicato": "",
577 "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
578 "staccato": (musicexp.ShortArticulationEvent, "."),
579 "stopped": (musicexp.ShortArticulationEvent, "+"),
582 "strong-accent": (musicexp.ShortArticulationEvent, "^"),
584 "tenuto": (musicexp.ShortArticulationEvent, "-"),
585 #"thumb-position": "",
588 "tremolo": musicxml_tremolo_to_lily_event,
589 "trill-mark": "trill",
590 #"triple-tongue": "",
595 articulation_spanners = [ "wavy-line" ]
597 def musicxml_articulation_to_lily_event (mxl_event):
598 # wavy-line elements are treated as trill spanners, not as articulation ornaments
599 if mxl_event.get_name () in articulation_spanners:
600 return musicxml_spanner_to_lily_event (mxl_event)
602 tmp_tp = articulations_dict.get (mxl_event.get_name ())
606 if isinstance (tmp_tp, str):
607 ev = musicexp.ArticulationEvent ()
609 elif isinstance (tmp_tp, tuple):
613 ev = tmp_tp (mxl_event)
615 # Some articulations use the type attribute, other the placement...
617 if hasattr (mxl_event, 'type'):
618 dir = musicxml_direction_to_indicator (mxl_event.type)
619 if hasattr (mxl_event, 'placement'):
620 dir = musicxml_direction_to_indicator (mxl_event.placement)
624 def musicxml_dynamics_to_lily_event (dynentry):
625 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
626 "f", "ff", "fff", "ffff", "fffff", "ffffff",
627 "mp", "mf", "sf", "sfp", "sfpp", "fp",
628 "rf", "rfz", "sfz", "sffz", "fz" )
629 if not dynentry.get_name() in dynamics_available:
631 event = musicexp.DynamicsEvent ()
632 event.type = dynentry.get_name ()
635 # Convert single-color two-byte strings to numbers 0.0 - 1.0
636 def hexcolorval_to_nr (hex_val):
638 v = int (hex_val, 16)
645 def hex_to_color (hex_val):
646 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)
648 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
652 def musicxml_words_to_lily_event (words):
653 event = musicexp.TextEvent ()
654 text = words.get_text ()
655 text = re.sub ('^ *\n? *', '', text)
656 text = re.sub (' *\n? *$', '', text)
659 if hasattr (words, 'default-y'):
660 offset = getattr (words, 'default-y')
662 off = string.atoi (offset)
664 event.force_direction = 1
666 event.force_direction = -1
668 event.force_direction = 0
670 if hasattr (words, 'font-weight'):
671 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
673 event.markup += font_weight
675 if hasattr (words, 'font-size'):
676 size = getattr (words, 'font-size')
678 "xx-small": '\\teeny',
684 "xx-large": '\\bigger\\huge'
687 event.markup += font_size
689 if hasattr (words, 'color'):
690 color = getattr (words, 'color')
691 rgb = hex_to_color (color)
693 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
695 if hasattr (words, 'font-style'):
696 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
698 event.markup += font_style
700 # TODO: How should I best convert the font-family attribute?
702 # TODO: How can I represent the underline, overline and line-through
703 # attributes in Lilypond? Values of these attributes indicate
704 # the number of lines
709 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
711 def musicxml_direction_to_lily (n):
712 # TODO: Handle the <staff> element!
714 dirtype_children = []
715 for dt in n.get_typed_children (musicxml.DirType):
716 dirtype_children += dt.get_all_children ()
718 for entry in dirtype_children:
720 if entry.get_name () == "dynamics":
721 for dynentry in entry.get_all_children ():
722 ev = musicxml_dynamics_to_lily_event (dynentry)
726 if entry.get_name () == "words":
727 ev = musicxml_words_to_lily_event (entry)
731 # octave shifts. pedal marks, hairpins etc. are spanners:
732 if entry.get_name() in direction_spanners:
733 event = musicxml_spanner_to_lily_event (entry)
740 def musicxml_frame_to_lily_event (frame):
741 ev = musicexp.FretEvent ()
742 ev.strings = frame.get_strings ()
743 ev.frets = frame.get_frets ()
744 #offset = frame.get_first_fret () - 1
746 for fn in frame.get_named_children ('frame-note'):
747 fret = fn.get_fret ()
750 el = [ fn.get_string (), fret ]
751 fingering = fn.get_fingering ()
753 el.append (fingering)
754 ev.elements.append (el)
757 barre[0] = el[0] # start string
758 barre[2] = el[1] # fret
760 barre[1] = el[0] # end string
765 def musicxml_harmony_to_lily (n):
767 for f in n.get_named_children ('frame'):
768 ev = musicxml_frame_to_lily_event (f)
774 instrument_drumtype_dict = {
775 'Acoustic Snare Drum': 'acousticsnare',
776 'Side Stick': 'sidestick',
777 'Open Triangle': 'opentriangle',
778 'Mute Triangle': 'mutetriangle',
779 'Tambourine': 'tambourine',
780 'Bass Drum': 'bassdrum',
783 def musicxml_note_to_lily_main_event (n):
787 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
790 pitch = musicxml_pitch_to_lily (mxl_pitch)
791 event = musicexp.NoteEvent()
794 acc = n.get_maybe_exist_named_child ('accidental')
796 # let's not force accs everywhere.
797 event.cautionary = acc.editorial
799 elif n.get_maybe_exist_typed_child (musicxml.Rest):
800 # rests can have display-octave and display-step, which are
801 # treated like an ordinary note pitch
802 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
803 event = musicexp.RestEvent()
804 pitch = musicxml_restdisplay_to_lily (rest)
806 elif n.instrument_name:
807 event = musicexp.NoteEvent ()
808 drum_type = instrument_drumtype_dict.get (n.instrument_name)
810 event.drum_type = drum_type
812 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
813 event.drum_type = 'acousticsnare'
816 n.message ("cannot find suitable event")
818 event.duration = musicxml_duration_to_lily (n)
824 def __init__ (self, here, dest):
828 class LilyPondVoiceBuilder:
831 self.pending_dynamics = []
832 self.end_moment = Rational (0)
833 self.begin_moment = Rational (0)
834 self.pending_multibar = Rational (0)
835 self.ignore_skips = False
837 def _insert_multibar (self):
838 r = musicexp.MultiMeasureRest ()
839 r.duration = musicexp.Duration()
840 r.duration.duration_log = 0
841 r.duration.factor = self.pending_multibar
842 self.elements.append (r)
843 self.begin_moment = self.end_moment
844 self.end_moment = self.begin_moment + self.pending_multibar
845 self.pending_multibar = Rational (0)
847 def add_multibar_rest (self, duration):
848 self.pending_multibar += duration
850 def set_duration (self, duration):
851 self.end_moment = self.begin_moment + duration
852 def current_duration (self):
853 return self.end_moment - self.begin_moment
855 def add_music (self, music, duration):
856 assert isinstance (music, musicexp.Music)
857 if self.pending_multibar > Rational (0):
858 self._insert_multibar ()
860 self.elements.append (music)
861 self.begin_moment = self.end_moment
862 self.set_duration (duration)
864 # Insert all pending dynamics right after the note/rest:
865 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
866 for d in self.pending_dynamics:
868 self.pending_dynamics = []
870 # Insert some music command that does not affect the position in the measure
871 def add_command (self, command):
872 assert isinstance (command, musicexp.Music)
873 if self.pending_multibar > Rational (0):
874 self._insert_multibar ()
875 self.elements.append (command)
876 def add_barline (self, barline):
877 # TODO: Implement merging of default barline and custom bar line
878 self.add_music (barline, Rational (0))
879 def add_partial (self, command):
880 self.ignore_skips = True
881 self.add_command (command)
883 def add_dynamics (self, dynamic):
884 # store the dynamic item(s) until we encounter the next note/rest:
885 self.pending_dynamics.append (dynamic)
887 def add_bar_check (self, number):
888 b = musicexp.BarLine ()
889 b.bar_number = number
892 def jumpto (self, moment):
893 current_end = self.end_moment + self.pending_multibar
894 diff = moment - current_end
896 if diff < Rational (0):
897 error_message ('Negative skip %s' % diff)
900 if diff > Rational (0) and not self.ignore_skips:
901 skip = musicexp.SkipEvent()
902 skip.duration.duration_log = 0
903 skip.duration.factor = diff
905 evc = musicexp.EventChord ()
906 evc.elements.append (skip)
907 self.add_music (evc, diff)
909 if diff > Rational (0) and moment == 0:
910 self.ignore_skips = False
912 def last_event_chord (self, starting_at):
916 # if the position matches, find the last EventChord, do not cross a bar line!
917 at = len( self.elements ) - 1
919 not isinstance (self.elements[at], musicexp.EventChord) and
920 not isinstance (self.elements[at], musicexp.BarLine)):
925 and isinstance (self.elements[at], musicexp.EventChord)
926 and self.begin_moment == starting_at):
927 value = self.elements[at]
929 self.jumpto (starting_at)
933 def correct_negative_skip (self, goto):
934 self.end_moment = goto
935 self.begin_moment = goto
936 evc = musicexp.EventChord ()
937 self.elements.append (evc)
939 def musicxml_voice_to_lily_voice (voice):
944 # Needed for melismata detection (ignore lyrics on those notes!):
948 ignore_lyrics = False
950 # TODO: Make sure that the keys in the dict don't get reordered, since
951 # we need the correct ordering of the lyrics stanzas! By default,
952 # a dict will reorder its keys
953 for k in voice.get_lyrics_numbers ():
956 voice_builder = LilyPondVoiceBuilder()
958 for n in voice._elements:
959 if n.get_name () == 'forward':
962 if isinstance (n, musicxml.Partial) and n.partial > 0:
963 a = musicxml_partial_to_lily (n.partial)
965 voice_builder.add_partial (a)
968 if isinstance (n, musicxml.Direction):
969 for a in musicxml_direction_to_lily (n):
970 if a.wait_for_note ():
971 voice_builder.add_dynamics (a)
973 voice_builder.add_command (a)
976 if isinstance (n, musicxml.Harmony):
977 for a in musicxml_harmony_to_lily (n):
978 if a.wait_for_note ():
979 voice_builder.add_dynamics (a)
981 voice_builder.add_command (a)
984 is_chord = n.get_maybe_exist_named_child ('chord')
987 voice_builder.jumpto (n._when)
988 except NegativeSkip, neg:
989 voice_builder.correct_negative_skip (n._when)
990 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
992 if isinstance (n, musicxml.Attributes):
993 if n.is_first () and n._measure_position == Rational (0):
995 number = int (n.get_parent ().number)
999 voice_builder.add_bar_check (number)
1001 for a in musicxml_attributes_to_lily (n):
1002 voice_builder.add_command (a)
1005 if isinstance (n, musicxml.Barline):
1006 barlines = musicxml_barline_to_lily (n)
1008 if isinstance (a, musicexp.BarLine):
1009 voice_builder.add_barline (a)
1010 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
1011 voice_builder.add_command (a)
1014 if not n.__class__.__name__ == 'Note':
1015 error_message ('not a Note or Attributes? %s' % n)
1018 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1020 and rest.is_whole_measure ()):
1022 voice_builder.add_multibar_rest (n._duration)
1025 if n.is_first () and n._measure_position == Rational (0):
1027 num = int (n.get_parent ().number)
1031 voice_builder.add_bar_check (num)
1033 main_event = musicxml_note_to_lily_main_event (n)
1034 ignore_lyrics = inside_slur or is_tied or is_chord
1036 if hasattr (main_event, 'drum_type') and main_event.drum_type:
1037 modes_found['drummode'] = True
1040 ev_chord = voice_builder.last_event_chord (n._when)
1042 ev_chord = musicexp.EventChord()
1043 voice_builder.add_music (ev_chord, n._duration)
1045 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
1048 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
1049 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
1051 grace_chord = musicexp.EventChord ()
1052 ev_chord.append_grace (grace_chord)
1053 if hasattr (grace, 'slash'):
1054 # TODO: use grace_type = "appoggiatura" for slurred grace notes
1055 if grace.slash == "yes":
1056 ev_chord.grace_type = "acciaccatura"
1057 elif grace.slash == "no":
1058 ev_chord.grace_type = "grace"
1059 # now that we have inserted the chord into the grace music, insert
1060 # everything into that chord instead of the ev_chord
1061 ev_chord = grace_chord
1062 ev_chord.append (main_event)
1063 ignore_lyrics = True
1065 ev_chord.append (main_event)
1066 # When a note/chord has grace notes (duration==0), the duration of the
1067 # event chord is not yet known, but the event chord was already added
1068 # with duration 0. The following correct this when we hit the real note!
1069 if voice_builder.current_duration () == 0 and n._duration > 0:
1070 voice_builder.set_duration (n._duration)
1072 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
1076 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
1077 # +tied | +slur | +tuplet | glissando | slide |
1078 # ornaments | technical | articulations | dynamics |
1079 # +fermata | arpeggiate | non-arpeggiate |
1080 # accidental-mark | other-notation
1082 if notations.get_tuplet():
1083 tuplet_event = notations.get_tuplet()
1084 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1087 frac = mod.get_fraction ()
1089 tuplet_events.append ((ev_chord, tuplet_event, frac))
1091 slurs = [s for s in notations.get_named_children ('slur')
1092 if s.get_type () in ('start','stop')]
1095 error_message ('more than 1 slur?')
1096 # record the slur status for the next note in the loop
1097 if slurs[0].get_type () == 'start':
1099 elif slurs[0].get_type () == 'stop':
1101 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
1102 ev_chord.append (lily_ev)
1104 mxl_tie = notations.get_tie ()
1105 if mxl_tie and mxl_tie.type == 'start':
1106 ev_chord.append (musicexp.TieEvent ())
1111 fermatas = notations.get_named_children ('fermata')
1113 ev = musicxml_fermata_to_lily_event (a)
1115 ev_chord.append (ev)
1117 arpeggiate = notations.get_named_children ('arpeggiate')
1118 for a in arpeggiate:
1119 ev_chord.append (musicexp.ArpeggioEvent ())
1121 glissandos = notations.get_named_children ('glissando')
1122 for a in glissandos:
1123 ev = musicxml_spanner_to_lily_event (a)
1125 ev_chord.append (ev)
1127 # Articulations can contain the following child elements:
1128 # accent | strong-accent | staccato | tenuto |
1129 # detached-legato | staccatissimo | spiccato |
1130 # scoop | plop | doit | falloff | breath-mark |
1131 # caesura | stress | unstress
1132 # Technical can contain the following child elements:
1133 # up-bow | down-bow | harmonic | open-string |
1134 # thumb-position | fingering | pluck | double-tongue |
1135 # triple-tongue | stopped | snap-pizzicato | fret |
1136 # string | hammer-on | pull-off | bend | tap | heel |
1137 # toe | fingernails | other-technical
1138 # Ornaments can contain the following child elements:
1139 # trill-mark | turn | delayed-turn | inverted-turn |
1140 # shake | wavy-line | mordent | inverted-mordent |
1141 # schleifer | tremolo | other-ornament, accidental-mark
1142 ornaments = notations.get_named_children ('ornaments')
1144 for ch in a.get_named_children ('tremolo'):
1145 ev = musicxml_tremolo_to_lily_event (ch)
1147 ev_chord.append (ev)
1149 ornaments += notations.get_named_children ('articulations')
1150 ornaments += notations.get_named_children ('technical')
1153 for ch in a.get_all_children ():
1154 ev = musicxml_articulation_to_lily_event (ch)
1156 ev_chord.append (ev)
1158 dynamics = notations.get_named_children ('dynamics')
1160 for ch in a.get_all_children ():
1161 ev = musicxml_dynamics_to_lily_event (ch)
1163 ev_chord.append (ev)
1165 # Extract the lyrics
1166 if not rest and not ignore_lyrics:
1167 note_lyrics_processed = []
1168 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1169 for l in note_lyrics_elements:
1170 if l.get_number () < 0:
1171 for k in lyrics.keys ():
1172 lyrics[k].append (l.lyric_to_text ())
1173 note_lyrics_processed.append (k)
1175 lyrics[l.number].append(l.lyric_to_text ())
1176 note_lyrics_processed.append (l.number)
1177 for lnr in lyrics.keys ():
1178 if not lnr in note_lyrics_processed:
1179 lyrics[lnr].append ("\skip4")
1182 mxl_beams = [b for b in n.get_named_children ('beam')
1183 if (b.get_type () in ('begin', 'end')
1184 and b.is_primary ())]
1186 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1188 ev_chord.append (beam_ev)
1191 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1194 frac = mod.get_fraction ()
1196 tuplet_events.append ((ev_chord, tuplet_event, frac))
1198 ## force trailing mm rests to be written out.
1199 voice_builder.add_music (musicexp.EventChord (), Rational (0))
1201 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1202 ly_voice = group_repeats (ly_voice)
1204 seq_music = musicexp.SequentialMusic ()
1206 if 'drummode' in modes_found.keys ():
1207 ## \key <pitch> barfs in drummode.
1208 ly_voice = [e for e in ly_voice
1209 if not isinstance(e, musicexp.KeySignatureChange)]
1211 seq_music.elements = ly_voice
1213 for k in lyrics.keys ():
1214 lyrics_dict[k] = musicexp.Lyrics ()
1215 lyrics_dict[k].lyrics_syllables = lyrics[k]
1218 if len (modes_found) > 1:
1219 error_message ('Too many modes found %s' % modes_found.keys ())
1221 return_value = seq_music
1222 for mode in modes_found.keys ():
1223 v = musicexp.ModeChangingMusicWrapper()
1224 v.element = return_value
1228 return (return_value, lyrics_dict)
1231 def musicxml_id_to_lily (id):
1232 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1233 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1235 for digit in digits:
1236 d = digits.index (digit)
1237 id = re.sub ('%d' % d, digit, id)
1239 id = re.sub ('[^a-zA-Z]', 'X', id)
1243 def musicxml_pitch_to_lily (mxl_pitch):
1244 p = musicexp.Pitch()
1245 p.alteration = mxl_pitch.get_alteration ()
1246 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1247 p.octave = mxl_pitch.get_octave () - 4
1250 def musicxml_restdisplay_to_lily (mxl_rest):
1252 step = mxl_rest.get_step ()
1254 p = musicexp.Pitch()
1255 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1256 octave = mxl_rest.get_octave ()
1258 p.octave = octave - 4
1261 def voices_in_part (part):
1262 """Return a Name -> Voice dictionary for PART"""
1264 part.extract_voices ()
1265 voice_dict = part.get_voices ()
1269 def voices_in_part_in_parts (parts):
1270 """return a Part -> Name -> Voice dictionary"""
1271 return dict([(p, voices_in_part (p)) for p in parts])
1274 def get_all_voices (parts):
1275 all_voices = voices_in_part_in_parts (parts)
1278 for p, name_voice in all_voices.items ():
1281 for n, v in name_voice.items ():
1282 progress ("Converting to LilyPond expressions...")
1283 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1284 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
1286 all_ly_voices[p] = part_ly_voices
1288 return all_ly_voices
1291 def option_parser ():
1292 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1293 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1295 _ ("""This program is free software. It is covered by the GNU General Public
1296 License and you are welcome to change it and/or distribute copies of it
1297 under certain conditions. Invoke as `%s --warranty' for more
1298 information.""") % 'lilypond'
1300 Copyright (c) 2005--2007 by
1301 Han-Wen Nienhuys <hanwen@xs4all.nl> and
1302 Jan Nieuwenhuizen <janneke@gnu.org>
1304 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1305 p.add_option ('-v', '--verbose',
1306 action="store_true",
1308 help=_ ("be verbose"))
1310 p.add_option ('', '--lxml',
1311 action="store_true",
1314 help=_ ("Use lxml.etree; uses less memory and cpu time."))
1316 p.add_option ('-o', '--output',
1322 help=_ ("set output filename to FILE"))
1323 p.add_option_group ('bugs',
1324 description=(_ ("Report bugs via")
1325 + ''' http://post.gmane.org/post.php'''
1326 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1329 def music_xml_voice_name_to_lily_name (part, name):
1330 str = "Part%sVoice%s" % (part.id, name)
1331 return musicxml_id_to_lily (str)
1333 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1334 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1335 return musicxml_id_to_lily (str)
1337 def print_voice_definitions (printer, part_list, voices):
1339 for (part, nv_dict) in voices.items():
1340 part_dict[part.id] = (part, nv_dict)
1342 for part in part_list:
1343 (p, nv_dict) = part_dict.get (part.id, (None, {}))
1344 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1345 k = music_xml_voice_name_to_lily_name (p, name)
1346 printer.dump ('%s = ' % k)
1347 voice.print_ly (printer)
1350 for l in lyrics.keys ():
1351 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1352 printer.dump ('%s = ' %lname )
1353 lyrics[l].print_ly (printer)
1358 return dict ([(elt,1) for elt in l]).keys ()
1360 # format the information about the staff in the form
1363 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1364 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1368 # raw_voices is of the form [(voicename, lyrics)*]
1369 def format_staff_info (part, staff_id, raw_voices):
1371 for (v, lyrics) in raw_voices:
1372 voice_name = music_xml_voice_name_to_lily_name (part, v)
1373 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1374 for l in lyrics.keys ()]
1375 voices.append ([voice_name, voice_lyrics])
1376 return [staff_id, voices]
1378 def update_score_setup (score_structure, part_list, voices):
1379 part_dict = dict ([(p.id, p) for p in voices.keys ()])
1380 final_part_dict = {}
1382 for part_definition in part_list:
1383 part_name = part_definition.id
1384 part = part_dict.get (part_name)
1386 error_message ('unknown part in part-list: %s' % part_name)
1389 nv_dict = voices.get (part)
1390 staves = reduce (lambda x,y: x+ y,
1391 [mxlvoice._staves.keys ()
1392 for (v, mxlvoice) in nv_dict.values ()],
1395 if len (staves) > 1:
1397 staves = uniq_list (staves)
1400 thisstaff_raw_voices = [(voice_name, lyrics)
1401 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1402 if mxlvoice._start_staff == s]
1403 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1405 thisstaff_raw_voices = [(voice_name, lyrics)
1406 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1407 staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1408 score_structure.setPartInformation (part_name, staves_info)
1410 def print_ly_preamble (printer, filename):
1411 printer.dump_version ()
1412 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1414 def read_musicxml (filename, use_lxml):
1418 tree = lxml.etree.parse (filename)
1419 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1422 from xml.dom import minidom, Node
1424 doc = minidom.parse(filename)
1425 node = doc.documentElement
1426 return musicxml.minidom_demarshal_node (node)
1431 def convert (filename, options):
1432 progress ("Reading MusicXML from %s ..." % filename)
1434 tree = read_musicxml (filename, options.use_lxml)
1436 score_structure = None
1437 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1439 score_structure = extract_score_layout (mxl_pl)
1440 part_list = mxl_pl.get_named_children ("score-part")
1442 # score information is contained in the <work>, <identification> or <movement-title> tags
1443 score_information = extract_score_information (tree)
1444 parts = tree.get_typed_children (musicxml.Part)
1445 voices = get_all_voices (parts)
1446 update_score_setup (score_structure, part_list, voices)
1448 if not options.output_name:
1449 options.output_name = os.path.basename (filename)
1450 options.output_name = os.path.splitext (options.output_name)[0]
1451 elif re.match (".*\.ly", options.output_name):
1452 options.output_name = os.path.splitext (options.output_name)[0]
1455 defs_ly_name = options.output_name + '-defs.ly'
1456 driver_ly_name = options.output_name + '.ly'
1458 printer = musicexp.Output_printer()
1459 progress ("Output to `%s'" % defs_ly_name)
1460 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1462 print_ly_preamble (printer, filename)
1463 score_information.print_ly (printer)
1464 print_voice_definitions (printer, part_list, voices)
1469 progress ("Output to `%s'" % driver_ly_name)
1470 printer = musicexp.Output_printer()
1471 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1472 print_ly_preamble (printer, filename)
1473 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1474 score_structure.print_ly (printer)
1479 def get_existing_filename_with_extension (filename, ext):
1480 if os.path.exists (filename):
1482 newfilename = filename + ".xml"
1483 if os.path.exists (newfilename):
1485 newfilename = filename + "xml"
1486 if os.path.exists (newfilename):
1491 opt_parser = option_parser()
1493 (options, args) = opt_parser.parse_args ()
1495 opt_parser.print_usage()
1498 # Allow the user to leave out the .xml or xml on the filename
1499 filename = get_existing_filename_with_extension (args[0], "xml")
1500 if filename and os.path.exists (filename):
1501 voices = convert (filename, options)
1503 progress ("Unable to find input file %s" % args[0])
1505 if __name__ == '__main__':