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 ())
70 return len (self.start) + len (self.end) == 0
71 def add_start (self, g):
72 self.start[getattr (g, 'number', "1")] = g
73 def add_end (self, g):
74 self.end[getattr (g, 'number', "1")] = g
75 def print_ly (self, printer):
76 error_message ("Unprocessed PartGroupInfo %s encountered" % self)
77 def ly_expression (self):
78 error_message ("Unprocessed PartGroupInfo %s encountered" % self)
82 def extract_score_layout (part_list):
83 layout = musicexp.StaffGroup (None)
87 def read_score_part (el):
88 if not isinstance (el, musicxml.Score_part):
90 staff = musicexp.Staff ()
92 partname = el.get_maybe_exist_named_child ('part-name')
93 # Finale gives unnamed parts the name "MusicXML Part" automatically!
94 if partname and partname.get_text() != "MusicXML Part":
95 staff.instrument_name = partname.get_text ()
96 if el.get_maybe_exist_named_child ('part-abbreviation'):
97 staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
98 # TODO: Read in the MIDI device / instrument
101 def read_score_group (el):
102 if not isinstance (el, musicxml.Part_group):
104 group = musicexp.StaffGroup ()
105 if hasattr (el, 'number'):
108 #currentgroups_dict[id] = group
109 #currentgroups.append (id)
110 if el.get_maybe_exist_named_child ('group-name'):
111 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
112 if el.get_maybe_exist_named_child ('group-abbreviation'):
113 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
114 if el.get_maybe_exist_named_child ('group-symbol'):
115 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
116 if el.get_maybe_exist_named_child ('group-barline'):
117 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
121 parts_groups = part_list.get_all_children ()
123 # the start/end group tags are not necessarily ordered correctly and groups
124 # might even overlap, so we can't go through the children sequentially!
126 # 1) Replace all Score_part objects by their corresponding Staff objects,
127 # also collect all group start/stop points into one PartGroupInfo object
129 group_info = PartGroupInfo ()
130 for el in parts_groups:
131 if isinstance (el, musicxml.Score_part):
132 if not group_info.is_empty ():
133 staves.append (group_info)
134 group_info = PartGroupInfo ()
135 staves.append (read_score_part (el))
136 elif isinstance (el, musicxml.Part_group):
137 if el.type == "start":
138 group_info.add_start (el)
139 elif el.type == "stop":
140 group_info.add_end (el)
141 if not group_info.is_empty ():
142 staves.append (group_info)
144 # 2) Now, detect the groups:
147 while pos < len (staves):
149 if isinstance (el, PartGroupInfo):
151 if len (group_starts) > 0:
152 prev_start = group_starts[-1]
153 elif len (el.end) > 0: # no group to end here
155 if len (el.end) > 0: # closes an existing group
156 ends = el.end.keys ()
157 prev_started = staves[prev_start].start.keys ()
159 intersection = filter(lambda x:x in ends, prev_started)
160 if len (intersection) > 0:
161 grpid = intersection[0]
163 # Close the last started group
164 grpid = staves[prev_start].start.keys () [0]
165 # Find the corresponding closing tag and remove it!
168 while j < len (staves) and not foundclosing:
169 if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
171 del staves[j].end[grpid]
172 if staves[j].is_empty ():
175 grpobj = staves[prev_start].start[grpid]
176 group = read_score_group (grpobj)
177 # remove the id from both the start and end
178 if el.end.has_key (grpid):
180 del staves[prev_start].start[grpid]
183 # replace the staves with the whole group
184 for j in staves[(prev_start + 1):pos]:
186 j.stafftype = "InnerStaffGroup"
187 group.append_staff (j)
188 del staves[(prev_start + 1):pos]
189 staves.insert (prev_start + 1, group)
190 # reset pos so that we continue at the correct position
192 # remove an empty start group
193 if staves[prev_start].is_empty ():
194 del staves[prev_start]
195 group_starts.remove (prev_start)
197 elif len (el.start) > 0: # starts new part groups
198 group_starts.append (pos)
201 if len (staves) == 1:
204 layout.append_staff (i)
209 def musicxml_duration_to_lily (mxl_note):
210 d = musicexp.Duration ()
211 # if the note has no Type child, then that method spits out a warning and
212 # returns 0, i.e. a whole note
213 d.duration_log = mxl_note.get_duration_log ()
215 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
216 # Grace notes by specification have duration 0, so no time modification
217 # factor is possible. It even messes up the output with *0/1
218 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
219 d.factor = mxl_note._duration / d.get_length ()
223 def rational_to_lily_duration (rational_len):
224 d = musicexp.Duration ()
225 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)
226 d.factor = Rational (rational_len.numerator ())
227 if d.duration_log < 0:
228 error_message ("Encountered rational duration with denominator %s, "
229 "unable to convert to lilypond duration" %
230 rational_len.denominator ())
231 # TODO: Test the above error message
236 def musicxml_partial_to_lily (partial_len):
238 p = musicexp.Partial ()
239 p.partial = rational_to_lily_duration (partial_len)
244 # Detect repeats and alternative endings in the chord event list (music_list)
245 # and convert them to the corresponding musicexp objects, containing nested
247 def group_repeats (music_list):
248 repeat_replaced = True
251 # Walk through the list of expressions, looking for repeat structure
252 # (repeat start/end, corresponding endings). If we find one, try to find the
253 # last event of the repeat, replace the whole structure and start over again.
254 # For nested repeats, as soon as we encounter another starting repeat bar,
255 # treat that one first, and start over for the outer repeat.
256 while repeat_replaced and i < 100:
258 repeat_start = -1 # position of repeat start / end
259 repeat_end = -1 # position of repeat start / end
261 ending_start = -1 # position of current ending start
262 endings = [] # list of already finished endings
264 last = len (music_list) - 1
265 repeat_replaced = False
267 while pos < len (music_list) and not repeat_replaced:
269 repeat_finished = False
270 if isinstance (e, RepeatMarker):
271 if not repeat_times and e.times:
272 repeat_times = e.times
273 if e.direction == -1:
275 repeat_finished = True
281 elif e.direction == 1:
287 elif isinstance (e, EndingMarker):
288 if e.direction == -1:
294 elif e.direction == 1:
297 endings.append ([ending_start, pos])
300 elif not isinstance (e, musicexp.BarLine):
301 # As soon as we encounter an element when repeat start and end
302 # is set and we are not inside an alternative ending,
303 # this whole repeat structure is finished => replace it
304 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
305 repeat_finished = True
307 # Finish off all repeats without explicit ending bar (e.g. when
308 # we convert only one page of a multi-page score with repeats)
309 if pos == last and repeat_start >= 0:
310 repeat_finished = True
314 if ending_start >= 0:
315 endings.append ([ending_start, pos])
319 # We found the whole structure replace it!
320 r = musicexp.RepeatedMusic ()
321 if repeat_times <= 0:
323 r.repeat_count = repeat_times
324 # don't erase the first element for "implicit" repeats (i.e. no
325 # starting repeat bars at the very beginning)
326 start = repeat_start+1
327 if repeat_start == music_start:
329 r.set_music (music_list[start:repeat_end])
330 for (start, end) in endings:
331 s = musicexp.SequentialMusic ()
332 s.elements = music_list[start+1:end]
334 del music_list[repeat_start:final_marker+1]
335 music_list.insert (repeat_start, r)
336 repeat_replaced = True
338 # TODO: Implement repeats until the end without explicit ending bar
343 def group_tuplets (music_list, events):
346 """Collect Musics from
347 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
354 for (ev_chord, tuplet_elt, fraction) in events:
355 while (j < len (music_list)):
356 if music_list[j] == ev_chord:
359 if tuplet_elt.type == 'start':
360 indices.append ((j, None, fraction))
361 elif tuplet_elt.type == 'stop':
362 indices[-1] = (indices[-1][0], j, indices[-1][2])
366 for (i1, i2, frac) in indices:
370 new_list.extend (music_list[last:i1])
371 seq = musicexp.SequentialMusic ()
373 seq.elements = music_list[i1:last]
375 tsm = musicexp.TimeScaledMusic ()
378 tsm.numerator = frac[0]
379 tsm.denominator = frac[1]
381 new_list.append (tsm)
383 new_list.extend (music_list[last:])
387 def musicxml_clef_to_lily (attributes):
388 change = musicexp.ClefChange ()
389 (change.type, change.position, change.octave) = attributes.get_clef_information ()
392 def musicxml_time_to_lily (attributes):
393 (beats, type) = attributes.get_time_signature ()
395 change = musicexp.TimeSignatureChange()
396 change.fraction = (beats, type)
400 def musicxml_key_to_lily (attributes):
401 start_pitch = musicexp.Pitch ()
402 (fifths, mode) = attributes.get_key_signature ()
409 start_pitch.alteration = a
411 error_message ('unknown mode %s' % mode)
413 fifth = musicexp.Pitch()
420 for x in range (fifths):
421 start_pitch = start_pitch.transposed (fifth)
423 start_pitch.octave = 0
425 change = musicexp.KeySignatureChange()
427 change.tonic = start_pitch
430 def musicxml_attributes_to_lily (attrs):
433 'clef': musicxml_clef_to_lily,
434 'time': musicxml_time_to_lily,
435 'key': musicxml_key_to_lily
437 for (k, func) in attr_dispatch.items ():
438 children = attrs.get_named_children (k)
440 elts.append (func (attrs))
444 class Marker (musicexp.Music):
448 def print_ly (self, printer):
449 sys.stderr.write ("Encountered unprocessed marker %s\n" % self)
451 def ly_expression (self):
453 class RepeatMarker (Marker):
455 Marker.__init__ (self)
457 class EndingMarker (Marker):
460 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
461 # and to RepeatMarker and EndingMarker objects for repeat and
462 # alternatives start/stops
463 def musicxml_barline_to_lily (barline):
464 # retval contains all possible markers in the order:
465 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
467 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
468 repeat_element = barline.get_maybe_exist_named_child ("repeat")
469 ending_element = barline.get_maybe_exist_named_child ("ending")
473 bartype = bartype_element.get_text ()
475 if repeat_element and hasattr (repeat_element, 'direction'):
476 repeat = RepeatMarker ()
477 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
479 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
480 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
482 if hasattr (repeat_element, 'times'):
484 repeat.times = int (repeat_element.times)
487 repeat.event = barline
488 if repeat.direction == -1:
493 if ending_element and hasattr (ending_element, 'type'):
494 ending = EndingMarker ()
495 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
496 ending.event = barline
497 if ending.direction == -1:
503 b = musicexp.BarLine ()
507 return retval.values ()
509 spanner_event_dict = {
510 'slur' : musicexp.SlurEvent,
511 'beam' : musicexp.BeamEvent,
512 'glissando' : musicexp.GlissandoEvent,
513 'pedal' : musicexp.PedalEvent,
514 'wavy-line' : musicexp.TrillSpanEvent,
515 'octave-shift' : musicexp.OctaveShiftEvent,
516 'wedge' : musicexp.HairpinEvent
518 spanner_type_dict = {
531 def musicxml_spanner_to_lily_event (mxl_event):
534 name = mxl_event.get_name()
535 func = spanner_event_dict.get (name)
539 error_message ('unknown span event %s' % mxl_event)
542 type = mxl_event.get_type ()
543 span_direction = spanner_type_dict.get (type)
544 # really check for None, because some types will be translated to 0, which
545 # would otherwise also lead to the unknown span warning
546 if span_direction != None:
547 ev.span_direction = span_direction
549 error_message ('unknown span type %s for %s' % (type, name))
551 ev.set_span_type (type)
552 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
554 # assign the size, which is used for octave-shift, etc.
555 ev.size = mxl_event.get_size ()
559 def musicxml_direction_to_indicator (direction):
560 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
562 def musicxml_fermata_to_lily_event (mxl_event):
563 ev = musicexp.ArticulationEvent ()
565 if hasattr (mxl_event, 'type'):
566 dir = musicxml_direction_to_indicator (mxl_event.type)
568 ev.force_direction = dir
571 def musicxml_tremolo_to_lily_event (mxl_event):
572 ev = musicexp.TremoloEvent ()
573 ev.bars = mxl_event.get_text ()
576 def musicxml_bend_to_lily_event (mxl_event):
577 ev = musicexp.BendEvent ()
578 ev.alter = mxl_event.bend_alter ()
582 def musicxml_fingering_event (mxl_event):
583 ev = musicexp.ShortArticulationEvent ()
584 ev.type = mxl_event.get_text ()
587 def musicxml_accidental_mark (mxl_event):
588 ev = musicexp.MarkupEvent ()
589 contents = { "sharp": "\\sharp",
590 "natural": "\\natural",
592 "double-sharp": "\\doublesharp",
593 "sharp-sharp": "\\sharp\\sharp",
594 "flat-flat": "\\flat\\flat",
595 "flat-flat": "\\doubleflat",
596 "natural-sharp": "\\natural\\sharp",
597 "natural-flat": "\\natural\\flat",
598 "quarter-flat": "\\semiflat",
599 "quarter-sharp": "\\semisharp",
600 "three-quarters-flat": "\\sesquiflat",
601 "three-quarters-sharp": "\\sesquisharp",
602 }.get (mxl_event.get_text ())
604 ev.contents = contents
609 # translate articulations, ornaments and other notations into ArticulationEvents
611 # -) string (ArticulationEvent with that name)
612 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
613 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
614 # TODO: Some translations are missing!
615 articulations_dict = {
616 "accent": (musicexp.ShortArticulationEvent, ">"),
617 "accidental-mark": musicxml_accidental_mark,
618 "bend": musicxml_bend_to_lily_event,
619 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
620 #"caesura": "caesura",
621 #"delayed-turn": "?",
622 #"detached-legato": "",
624 #"double-tongue": "",
625 "down-bow": "downbow",
627 "fingering": musicxml_fingering_event,
631 "harmonic": "flageolet",
633 "inverted-mordent": "prall",
634 "inverted-turn": "reverseturn",
635 "mordent": "mordent",
639 #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
644 #"snap-pizzicato": "",
646 "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
647 "staccato": (musicexp.ShortArticulationEvent, "."),
648 "stopped": (musicexp.ShortArticulationEvent, "+"),
651 "strong-accent": (musicexp.ShortArticulationEvent, "^"),
653 "tenuto": (musicexp.ShortArticulationEvent, "-"),
654 #"thumb-position": "",
657 "tremolo": musicxml_tremolo_to_lily_event,
658 "trill-mark": "trill",
659 #"triple-tongue": "",
664 articulation_spanners = [ "wavy-line" ]
666 def musicxml_articulation_to_lily_event (mxl_event):
667 # wavy-line elements are treated as trill spanners, not as articulation ornaments
668 if mxl_event.get_name () in articulation_spanners:
669 return musicxml_spanner_to_lily_event (mxl_event)
671 tmp_tp = articulations_dict.get (mxl_event.get_name ())
675 if isinstance (tmp_tp, str):
676 ev = musicexp.ArticulationEvent ()
678 elif isinstance (tmp_tp, tuple):
682 ev = tmp_tp (mxl_event)
684 # Some articulations use the type attribute, other the placement...
686 if hasattr (mxl_event, 'type'):
687 dir = musicxml_direction_to_indicator (mxl_event.type)
688 if hasattr (mxl_event, 'placement'):
689 dir = musicxml_direction_to_indicator (mxl_event.placement)
693 def musicxml_dynamics_to_lily_event (dynentry):
694 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
695 "f", "ff", "fff", "ffff", "fffff", "ffffff",
696 "mp", "mf", "sf", "sfp", "sfpp", "fp",
697 "rf", "rfz", "sfz", "sffz", "fz" )
698 if not dynentry.get_name() in dynamics_available:
700 event = musicexp.DynamicsEvent ()
701 event.type = dynentry.get_name ()
704 # Convert single-color two-byte strings to numbers 0.0 - 1.0
705 def hexcolorval_to_nr (hex_val):
707 v = int (hex_val, 16)
714 def hex_to_color (hex_val):
715 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)
717 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
721 def musicxml_words_to_lily_event (words):
722 event = musicexp.TextEvent ()
723 text = words.get_text ()
724 text = re.sub ('^ *\n? *', '', text)
725 text = re.sub (' *\n? *$', '', text)
728 if hasattr (words, 'default-y'):
729 offset = getattr (words, 'default-y')
731 off = string.atoi (offset)
733 event.force_direction = 1
735 event.force_direction = -1
737 event.force_direction = 0
739 if hasattr (words, 'font-weight'):
740 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
742 event.markup += font_weight
744 if hasattr (words, 'font-size'):
745 size = getattr (words, 'font-size')
747 "xx-small": '\\teeny',
753 "xx-large": '\\bigger\\huge'
756 event.markup += font_size
758 if hasattr (words, 'color'):
759 color = getattr (words, 'color')
760 rgb = hex_to_color (color)
762 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
764 if hasattr (words, 'font-style'):
765 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
767 event.markup += font_style
769 # TODO: How should I best convert the font-family attribute?
771 # TODO: How can I represent the underline, overline and line-through
772 # attributes in Lilypond? Values of these attributes indicate
773 # the number of lines
778 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
780 def musicxml_direction_to_lily (n):
781 # TODO: Handle the <staff> element!
783 dirtype_children = []
784 for dt in n.get_typed_children (musicxml.DirType):
785 dirtype_children += dt.get_all_children ()
787 for entry in dirtype_children:
789 if entry.get_name () == "dynamics":
790 for dynentry in entry.get_all_children ():
791 ev = musicxml_dynamics_to_lily_event (dynentry)
795 if entry.get_name () == "words":
796 ev = musicxml_words_to_lily_event (entry)
800 # octave shifts. pedal marks, hairpins etc. are spanners:
801 if entry.get_name() in direction_spanners:
802 event = musicxml_spanner_to_lily_event (entry)
809 def musicxml_frame_to_lily_event (frame):
810 ev = musicexp.FretEvent ()
811 ev.strings = frame.get_strings ()
812 ev.frets = frame.get_frets ()
813 #offset = frame.get_first_fret () - 1
815 for fn in frame.get_named_children ('frame-note'):
816 fret = fn.get_fret ()
819 el = [ fn.get_string (), fret ]
820 fingering = fn.get_fingering ()
822 el.append (fingering)
823 ev.elements.append (el)
826 barre[0] = el[0] # start string
827 barre[2] = el[1] # fret
829 barre[1] = el[0] # end string
834 def musicxml_harmony_to_lily (n):
836 for f in n.get_named_children ('frame'):
837 ev = musicxml_frame_to_lily_event (f)
843 instrument_drumtype_dict = {
844 'Acoustic Snare Drum': 'acousticsnare',
845 'Side Stick': 'sidestick',
846 'Open Triangle': 'opentriangle',
847 'Mute Triangle': 'mutetriangle',
848 'Tambourine': 'tambourine',
849 'Bass Drum': 'bassdrum',
852 def musicxml_note_to_lily_main_event (n):
856 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
859 pitch = musicxml_pitch_to_lily (mxl_pitch)
860 event = musicexp.NoteEvent()
863 acc = n.get_maybe_exist_named_child ('accidental')
865 # let's not force accs everywhere.
866 event.cautionary = acc.editorial
868 elif n.get_maybe_exist_typed_child (musicxml.Rest):
869 # rests can have display-octave and display-step, which are
870 # treated like an ordinary note pitch
871 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
872 event = musicexp.RestEvent()
873 pitch = musicxml_restdisplay_to_lily (rest)
875 elif n.instrument_name:
876 event = musicexp.NoteEvent ()
877 drum_type = instrument_drumtype_dict.get (n.instrument_name)
879 event.drum_type = drum_type
881 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
882 event.drum_type = 'acousticsnare'
885 n.message ("cannot find suitable event")
887 event.duration = musicxml_duration_to_lily (n)
893 def __init__ (self, here, dest):
897 class LilyPondVoiceBuilder:
900 self.pending_dynamics = []
901 self.end_moment = Rational (0)
902 self.begin_moment = Rational (0)
903 self.pending_multibar = Rational (0)
904 self.ignore_skips = False
906 def _insert_multibar (self):
907 r = musicexp.MultiMeasureRest ()
908 r.duration = musicexp.Duration()
909 r.duration.duration_log = 0
910 r.duration.factor = self.pending_multibar
911 self.elements.append (r)
912 self.begin_moment = self.end_moment
913 self.end_moment = self.begin_moment + self.pending_multibar
914 self.pending_multibar = Rational (0)
916 def add_multibar_rest (self, duration):
917 self.pending_multibar += duration
919 def set_duration (self, duration):
920 self.end_moment = self.begin_moment + duration
921 def current_duration (self):
922 return self.end_moment - self.begin_moment
924 def add_music (self, music, duration):
925 assert isinstance (music, musicexp.Music)
926 if self.pending_multibar > Rational (0):
927 self._insert_multibar ()
929 self.elements.append (music)
930 self.begin_moment = self.end_moment
931 self.set_duration (duration)
933 # Insert all pending dynamics right after the note/rest:
934 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
935 for d in self.pending_dynamics:
937 self.pending_dynamics = []
939 # Insert some music command that does not affect the position in the measure
940 def add_command (self, command):
941 assert isinstance (command, musicexp.Music)
942 if self.pending_multibar > Rational (0):
943 self._insert_multibar ()
944 self.elements.append (command)
945 def add_barline (self, barline):
946 # TODO: Implement merging of default barline and custom bar line
947 self.add_music (barline, Rational (0))
948 def add_partial (self, command):
949 self.ignore_skips = True
950 self.add_command (command)
952 def add_dynamics (self, dynamic):
953 # store the dynamic item(s) until we encounter the next note/rest:
954 self.pending_dynamics.append (dynamic)
956 def add_bar_check (self, number):
957 b = musicexp.BarLine ()
958 b.bar_number = number
961 def jumpto (self, moment):
962 current_end = self.end_moment + self.pending_multibar
963 diff = moment - current_end
965 if diff < Rational (0):
966 error_message ('Negative skip %s' % diff)
969 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
970 skip = musicexp.SkipEvent()
971 skip.duration.duration_log = 0
972 skip.duration.factor = diff
974 evc = musicexp.EventChord ()
975 evc.elements.append (skip)
976 self.add_music (evc, diff)
978 if diff > Rational (0) and moment == 0:
979 self.ignore_skips = False
981 def last_event_chord (self, starting_at):
985 # if the position matches, find the last EventChord, do not cross a bar line!
986 at = len( self.elements ) - 1
988 not isinstance (self.elements[at], musicexp.EventChord) and
989 not isinstance (self.elements[at], musicexp.BarLine)):
994 and isinstance (self.elements[at], musicexp.EventChord)
995 and self.begin_moment == starting_at):
996 value = self.elements[at]
998 self.jumpto (starting_at)
1002 def correct_negative_skip (self, goto):
1003 self.end_moment = goto
1004 self.begin_moment = goto
1005 evc = musicexp.EventChord ()
1006 self.elements.append (evc)
1010 def __init__ (self):
1011 self.voicedata = None
1012 self.ly_voice = None
1013 self.lyrics_dict = {}
1014 self.lyrics_order = []
1016 def musicxml_voice_to_lily_voice (voice):
1020 return_value = VoiceData ()
1021 return_value.voicedata = voice
1023 # Needed for melismata detection (ignore lyrics on those notes!):
1027 ignore_lyrics = False
1029 current_staff = None
1031 # TODO: Make sure that the keys in the dict don't get reordered, since
1032 # we need the correct ordering of the lyrics stanzas! By default,
1033 # a dict will reorder its keys
1034 return_value.lyrics_order = voice.get_lyrics_numbers ()
1035 for k in return_value.lyrics_order:
1038 voice_builder = LilyPondVoiceBuilder()
1040 for n in voice._elements:
1041 if n.get_name () == 'forward':
1043 staff = n.get_maybe_exist_named_child ('staff')
1045 staff = staff.get_text ()
1046 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
1047 voice_builder.add_command (musicexp.StaffChange (staff))
1048 current_staff = staff
1050 if isinstance (n, musicxml.Partial) and n.partial > 0:
1051 a = musicxml_partial_to_lily (n.partial)
1053 voice_builder.add_partial (a)
1056 if isinstance (n, musicxml.Direction):
1057 for a in musicxml_direction_to_lily (n):
1058 if a.wait_for_note ():
1059 voice_builder.add_dynamics (a)
1061 voice_builder.add_command (a)
1064 if isinstance (n, musicxml.Harmony):
1065 for a in musicxml_harmony_to_lily (n):
1066 if a.wait_for_note ():
1067 voice_builder.add_dynamics (a)
1069 voice_builder.add_command (a)
1072 is_chord = n.get_maybe_exist_named_child ('chord')
1075 voice_builder.jumpto (n._when)
1076 except NegativeSkip, neg:
1077 voice_builder.correct_negative_skip (n._when)
1078 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
1080 if isinstance (n, musicxml.Attributes):
1081 if n.is_first () and n._measure_position == Rational (0):
1083 number = int (n.get_parent ().number)
1087 voice_builder.add_bar_check (number)
1089 for a in musicxml_attributes_to_lily (n):
1090 voice_builder.add_command (a)
1093 if isinstance (n, musicxml.Barline):
1094 barlines = musicxml_barline_to_lily (n)
1096 if isinstance (a, musicexp.BarLine):
1097 voice_builder.add_barline (a)
1098 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
1099 voice_builder.add_command (a)
1102 if not n.__class__.__name__ == 'Note':
1103 error_message ('not a Note or Attributes? %s' % n)
1106 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1108 and rest.is_whole_measure ()):
1110 voice_builder.add_multibar_rest (n._duration)
1113 if n.is_first () and n._measure_position == Rational (0):
1115 num = int (n.get_parent ().number)
1119 voice_builder.add_bar_check (num)
1121 main_event = musicxml_note_to_lily_main_event (n)
1122 ignore_lyrics = inside_slur or is_tied or is_chord
1124 if hasattr (main_event, 'drum_type') and main_event.drum_type:
1125 modes_found['drummode'] = True
1128 ev_chord = voice_builder.last_event_chord (n._when)
1130 ev_chord = musicexp.EventChord()
1131 voice_builder.add_music (ev_chord, n._duration)
1133 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
1136 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
1137 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
1139 grace_chord = musicexp.EventChord ()
1140 ev_chord.append_grace (grace_chord)
1141 if hasattr (grace, 'slash'):
1142 # TODO: use grace_type = "appoggiatura" for slurred grace notes
1143 if grace.slash == "yes":
1144 ev_chord.grace_type = "acciaccatura"
1145 elif grace.slash == "no":
1146 ev_chord.grace_type = "grace"
1147 # now that we have inserted the chord into the grace music, insert
1148 # everything into that chord instead of the ev_chord
1149 ev_chord = grace_chord
1150 ev_chord.append (main_event)
1151 ignore_lyrics = True
1153 ev_chord.append (main_event)
1154 # When a note/chord has grace notes (duration==0), the duration of the
1155 # event chord is not yet known, but the event chord was already added
1156 # with duration 0. The following correct this when we hit the real note!
1157 if voice_builder.current_duration () == 0 and n._duration > 0:
1158 voice_builder.set_duration (n._duration)
1160 notations_children = n.get_typed_children (musicxml.Notations)
1164 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
1165 # +tied | +slur | +tuplet | glissando | slide |
1166 # ornaments | technical | articulations | dynamics |
1167 # +fermata | arpeggiate | non-arpeggiate |
1168 # accidental-mark | other-notation
1169 for notations in notations_children:
1170 if notations.get_tuplet():
1171 tuplet_event = notations.get_tuplet()
1172 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1175 frac = mod.get_fraction ()
1177 tuplet_events.append ((ev_chord, tuplet_event, frac))
1179 slurs = [s for s in notations.get_named_children ('slur')
1180 if s.get_type () in ('start','stop')]
1183 error_message ('more than 1 slur?')
1184 # record the slur status for the next note in the loop
1186 if slurs[0].get_type () == 'start':
1188 elif slurs[0].get_type () == 'stop':
1190 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
1191 ev_chord.append (lily_ev)
1194 mxl_tie = notations.get_tie ()
1195 if mxl_tie and mxl_tie.type == 'start':
1196 ev_chord.append (musicexp.TieEvent ())
1201 fermatas = notations.get_named_children ('fermata')
1203 ev = musicxml_fermata_to_lily_event (a)
1205 ev_chord.append (ev)
1207 arpeggiate = notations.get_named_children ('arpeggiate')
1208 for a in arpeggiate:
1209 ev_chord.append (musicexp.ArpeggioEvent ())
1211 glissandos = notations.get_named_children ('glissando')
1212 for a in glissandos:
1213 ev = musicxml_spanner_to_lily_event (a)
1215 ev_chord.append (ev)
1217 # Articulations can contain the following child elements:
1218 # accent | strong-accent | staccato | tenuto |
1219 # detached-legato | staccatissimo | spiccato |
1220 # scoop | plop | doit | falloff | breath-mark |
1221 # caesura | stress | unstress
1222 # Technical can contain the following child elements:
1223 # up-bow | down-bow | harmonic | open-string |
1224 # thumb-position | fingering | pluck | double-tongue |
1225 # triple-tongue | stopped | snap-pizzicato | fret |
1226 # string | hammer-on | pull-off | bend | tap | heel |
1227 # toe | fingernails | other-technical
1228 # Ornaments can contain the following child elements:
1229 # trill-mark | turn | delayed-turn | inverted-turn |
1230 # shake | wavy-line | mordent | inverted-mordent |
1231 # schleifer | tremolo | other-ornament, accidental-mark
1232 ornaments = notations.get_named_children ('ornaments')
1234 for ch in a.get_named_children ('tremolo'):
1235 ev = musicxml_tremolo_to_lily_event (ch)
1237 ev_chord.append (ev)
1239 ornaments += notations.get_named_children ('articulations')
1240 ornaments += notations.get_named_children ('technical')
1243 for ch in a.get_all_children ():
1244 ev = musicxml_articulation_to_lily_event (ch)
1246 ev_chord.append (ev)
1248 dynamics = notations.get_named_children ('dynamics')
1250 for ch in a.get_all_children ():
1251 ev = musicxml_dynamics_to_lily_event (ch)
1253 ev_chord.append (ev)
1255 # Extract the lyrics
1256 if not rest and not ignore_lyrics:
1257 note_lyrics_processed = []
1258 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1259 for l in note_lyrics_elements:
1260 if l.get_number () < 0:
1261 for k in lyrics.keys ():
1262 lyrics[k].append (l.lyric_to_text ())
1263 note_lyrics_processed.append (k)
1265 lyrics[l.number].append(l.lyric_to_text ())
1266 note_lyrics_processed.append (l.number)
1267 for lnr in lyrics.keys ():
1268 if not lnr in note_lyrics_processed:
1269 lyrics[lnr].append ("\skip4")
1272 mxl_beams = [b for b in n.get_named_children ('beam')
1273 if (b.get_type () in ('begin', 'end')
1274 and b.is_primary ())]
1276 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1278 ev_chord.append (beam_ev)
1281 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1284 frac = mod.get_fraction ()
1286 tuplet_events.append ((ev_chord, tuplet_event, frac))
1288 ## force trailing mm rests to be written out.
1289 voice_builder.add_music (musicexp.EventChord (), Rational (0))
1291 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1292 ly_voice = group_repeats (ly_voice)
1294 seq_music = musicexp.SequentialMusic ()
1296 if 'drummode' in modes_found.keys ():
1297 ## \key <pitch> barfs in drummode.
1298 ly_voice = [e for e in ly_voice
1299 if not isinstance(e, musicexp.KeySignatureChange)]
1301 seq_music.elements = ly_voice
1302 for k in lyrics.keys ():
1303 return_value.lyrics_dict[k] = musicexp.Lyrics ()
1304 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
1307 if len (modes_found) > 1:
1308 error_message ('Too many modes found %s' % modes_found.keys ())
1310 return_value.ly_voice = seq_music
1311 for mode in modes_found.keys ():
1312 v = musicexp.ModeChangingMusicWrapper()
1313 v.element = seq_music
1315 return_value.ly_voice = v
1320 def musicxml_id_to_lily (id):
1321 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1322 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1324 for digit in digits:
1325 d = digits.index (digit)
1326 id = re.sub ('%d' % d, digit, id)
1328 id = re.sub ('[^a-zA-Z]', 'X', id)
1332 def musicxml_pitch_to_lily (mxl_pitch):
1333 p = musicexp.Pitch()
1334 p.alteration = mxl_pitch.get_alteration ()
1335 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1336 p.octave = mxl_pitch.get_octave () - 4
1339 def musicxml_restdisplay_to_lily (mxl_rest):
1341 step = mxl_rest.get_step ()
1343 p = musicexp.Pitch()
1344 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1345 octave = mxl_rest.get_octave ()
1347 p.octave = octave - 4
1350 def voices_in_part (part):
1351 """Return a Name -> Voice dictionary for PART"""
1353 part.extract_voices ()
1354 voice_dict = part.get_voices ()
1358 def voices_in_part_in_parts (parts):
1359 """return a Part -> Name -> Voice dictionary"""
1360 return dict([(p, voices_in_part (p)) for p in parts])
1363 def get_all_voices (parts):
1364 all_voices = voices_in_part_in_parts (parts)
1367 for p, name_voice in all_voices.items ():
1370 for n, v in name_voice.items ():
1371 progress ("Converting to LilyPond expressions...")
1372 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1373 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
1375 all_ly_voices[p] = part_ly_voices
1377 return all_ly_voices
1380 def option_parser ():
1381 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1382 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1384 _ ("""This program is free software. It is covered by the GNU General Public
1385 License and you are welcome to change it and/or distribute copies of it
1386 under certain conditions. Invoke as `%s --warranty' for more
1387 information.""") % 'lilypond'
1389 Copyright (c) 2005--2007 by
1390 Han-Wen Nienhuys <hanwen@xs4all.nl> and
1391 Jan Nieuwenhuizen <janneke@gnu.org>
1393 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1394 p.add_option ('-v', '--verbose',
1395 action="store_true",
1397 help=_ ("be verbose"))
1399 p.add_option ('', '--lxml',
1400 action="store_true",
1403 help=_ ("Use lxml.etree; uses less memory and cpu time."))
1405 p.add_option ('-o', '--output',
1411 help=_ ("set output filename to FILE"))
1412 p.add_option_group ('bugs',
1413 description=(_ ("Report bugs via")
1414 + ''' http://post.gmane.org/post.php'''
1415 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1418 def music_xml_voice_name_to_lily_name (part, name):
1419 str = "Part%sVoice%s" % (part.id, name)
1420 return musicxml_id_to_lily (str)
1422 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1423 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1424 return musicxml_id_to_lily (str)
1426 def print_voice_definitions (printer, part_list, voices):
1428 for (part, nv_dict) in voices.items():
1429 part_dict[part.id] = (part, nv_dict)
1431 for part in part_list:
1432 (p, nv_dict) = part_dict.get (part.id, (None, {}))
1433 #for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1434 for (name, voice) in nv_dict.items ():
1435 k = music_xml_voice_name_to_lily_name (p, name)
1436 printer.dump ('%s = ' % k)
1437 voice.ly_voice.print_ly (printer)
1440 for l in voice.lyrics_order:
1441 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1442 printer.dump ('%s = ' %lname )
1443 voice.lyrics_dict[l].print_ly (printer)
1448 return dict ([(elt,1) for elt in l]).keys ()
1450 # format the information about the staff in the form
1453 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1454 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1458 # raw_voices is of the form [(voicename, lyricsids)*]
1459 def format_staff_info (part, staff_id, raw_voices):
1461 for (v, lyricsids) in raw_voices:
1462 voice_name = music_xml_voice_name_to_lily_name (part, v)
1463 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1465 voices.append ([voice_name, voice_lyrics])
1466 return [staff_id, voices]
1468 def update_score_setup (score_structure, part_list, voices):
1469 part_dict = dict ([(p.id, p) for p in voices.keys ()])
1470 final_part_dict = {}
1472 for part_definition in part_list:
1473 part_name = part_definition.id
1474 part = part_dict.get (part_name)
1476 error_message ('unknown part in part-list: %s' % part_name)
1479 nv_dict = voices.get (part)
1480 staves = reduce (lambda x,y: x+ y,
1481 [voice.voicedata._staves.keys ()
1482 for voice in nv_dict.values ()],
1485 if len (staves) > 1:
1487 staves = uniq_list (staves)
1490 #((music, lyrics), mxlvoice))
1491 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1492 for (voice_name, voice) in nv_dict.items ()
1493 if voice.voicedata._start_staff == s]
1494 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1496 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1497 for (voice_name, voice) in nv_dict.items ()]
1498 staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1499 score_structure.set_part_information (part_name, staves_info)
1501 def print_ly_preamble (printer, filename):
1502 printer.dump_version ()
1503 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1505 def read_musicxml (filename, use_lxml):
1509 tree = lxml.etree.parse (filename)
1510 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1513 from xml.dom import minidom, Node
1515 doc = minidom.parse(filename)
1516 node = doc.documentElement
1517 return musicxml.minidom_demarshal_node (node)
1522 def convert (filename, options):
1523 progress ("Reading MusicXML from %s ..." % filename)
1525 tree = read_musicxml (filename, options.use_lxml)
1527 score_structure = None
1528 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1530 score_structure = extract_score_layout (mxl_pl)
1531 part_list = mxl_pl.get_named_children ("score-part")
1533 # score information is contained in the <work>, <identification> or <movement-title> tags
1534 score_information = extract_score_information (tree)
1535 parts = tree.get_typed_children (musicxml.Part)
1536 voices = get_all_voices (parts)
1537 update_score_setup (score_structure, part_list, voices)
1539 if not options.output_name:
1540 options.output_name = os.path.basename (filename)
1541 options.output_name = os.path.splitext (options.output_name)[0]
1542 elif re.match (".*\.ly", options.output_name):
1543 options.output_name = os.path.splitext (options.output_name)[0]
1546 defs_ly_name = options.output_name + '-defs.ly'
1547 driver_ly_name = options.output_name + '.ly'
1549 printer = musicexp.Output_printer()
1550 progress ("Output to `%s'" % defs_ly_name)
1551 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1553 print_ly_preamble (printer, filename)
1554 score_information.print_ly (printer)
1555 print_voice_definitions (printer, part_list, voices)
1560 progress ("Output to `%s'" % driver_ly_name)
1561 printer = musicexp.Output_printer()
1562 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1563 print_ly_preamble (printer, filename)
1564 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1565 score_structure.print_ly (printer)
1570 def get_existing_filename_with_extension (filename, ext):
1571 if os.path.exists (filename):
1573 newfilename = filename + ".xml"
1574 if os.path.exists (newfilename):
1576 newfilename = filename + "xml"
1577 if os.path.exists (newfilename):
1582 opt_parser = option_parser()
1584 (options, args) = opt_parser.parse_args ()
1586 opt_parser.print_usage()
1589 # Allow the user to leave out the .xml or xml on the filename
1590 filename = get_existing_filename_with_extension (args[0], "xml")
1591 if filename and os.path.exists (filename):
1592 voices = convert (filename, options)
1594 progress ("Unable to find input file %s" % args[0])
1596 if __name__ == '__main__':