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_string_event (mxl_event):
588 ev = musicexp.NoDirectionArticulationEvent ()
589 ev.type = mxl_event.get_text ()
592 def musicxml_accidental_mark (mxl_event):
593 ev = musicexp.MarkupEvent ()
594 contents = { "sharp": "\\sharp",
595 "natural": "\\natural",
597 "double-sharp": "\\doublesharp",
598 "sharp-sharp": "\\sharp\\sharp",
599 "flat-flat": "\\flat\\flat",
600 "flat-flat": "\\doubleflat",
601 "natural-sharp": "\\natural\\sharp",
602 "natural-flat": "\\natural\\flat",
603 "quarter-flat": "\\semiflat",
604 "quarter-sharp": "\\semisharp",
605 "three-quarters-flat": "\\sesquiflat",
606 "three-quarters-sharp": "\\sesquisharp",
607 }.get (mxl_event.get_text ())
609 ev.contents = contents
614 # translate articulations, ornaments and other notations into ArticulationEvents
616 # -) string (ArticulationEvent with that name)
617 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
618 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
619 # TODO: Some translations are missing!
620 articulations_dict = {
621 "accent": (musicexp.ShortArticulationEvent, ">"),
622 "accidental-mark": musicxml_accidental_mark,
623 "bend": musicxml_bend_to_lily_event,
624 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
625 #"caesura": "caesura",
626 #"delayed-turn": "?",
627 #"detached-legato": "",
629 #"double-tongue": "",
630 "down-bow": "downbow",
632 "fingering": musicxml_fingering_event,
636 "harmonic": "flageolet",
638 "inverted-mordent": "prall",
639 "inverted-turn": "reverseturn",
640 "mordent": "mordent",
644 #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
649 #"snap-pizzicato": "",
651 "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
652 "staccato": (musicexp.ShortArticulationEvent, "."),
653 "stopped": (musicexp.ShortArticulationEvent, "+"),
655 "string": musicxml_string_event,
656 "strong-accent": (musicexp.ShortArticulationEvent, "^"),
658 "tenuto": (musicexp.ShortArticulationEvent, "-"),
659 #"thumb-position": "",
662 "tremolo": musicxml_tremolo_to_lily_event,
663 "trill-mark": "trill",
664 #"triple-tongue": "",
669 articulation_spanners = [ "wavy-line" ]
671 def musicxml_articulation_to_lily_event (mxl_event):
672 # wavy-line elements are treated as trill spanners, not as articulation ornaments
673 if mxl_event.get_name () in articulation_spanners:
674 return musicxml_spanner_to_lily_event (mxl_event)
676 tmp_tp = articulations_dict.get (mxl_event.get_name ())
680 if isinstance (tmp_tp, str):
681 ev = musicexp.ArticulationEvent ()
683 elif isinstance (tmp_tp, tuple):
687 ev = tmp_tp (mxl_event)
689 # Some articulations use the type attribute, other the placement...
691 if hasattr (mxl_event, 'type'):
692 dir = musicxml_direction_to_indicator (mxl_event.type)
693 if hasattr (mxl_event, 'placement'):
694 dir = musicxml_direction_to_indicator (mxl_event.placement)
698 def musicxml_dynamics_to_lily_event (dynentry):
699 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
700 "f", "ff", "fff", "ffff", "fffff", "ffffff",
701 "mp", "mf", "sf", "sfp", "sfpp", "fp",
702 "rf", "rfz", "sfz", "sffz", "fz" )
703 if not dynentry.get_name() in dynamics_available:
705 event = musicexp.DynamicsEvent ()
706 event.type = dynentry.get_name ()
709 # Convert single-color two-byte strings to numbers 0.0 - 1.0
710 def hexcolorval_to_nr (hex_val):
712 v = int (hex_val, 16)
719 def hex_to_color (hex_val):
720 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)
722 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
726 def musicxml_words_to_lily_event (words):
727 event = musicexp.TextEvent ()
728 text = words.get_text ()
729 text = re.sub ('^ *\n? *', '', text)
730 text = re.sub (' *\n? *$', '', text)
733 if hasattr (words, 'default-y'):
734 offset = getattr (words, 'default-y')
736 off = string.atoi (offset)
738 event.force_direction = 1
740 event.force_direction = -1
742 event.force_direction = 0
744 if hasattr (words, 'font-weight'):
745 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
747 event.markup += font_weight
749 if hasattr (words, 'font-size'):
750 size = getattr (words, 'font-size')
752 "xx-small": '\\teeny',
758 "xx-large": '\\bigger\\huge'
761 event.markup += font_size
763 if hasattr (words, 'color'):
764 color = getattr (words, 'color')
765 rgb = hex_to_color (color)
767 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
769 if hasattr (words, 'font-style'):
770 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
772 event.markup += font_style
774 # TODO: How should I best convert the font-family attribute?
776 # TODO: How can I represent the underline, overline and line-through
777 # attributes in Lilypond? Values of these attributes indicate
778 # the number of lines
783 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
785 def musicxml_direction_to_lily (n):
786 # TODO: Handle the <staff> element!
788 dirtype_children = []
789 for dt in n.get_typed_children (musicxml.DirType):
790 dirtype_children += dt.get_all_children ()
792 for entry in dirtype_children:
794 if entry.get_name () == "dynamics":
795 for dynentry in entry.get_all_children ():
796 ev = musicxml_dynamics_to_lily_event (dynentry)
800 if entry.get_name () == "words":
801 ev = musicxml_words_to_lily_event (entry)
805 # octave shifts. pedal marks, hairpins etc. are spanners:
806 if entry.get_name() in direction_spanners:
807 event = musicxml_spanner_to_lily_event (entry)
814 def musicxml_frame_to_lily_event (frame):
815 ev = musicexp.FretEvent ()
816 ev.strings = frame.get_strings ()
817 ev.frets = frame.get_frets ()
818 #offset = frame.get_first_fret () - 1
820 for fn in frame.get_named_children ('frame-note'):
821 fret = fn.get_fret ()
824 el = [ fn.get_string (), fret ]
825 fingering = fn.get_fingering ()
827 el.append (fingering)
828 ev.elements.append (el)
831 barre[0] = el[0] # start string
832 barre[2] = el[1] # fret
834 barre[1] = el[0] # end string
839 def musicxml_harmony_to_lily (n):
841 for f in n.get_named_children ('frame'):
842 ev = musicxml_frame_to_lily_event (f)
848 instrument_drumtype_dict = {
849 'Acoustic Snare Drum': 'acousticsnare',
850 'Side Stick': 'sidestick',
851 'Open Triangle': 'opentriangle',
852 'Mute Triangle': 'mutetriangle',
853 'Tambourine': 'tambourine',
854 'Bass Drum': 'bassdrum',
857 def musicxml_note_to_lily_main_event (n):
861 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
864 pitch = musicxml_pitch_to_lily (mxl_pitch)
865 event = musicexp.NoteEvent()
868 acc = n.get_maybe_exist_named_child ('accidental')
870 # let's not force accs everywhere.
871 event.cautionary = acc.editorial
873 elif n.get_maybe_exist_typed_child (musicxml.Rest):
874 # rests can have display-octave and display-step, which are
875 # treated like an ordinary note pitch
876 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
877 event = musicexp.RestEvent()
878 pitch = musicxml_restdisplay_to_lily (rest)
880 elif n.instrument_name:
881 event = musicexp.NoteEvent ()
882 drum_type = instrument_drumtype_dict.get (n.instrument_name)
884 event.drum_type = drum_type
886 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
887 event.drum_type = 'acousticsnare'
890 n.message ("cannot find suitable event")
892 event.duration = musicxml_duration_to_lily (n)
898 def __init__ (self, here, dest):
902 class LilyPondVoiceBuilder:
905 self.pending_dynamics = []
906 self.end_moment = Rational (0)
907 self.begin_moment = Rational (0)
908 self.pending_multibar = Rational (0)
909 self.ignore_skips = False
911 def _insert_multibar (self):
912 r = musicexp.MultiMeasureRest ()
913 r.duration = musicexp.Duration()
914 r.duration.duration_log = 0
915 r.duration.factor = self.pending_multibar
916 self.elements.append (r)
917 self.begin_moment = self.end_moment
918 self.end_moment = self.begin_moment + self.pending_multibar
919 self.pending_multibar = Rational (0)
921 def add_multibar_rest (self, duration):
922 self.pending_multibar += duration
924 def set_duration (self, duration):
925 self.end_moment = self.begin_moment + duration
926 def current_duration (self):
927 return self.end_moment - self.begin_moment
929 def add_music (self, music, duration):
930 assert isinstance (music, musicexp.Music)
931 if self.pending_multibar > Rational (0):
932 self._insert_multibar ()
934 self.elements.append (music)
935 self.begin_moment = self.end_moment
936 self.set_duration (duration)
938 # Insert all pending dynamics right after the note/rest:
939 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
940 for d in self.pending_dynamics:
942 self.pending_dynamics = []
944 # Insert some music command that does not affect the position in the measure
945 def add_command (self, command):
946 assert isinstance (command, musicexp.Music)
947 if self.pending_multibar > Rational (0):
948 self._insert_multibar ()
949 self.elements.append (command)
950 def add_barline (self, barline):
951 # TODO: Implement merging of default barline and custom bar line
952 self.add_music (barline, Rational (0))
953 def add_partial (self, command):
954 self.ignore_skips = True
955 self.add_command (command)
957 def add_dynamics (self, dynamic):
958 # store the dynamic item(s) until we encounter the next note/rest:
959 self.pending_dynamics.append (dynamic)
961 def add_bar_check (self, number):
962 b = musicexp.BarLine ()
963 b.bar_number = number
966 def jumpto (self, moment):
967 current_end = self.end_moment + self.pending_multibar
968 diff = moment - current_end
970 if diff < Rational (0):
971 error_message ('Negative skip %s' % diff)
974 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
975 skip = musicexp.SkipEvent()
976 skip.duration.duration_log = 0
977 skip.duration.factor = diff
979 evc = musicexp.EventChord ()
980 evc.elements.append (skip)
981 self.add_music (evc, diff)
983 if diff > Rational (0) and moment == 0:
984 self.ignore_skips = False
986 def last_event_chord (self, starting_at):
990 # if the position matches, find the last EventChord, do not cross a bar line!
991 at = len( self.elements ) - 1
993 not isinstance (self.elements[at], musicexp.EventChord) and
994 not isinstance (self.elements[at], musicexp.BarLine)):
999 and isinstance (self.elements[at], musicexp.EventChord)
1000 and self.begin_moment == starting_at):
1001 value = self.elements[at]
1003 self.jumpto (starting_at)
1007 def correct_negative_skip (self, goto):
1008 self.end_moment = goto
1009 self.begin_moment = goto
1010 evc = musicexp.EventChord ()
1011 self.elements.append (evc)
1015 def __init__ (self):
1016 self.voicedata = None
1017 self.ly_voice = None
1018 self.lyrics_dict = {}
1019 self.lyrics_order = []
1021 def musicxml_voice_to_lily_voice (voice):
1025 return_value = VoiceData ()
1026 return_value.voicedata = voice
1028 # Needed for melismata detection (ignore lyrics on those notes!):
1032 ignore_lyrics = False
1034 current_staff = None
1036 # TODO: Make sure that the keys in the dict don't get reordered, since
1037 # we need the correct ordering of the lyrics stanzas! By default,
1038 # a dict will reorder its keys
1039 return_value.lyrics_order = voice.get_lyrics_numbers ()
1040 for k in return_value.lyrics_order:
1043 voice_builder = LilyPondVoiceBuilder()
1045 for n in voice._elements:
1046 if n.get_name () == 'forward':
1048 staff = n.get_maybe_exist_named_child ('staff')
1050 staff = staff.get_text ()
1051 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
1052 voice_builder.add_command (musicexp.StaffChange (staff))
1053 current_staff = staff
1055 if isinstance (n, musicxml.Partial) and n.partial > 0:
1056 a = musicxml_partial_to_lily (n.partial)
1058 voice_builder.add_partial (a)
1061 if isinstance (n, musicxml.Direction):
1062 for a in musicxml_direction_to_lily (n):
1063 if a.wait_for_note ():
1064 voice_builder.add_dynamics (a)
1066 voice_builder.add_command (a)
1069 if isinstance (n, musicxml.Harmony):
1070 for a in musicxml_harmony_to_lily (n):
1071 if a.wait_for_note ():
1072 voice_builder.add_dynamics (a)
1074 voice_builder.add_command (a)
1077 is_chord = n.get_maybe_exist_named_child ('chord')
1080 voice_builder.jumpto (n._when)
1081 except NegativeSkip, neg:
1082 voice_builder.correct_negative_skip (n._when)
1083 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
1085 if isinstance (n, musicxml.Attributes):
1086 if n.is_first () and n._measure_position == Rational (0):
1088 number = int (n.get_parent ().number)
1092 voice_builder.add_bar_check (number)
1094 for a in musicxml_attributes_to_lily (n):
1095 voice_builder.add_command (a)
1098 if isinstance (n, musicxml.Barline):
1099 barlines = musicxml_barline_to_lily (n)
1101 if isinstance (a, musicexp.BarLine):
1102 voice_builder.add_barline (a)
1103 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
1104 voice_builder.add_command (a)
1107 if not n.__class__.__name__ == 'Note':
1108 error_message ('not a Note or Attributes? %s' % n)
1111 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1113 and rest.is_whole_measure ()):
1115 voice_builder.add_multibar_rest (n._duration)
1118 if n.is_first () and n._measure_position == Rational (0):
1120 num = int (n.get_parent ().number)
1124 voice_builder.add_bar_check (num)
1126 main_event = musicxml_note_to_lily_main_event (n)
1127 ignore_lyrics = inside_slur or is_tied or is_chord
1129 if hasattr (main_event, 'drum_type') and main_event.drum_type:
1130 modes_found['drummode'] = True
1133 ev_chord = voice_builder.last_event_chord (n._when)
1135 ev_chord = musicexp.EventChord()
1136 voice_builder.add_music (ev_chord, n._duration)
1138 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
1141 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
1142 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
1144 grace_chord = musicexp.EventChord ()
1145 ev_chord.append_grace (grace_chord)
1146 if hasattr (grace, 'slash'):
1147 # TODO: use grace_type = "appoggiatura" for slurred grace notes
1148 if grace.slash == "yes":
1149 ev_chord.grace_type = "acciaccatura"
1150 elif grace.slash == "no":
1151 ev_chord.grace_type = "grace"
1152 # now that we have inserted the chord into the grace music, insert
1153 # everything into that chord instead of the ev_chord
1154 ev_chord = grace_chord
1155 ev_chord.append (main_event)
1156 ignore_lyrics = True
1158 ev_chord.append (main_event)
1159 # When a note/chord has grace notes (duration==0), the duration of the
1160 # event chord is not yet known, but the event chord was already added
1161 # with duration 0. The following correct this when we hit the real note!
1162 if voice_builder.current_duration () == 0 and n._duration > 0:
1163 voice_builder.set_duration (n._duration)
1165 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
1169 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
1170 # +tied | +slur | +tuplet | glissando | slide |
1171 # ornaments | technical | articulations | dynamics |
1172 # +fermata | arpeggiate | non-arpeggiate |
1173 # accidental-mark | other-notation
1175 if notations.get_tuplet():
1176 tuplet_event = notations.get_tuplet()
1177 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1180 frac = mod.get_fraction ()
1182 tuplet_events.append ((ev_chord, tuplet_event, frac))
1184 slurs = [s for s in notations.get_named_children ('slur')
1185 if s.get_type () in ('start','stop')]
1188 error_message ('more than 1 slur?')
1189 # record the slur status for the next note in the loop
1191 if slurs[0].get_type () == 'start':
1193 elif slurs[0].get_type () == 'stop':
1195 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
1196 ev_chord.append (lily_ev)
1199 mxl_tie = notations.get_tie ()
1200 if mxl_tie and mxl_tie.type == 'start':
1201 ev_chord.append (musicexp.TieEvent ())
1206 fermatas = notations.get_named_children ('fermata')
1208 ev = musicxml_fermata_to_lily_event (a)
1210 ev_chord.append (ev)
1212 arpeggiate = notations.get_named_children ('arpeggiate')
1213 for a in arpeggiate:
1214 ev_chord.append (musicexp.ArpeggioEvent ())
1216 glissandos = notations.get_named_children ('glissando')
1217 for a in glissandos:
1218 ev = musicxml_spanner_to_lily_event (a)
1220 ev_chord.append (ev)
1222 # Articulations can contain the following child elements:
1223 # accent | strong-accent | staccato | tenuto |
1224 # detached-legato | staccatissimo | spiccato |
1225 # scoop | plop | doit | falloff | breath-mark |
1226 # caesura | stress | unstress
1227 # Technical can contain the following child elements:
1228 # up-bow | down-bow | harmonic | open-string |
1229 # thumb-position | fingering | pluck | double-tongue |
1230 # triple-tongue | stopped | snap-pizzicato | fret |
1231 # string | hammer-on | pull-off | bend | tap | heel |
1232 # toe | fingernails | other-technical
1233 # Ornaments can contain the following child elements:
1234 # trill-mark | turn | delayed-turn | inverted-turn |
1235 # shake | wavy-line | mordent | inverted-mordent |
1236 # schleifer | tremolo | other-ornament, accidental-mark
1237 ornaments = notations.get_named_children ('ornaments')
1239 for ch in a.get_named_children ('tremolo'):
1240 ev = musicxml_tremolo_to_lily_event (ch)
1242 ev_chord.append (ev)
1244 ornaments += notations.get_named_children ('articulations')
1245 ornaments += notations.get_named_children ('technical')
1248 for ch in a.get_all_children ():
1249 ev = musicxml_articulation_to_lily_event (ch)
1251 ev_chord.append (ev)
1253 dynamics = notations.get_named_children ('dynamics')
1255 for ch in a.get_all_children ():
1256 ev = musicxml_dynamics_to_lily_event (ch)
1258 ev_chord.append (ev)
1260 # Extract the lyrics
1261 if not rest and not ignore_lyrics:
1262 note_lyrics_processed = []
1263 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1264 for l in note_lyrics_elements:
1265 if l.get_number () < 0:
1266 for k in lyrics.keys ():
1267 lyrics[k].append (l.lyric_to_text ())
1268 note_lyrics_processed.append (k)
1270 lyrics[l.number].append(l.lyric_to_text ())
1271 note_lyrics_processed.append (l.number)
1272 for lnr in lyrics.keys ():
1273 if not lnr in note_lyrics_processed:
1274 lyrics[lnr].append ("\skip4")
1277 mxl_beams = [b for b in n.get_named_children ('beam')
1278 if (b.get_type () in ('begin', 'end')
1279 and b.is_primary ())]
1281 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1283 ev_chord.append (beam_ev)
1286 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1289 frac = mod.get_fraction ()
1291 tuplet_events.append ((ev_chord, tuplet_event, frac))
1293 ## force trailing mm rests to be written out.
1294 voice_builder.add_music (musicexp.EventChord (), Rational (0))
1296 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1297 ly_voice = group_repeats (ly_voice)
1299 seq_music = musicexp.SequentialMusic ()
1301 if 'drummode' in modes_found.keys ():
1302 ## \key <pitch> barfs in drummode.
1303 ly_voice = [e for e in ly_voice
1304 if not isinstance(e, musicexp.KeySignatureChange)]
1306 seq_music.elements = ly_voice
1307 for k in lyrics.keys ():
1308 return_value.lyrics_dict[k] = musicexp.Lyrics ()
1309 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
1312 if len (modes_found) > 1:
1313 error_message ('Too many modes found %s' % modes_found.keys ())
1315 return_value.ly_voice = seq_music
1316 for mode in modes_found.keys ():
1317 v = musicexp.ModeChangingMusicWrapper()
1318 v.element = seq_music
1320 return_value.ly_voice = v
1325 def musicxml_id_to_lily (id):
1326 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1327 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1329 for digit in digits:
1330 d = digits.index (digit)
1331 id = re.sub ('%d' % d, digit, id)
1333 id = re.sub ('[^a-zA-Z]', 'X', id)
1337 def musicxml_pitch_to_lily (mxl_pitch):
1338 p = musicexp.Pitch()
1339 p.alteration = mxl_pitch.get_alteration ()
1340 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1341 p.octave = mxl_pitch.get_octave () - 4
1344 def musicxml_restdisplay_to_lily (mxl_rest):
1346 step = mxl_rest.get_step ()
1348 p = musicexp.Pitch()
1349 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1350 octave = mxl_rest.get_octave ()
1352 p.octave = octave - 4
1355 def voices_in_part (part):
1356 """Return a Name -> Voice dictionary for PART"""
1358 part.extract_voices ()
1359 voice_dict = part.get_voices ()
1363 def voices_in_part_in_parts (parts):
1364 """return a Part -> Name -> Voice dictionary"""
1365 return dict([(p, voices_in_part (p)) for p in parts])
1368 def get_all_voices (parts):
1369 all_voices = voices_in_part_in_parts (parts)
1372 for p, name_voice in all_voices.items ():
1375 for n, v in name_voice.items ():
1376 progress ("Converting to LilyPond expressions...")
1377 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1378 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
1380 all_ly_voices[p] = part_ly_voices
1382 return all_ly_voices
1385 def option_parser ():
1386 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1387 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1389 _ ("""This program is free software. It is covered by the GNU General Public
1390 License and you are welcome to change it and/or distribute copies of it
1391 under certain conditions. Invoke as `%s --warranty' for more
1392 information.""") % 'lilypond'
1394 Copyright (c) 2005--2007 by
1395 Han-Wen Nienhuys <hanwen@xs4all.nl> and
1396 Jan Nieuwenhuizen <janneke@gnu.org>
1398 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1399 p.add_option ('-v', '--verbose',
1400 action="store_true",
1402 help=_ ("be verbose"))
1404 p.add_option ('', '--lxml',
1405 action="store_true",
1408 help=_ ("Use lxml.etree; uses less memory and cpu time."))
1410 p.add_option ('-o', '--output',
1416 help=_ ("set output filename to FILE"))
1417 p.add_option_group ('bugs',
1418 description=(_ ("Report bugs via")
1419 + ''' http://post.gmane.org/post.php'''
1420 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1423 def music_xml_voice_name_to_lily_name (part, name):
1424 str = "Part%sVoice%s" % (part.id, name)
1425 return musicxml_id_to_lily (str)
1427 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1428 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1429 return musicxml_id_to_lily (str)
1431 def print_voice_definitions (printer, part_list, voices):
1433 for (part, nv_dict) in voices.items():
1434 part_dict[part.id] = (part, nv_dict)
1436 for part in part_list:
1437 (p, nv_dict) = part_dict.get (part.id, (None, {}))
1438 #for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1439 for (name, voice) in nv_dict.items ():
1440 k = music_xml_voice_name_to_lily_name (p, name)
1441 printer.dump ('%s = ' % k)
1442 voice.ly_voice.print_ly (printer)
1445 for l in voice.lyrics_order:
1446 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1447 printer.dump ('%s = ' %lname )
1448 voice.lyrics_dict[l].print_ly (printer)
1453 return dict ([(elt,1) for elt in l]).keys ()
1455 # format the information about the staff in the form
1458 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1459 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1463 # raw_voices is of the form [(voicename, lyricsids)*]
1464 def format_staff_info (part, staff_id, raw_voices):
1466 for (v, lyricsids) in raw_voices:
1467 voice_name = music_xml_voice_name_to_lily_name (part, v)
1468 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1470 voices.append ([voice_name, voice_lyrics])
1471 return [staff_id, voices]
1473 def update_score_setup (score_structure, part_list, voices):
1474 part_dict = dict ([(p.id, p) for p in voices.keys ()])
1475 final_part_dict = {}
1477 for part_definition in part_list:
1478 part_name = part_definition.id
1479 part = part_dict.get (part_name)
1481 error_message ('unknown part in part-list: %s' % part_name)
1484 nv_dict = voices.get (part)
1485 staves = reduce (lambda x,y: x+ y,
1486 [voice.voicedata._staves.keys ()
1487 for voice in nv_dict.values ()],
1490 if len (staves) > 1:
1492 staves = uniq_list (staves)
1495 #((music, lyrics), mxlvoice))
1496 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1497 for (voice_name, voice) in nv_dict.items ()
1498 if voice.voicedata._start_staff == s]
1499 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1501 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1502 for (voice_name, voice) in nv_dict.items ()]
1503 staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1504 score_structure.set_part_information (part_name, staves_info)
1506 def print_ly_preamble (printer, filename):
1507 printer.dump_version ()
1508 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1510 def read_musicxml (filename, use_lxml):
1514 tree = lxml.etree.parse (filename)
1515 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1518 from xml.dom import minidom, Node
1520 doc = minidom.parse(filename)
1521 node = doc.documentElement
1522 return musicxml.minidom_demarshal_node (node)
1527 def convert (filename, options):
1528 progress ("Reading MusicXML from %s ..." % filename)
1530 tree = read_musicxml (filename, options.use_lxml)
1532 score_structure = None
1533 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1535 score_structure = extract_score_layout (mxl_pl)
1536 part_list = mxl_pl.get_named_children ("score-part")
1538 # score information is contained in the <work>, <identification> or <movement-title> tags
1539 score_information = extract_score_information (tree)
1540 parts = tree.get_typed_children (musicxml.Part)
1541 voices = get_all_voices (parts)
1542 update_score_setup (score_structure, part_list, voices)
1544 if not options.output_name:
1545 options.output_name = os.path.basename (filename)
1546 options.output_name = os.path.splitext (options.output_name)[0]
1547 elif re.match (".*\.ly", options.output_name):
1548 options.output_name = os.path.splitext (options.output_name)[0]
1551 defs_ly_name = options.output_name + '-defs.ly'
1552 driver_ly_name = options.output_name + '.ly'
1554 printer = musicexp.Output_printer()
1555 progress ("Output to `%s'" % defs_ly_name)
1556 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1558 print_ly_preamble (printer, filename)
1559 score_information.print_ly (printer)
1560 print_voice_definitions (printer, part_list, voices)
1565 progress ("Output to `%s'" % driver_ly_name)
1566 printer = musicexp.Output_printer()
1567 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1568 print_ly_preamble (printer, filename)
1569 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1570 score_structure.print_ly (printer)
1575 def get_existing_filename_with_extension (filename, ext):
1576 if os.path.exists (filename):
1578 newfilename = filename + ".xml"
1579 if os.path.exists (newfilename):
1581 newfilename = filename + "xml"
1582 if os.path.exists (newfilename):
1587 opt_parser = option_parser()
1589 (options, args) = opt_parser.parse_args ()
1591 opt_parser.print_usage()
1594 # Allow the user to leave out the .xml or xml on the filename
1595 filename = get_existing_filename_with_extension (args[0], "xml")
1596 if filename and os.path.exists (filename):
1597 voices = convert (filename, options)
1599 progress ("Unable to find input file %s" % args[0])
1601 if __name__ == '__main__':