9 from gettext import gettext as _
20 from rational import Rational
24 sys.stderr.write (str + '\n')
27 def error_message (str):
28 sys.stderr.write (str + '\n')
31 # score information is contained in the <work>, <identification> or <movement-title> tags
32 # extract those into a hash, indexed by proper lilypond header attributes
33 def extract_score_information (tree):
34 header = musicexp.Header ()
35 def set_if_exists (field, value):
37 header.set_field (field, musicxml.escape_ly_output_string (value))
39 work = tree.get_maybe_exist_named_child ('work')
41 set_if_exists ('title', work.get_work_title ())
42 set_if_exists ('worknumber', work.get_work_number ())
43 set_if_exists ('opus', work.get_opus ())
45 movement_title = tree.get_maybe_exist_named_child ('movement-title')
47 set_if_exists ('title', movement_title.get_text ())
49 identifications = tree.get_named_children ('identification')
50 for ids in identifications:
51 set_if_exists ('copyright', ids.get_rights ())
52 set_if_exists ('composer', ids.get_composer ())
53 set_if_exists ('arranger', ids.get_arranger ())
54 set_if_exists ('editor', ids.get_editor ())
55 set_if_exists ('poet', ids.get_poet ())
57 set_if_exists ('tagline', ids.get_encoding_software ())
58 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
59 set_if_exists ('encodingdate', ids.get_encoding_date ())
60 set_if_exists ('encoder', ids.get_encoding_person ())
61 set_if_exists ('encodingdescription', ids.get_encoding_description ())
66 def extract_score_layout (part_list):
67 layout = musicexp.StaffGroup (None)
68 currentgroups_dict = {}
73 def insert_into_layout (object):
74 if len (currentgroups) > 0:
75 group_to_insert = currentgroups_dict.get (currentgroups [-1], layout)
77 group_to_insert = layout
78 group_to_insert.appendStaff (object)
79 return group_to_insert
81 def read_score_part (el):
82 if not isinstance (el, musicxml.Score_part):
84 staff = musicexp.Staff ()
86 partname = el.get_maybe_exist_named_child ('part-name')
87 # Finale gives unnamed parts the name "MusicXML Part" automatically!
88 if partname and partname.get_text() != "MusicXML Part":
89 staff.instrument_name = partname.get_text ()
90 if el.get_maybe_exist_named_child ('part-abbreviation'):
91 staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
92 # TODO: Read in the MIDI device / instrument
96 parts_groups = part_list.get_all_children ()
97 # the start/end group tags are not necessarily ordered correctly, so
98 # we can't go through the children sequentially!
100 if len (parts_groups) == 1 and isinstance (parts_group[1], musicxml.Score_part):
101 return read_score_part (parts_group[1])
103 for el in parts_groups:
104 if isinstance (el, musicxml.Score_part):
105 staff = read_score_part (el)
106 insert_into_layout (staff)
107 elif isinstance (el, musicxml.Part_group):
108 if el.type == "start":
109 group = musicexp.StaffGroup ()
110 staff_group = insert_into_layout (group)
111 # If we're inserting a nested staffgroup, we need to use InnerStaffGroup
112 if staff_group != layout:
113 group.stafftype = "InnerStaffGroup"
114 if hasattr (el, 'number'):
117 currentgroups_dict[id] = group
118 currentgroups.append (id)
119 if el.get_maybe_exist_named_child ('group-name'):
120 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
121 if el.get_maybe_exist_named_child ('group-abbreviation'):
122 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
123 if el.get_maybe_exist_named_child ('group-symbol'):
124 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
125 if el.get_maybe_exist_named_child ('group-barline'):
126 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
128 elif el.type == "stop":
129 # end the part-group, i.e. simply remove it from the lists
130 if hasattr (el, 'number'):
132 elif len (currentgroups) > 0:
135 del currentgroups_dict[pid]
136 currentgroups.remove (pid)
141 def musicxml_duration_to_lily (mxl_note):
142 d = musicexp.Duration ()
143 # if the note has no Type child, then that method spits out a warning and
144 # returns 0, i.e. a whole note
145 d.duration_log = mxl_note.get_duration_log ()
147 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
148 # Grace notes by specification have duration 0, so no time modification
149 # factor is possible. It even messes up the output with *0/1
150 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
151 d.factor = mxl_note._duration / d.get_length ()
155 def rational_to_lily_duration (rational_len):
156 d = musicexp.Duration ()
157 d.duration_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (rational_len.denominator (), -1)
158 d.factor = Rational (rational_len.numerator ())
159 if d.duration_log < 0:
160 error_message ("Encountered rational duration with denominator %s, "
161 "unable to convert to lilypond duration" %
162 rational_len.denominator ())
163 # TODO: Test the above error message
168 def musicxml_partial_to_lily (partial_len):
170 p = musicexp.Partial ()
171 p.partial = rational_to_lily_duration (partial_len)
176 # Detect repeats and alternative endings in the chord event list (music_list)
177 # and convert them to the corresponding musicexp objects, containing nested
179 def group_repeats (music_list):
180 repeat_replaced = True
183 # Walk through the list of expressions, looking for repeat structure
184 # (repeat start/end, corresponding endings). If we find one, try to find the
185 # last event of the repeat, replace the whole structure and start over again.
186 # For nested repeats, as soon as we encounter another starting repeat bar,
187 # treat that one first, and start over for the outer repeat.
188 while repeat_replaced and i<10:
190 repeat_start = -1 # position of repeat start / end
191 repeat_end = -1 # position of repeat start / end
193 ending_start = -1 # position of current ending start
194 endings = [] # list of already finished endings
196 repeat_replaced = False
198 while pos < len (music_list) and not repeat_replaced:
200 repeat_finished = False
201 if isinstance (e, RepeatMarker):
202 if not repeat_times and e.times:
203 repeat_times = e.times
204 if e.direction == -1:
206 repeat_finished = True
212 elif e.direction == 1:
218 elif isinstance (e, EndingMarker):
219 if e.direction == -1:
224 elif e.direction == 1:
227 endings.append ([ending_start, pos])
230 elif not isinstance (e, musicexp.BarLine):
231 # As soon as we encounter an element when repeat start and end
232 # is set and we are not inside an alternative ending,
233 # this whole repeat structure is finished => replace it
234 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
235 repeat_finished = True
238 # We found the whole structure replace it!
239 r = musicexp.RepeatedMusic ()
240 if repeat_times <= 0:
242 r.repeat_count = repeat_times
243 # don't erase the first element for "implicit" repeats (i.e. no
244 # starting repeat bars at the very beginning)
245 start = repeat_start+1
246 if repeat_start == music_start:
248 r.set_music (music_list[start:repeat_end])
249 for (start, end) in endings:
250 s = musicexp.SequentialMusic ()
251 s.elements = music_list[start+1:end]
253 del music_list[repeat_start:final_marker+1]
254 music_list.insert (repeat_start, r)
255 repeat_replaced = True
257 # TODO: Implement repeats until the end without explicit ending bar
262 def group_tuplets (music_list, events):
265 """Collect Musics from
266 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
273 for (ev_chord, tuplet_elt, fraction) in events:
274 while (j < len (music_list)):
275 if music_list[j] == ev_chord:
278 if tuplet_elt.type == 'start':
279 indices.append ((j, None, fraction))
280 elif tuplet_elt.type == 'stop':
281 indices[-1] = (indices[-1][0], j, indices[-1][2])
285 for (i1, i2, frac) in indices:
289 new_list.extend (music_list[last:i1])
290 seq = musicexp.SequentialMusic ()
292 seq.elements = music_list[i1:last]
294 tsm = musicexp.TimeScaledMusic ()
297 tsm.numerator = frac[0]
298 tsm.denominator = frac[1]
300 new_list.append (tsm)
302 new_list.extend (music_list[last:])
306 def musicxml_clef_to_lily (attributes):
307 change = musicexp.ClefChange ()
308 (change.type, change.position, change.octave) = attributes.get_clef_information ()
311 def musicxml_time_to_lily (attributes):
312 (beats, type) = attributes.get_time_signature ()
314 change = musicexp.TimeSignatureChange()
315 change.fraction = (beats, type)
319 def musicxml_key_to_lily (attributes):
320 start_pitch = musicexp.Pitch ()
321 (fifths, mode) = attributes.get_key_signature ()
328 start_pitch.alteration = a
330 error_message ('unknown mode %s' % mode)
332 fifth = musicexp.Pitch()
339 for x in range (fifths):
340 start_pitch = start_pitch.transposed (fifth)
342 start_pitch.octave = 0
344 change = musicexp.KeySignatureChange()
346 change.tonic = start_pitch
349 def musicxml_attributes_to_lily (attrs):
352 'clef': musicxml_clef_to_lily,
353 'time': musicxml_time_to_lily,
354 'key': musicxml_key_to_lily
356 for (k, func) in attr_dispatch.items ():
357 children = attrs.get_named_children (k)
359 elts.append (func (attrs))
363 class Marker (musicexp.Music):
367 def print_ly (self, printer):
368 sys.stderr.write ("Encountered unprocessed marker %s\n" % self)
370 def ly_expression (self):
372 class RepeatMarker (Marker):
374 Marker.__init__ (self)
376 class EndingMarker (Marker):
379 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
380 # and to RepeatMarker and EndingMarker objects for repeat and
381 # alternatives start/stops
382 def musicxml_barline_to_lily (barline):
383 # retval contains all possible markers in the order:
384 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
386 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
387 repeat_element = barline.get_maybe_exist_named_child ("repeat")
388 ending_element = barline.get_maybe_exist_named_child ("ending")
392 bartype = bartype_element.get_text ()
394 if repeat_element and hasattr (repeat_element, 'direction'):
395 repeat = RepeatMarker ()
396 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
398 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
399 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
401 if hasattr (repeat_element, 'times'):
403 repeat.times = int (repeat_element.times)
406 repeat.event = barline
407 if repeat.direction == -1:
412 if ending_element and hasattr (ending_element, 'type'):
413 ending = EndingMarker ()
414 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
415 ending.event = barline
416 if ending.direction == -1:
422 b = musicexp.BarLine ()
426 return retval.values ()
428 spanner_event_dict = {
429 'slur' : musicexp.SlurEvent,
430 'beam' : musicexp.BeamEvent,
431 'glissando' : musicexp.GlissandoEvent,
432 'pedal' : musicexp.PedalEvent,
433 'wavy-line' : musicexp.TrillSpanEvent,
434 'octave-shift' : musicexp.OctaveShiftEvent,
435 'wedge' : musicexp.HairpinEvent
437 spanner_type_dict = {
450 def musicxml_spanner_to_lily_event (mxl_event):
453 name = mxl_event.get_name()
454 func = spanner_event_dict.get (name)
458 error_message ('unknown span event %s' % mxl_event)
461 type = mxl_event.get_type ()
462 span_direction = spanner_type_dict.get (type)
463 # really check for None, because some types will be translated to 0, which
464 # would otherwise also lead to the unknown span warning
465 if span_direction != None:
466 ev.span_direction = span_direction
468 error_message ('unknown span type %s for %s' % (type, name))
470 ev.set_span_type (type)
471 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
473 # assign the size, which is used for octave-shift, etc.
474 ev.size = mxl_event.get_size ()
478 def musicxml_direction_to_indicator (direction):
479 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
481 def musicxml_fermata_to_lily_event (mxl_event):
482 ev = musicexp.ArticulationEvent ()
484 if hasattr (mxl_event, 'type'):
485 dir = musicxml_direction_to_indicator (mxl_event.type)
487 ev.force_direction = dir
490 def musicxml_tremolo_to_lily_event (mxl_event):
491 ev = musicexp.TremoloEvent ()
492 ev.bars = mxl_event.get_text ()
495 def musicxml_bend_to_lily_event (mxl_event):
496 ev = musicexp.BendEvent ()
497 ev.alter = mxl_event.bend_alter ()
501 def musicxml_fingering_event (mxl_event):
502 ev = musicexp.ShortArticulationEvent ()
503 ev.type = mxl_event.get_text ()
506 def musicxml_accidental_mark (mxl_event):
507 ev = musicexp.MarkupEvent ()
508 contents = { "sharp": "\\sharp",
509 "natural": "\\natural",
511 "double-sharp": "\\doublesharp",
512 "sharp-sharp": "\\sharp\\sharp",
513 "flat-flat": "\\flat\\flat",
514 "flat-flat": "\\doubleflat",
515 "natural-sharp": "\\natural\\sharp",
516 "natural-flat": "\\natural\\flat",
517 "quarter-flat": "\\semiflat",
518 "quarter-sharp": "\\semisharp",
519 "three-quarters-flat": "\\sesquiflat",
520 "three-quarters-sharp": "\\sesquisharp",
521 }.get (mxl_event.get_text ())
523 ev.contents = contents
528 # translate articulations, ornaments and other notations into ArticulationEvents
530 # -) string (ArticulationEvent with that name)
531 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
532 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
533 # TODO: Some translations are missing!
534 articulations_dict = {
535 "accent": (musicexp.ShortArticulationEvent, ">"),
536 "accidental-mark": musicxml_accidental_mark,
537 "bend": musicxml_bend_to_lily_event,
538 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
539 #"caesura": "caesura",
540 #"delayed-turn": "?",
541 #"detached-legato": "",
543 #"double-tongue": "",
544 "down-bow": "downbow",
546 "fingering": musicxml_fingering_event,
550 "harmonic": "flageolet",
552 "inverted-mordent": "prall",
553 "inverted-turn": "reverseturn",
554 "mordent": "mordent",
558 #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
563 #"snap-pizzicato": "",
565 "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
566 "staccato": (musicexp.ShortArticulationEvent, "."),
567 "stopped": (musicexp.ShortArticulationEvent, "+"),
570 "strong-accent": (musicexp.ShortArticulationEvent, "^"),
572 "tenuto": (musicexp.ShortArticulationEvent, "-"),
573 #"thumb-position": "",
576 "tremolo": musicxml_tremolo_to_lily_event,
577 "trill-mark": "trill",
578 #"triple-tongue": "",
583 articulation_spanners = [ "wavy-line" ]
585 def musicxml_articulation_to_lily_event (mxl_event):
586 # wavy-line elements are treated as trill spanners, not as articulation ornaments
587 if mxl_event.get_name () in articulation_spanners:
588 return musicxml_spanner_to_lily_event (mxl_event)
590 tmp_tp = articulations_dict.get (mxl_event.get_name ())
594 if isinstance (tmp_tp, str):
595 ev = musicexp.ArticulationEvent ()
597 elif isinstance (tmp_tp, tuple):
601 ev = tmp_tp (mxl_event)
603 # Some articulations use the type attribute, other the placement...
605 if hasattr (mxl_event, 'type'):
606 dir = musicxml_direction_to_indicator (mxl_event.type)
607 if hasattr (mxl_event, 'placement'):
608 dir = musicxml_direction_to_indicator (mxl_event.placement)
612 def musicxml_dynamics_to_lily_event (dynentry):
613 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
614 "f", "ff", "fff", "ffff", "fffff", "ffffff",
615 "mp", "mf", "sf", "sfp", "sfpp", "fp",
616 "rf", "rfz", "sfz", "sffz", "fz" )
617 if not dynentry.get_name() in dynamics_available:
619 event = musicexp.DynamicsEvent ()
620 event.type = dynentry.get_name ()
623 def musicxml_words_to_lily_event (words):
624 event = musicexp.TextEvent ()
625 text = words.get_text ()
626 text = re.sub ('^ *\n? *', '', text)
627 text = re.sub (' *\n? *$', '', text)
629 if hasattr (words, 'default-y'):
630 if getattr (words, 'default-y') > 0:
631 event.force_direction = 1
633 event.force_direction = -1
635 if hasattr (words, 'font-weight'):
636 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
638 event.markup += font_weight
639 if hasattr (words, 'font-size'):
640 font_size = { "xx-small": '\\smaller\\smaller\\smaller', "x-small": '\\smaller\\smaller', "small": '\\smaller', "medium": '', "large": '\\large', "x-large": '\\large\\large', "xx-large": '\\large\\large\\large' }.get (getattr (words, 'font-size'), '')
642 event.markup += font_size
643 #TODO: Convert the other attributes defined in %text-formatting in common.mod:
646 event.text = text #re.replace (text, "^ *\n? *(.*) *\n? *", "\1")
650 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
652 def musicxml_direction_to_lily (n):
653 # TODO: Handle the <staff> element!
655 dirtype_children = []
656 for dt in n.get_typed_children (musicxml.DirType):
657 dirtype_children += dt.get_all_children ()
659 for entry in dirtype_children:
661 if entry.get_name () == "dynamics":
662 for dynentry in entry.get_all_children ():
663 ev = musicxml_dynamics_to_lily_event (dynentry)
667 if entry.get_name () == "words":
668 ev = musicxml_words_to_lily_event (entry)
672 # octave shifts. pedal marks, hairpins etc. are spanners:
673 if entry.get_name() in direction_spanners:
674 event = musicxml_spanner_to_lily_event (entry)
681 instrument_drumtype_dict = {
682 'Acoustic Snare Drum': 'acousticsnare',
683 'Side Stick': 'sidestick',
684 'Open Triangle': 'opentriangle',
685 'Mute Triangle': 'mutetriangle',
686 'Tambourine': 'tambourine',
687 'Bass Drum': 'bassdrum',
690 def musicxml_note_to_lily_main_event (n):
694 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
697 pitch = musicxml_pitch_to_lily (mxl_pitch)
698 event = musicexp.NoteEvent()
701 acc = n.get_maybe_exist_named_child ('accidental')
703 # let's not force accs everywhere.
704 event.cautionary = acc.editorial
706 elif n.get_maybe_exist_typed_child (musicxml.Rest):
707 # rests can have display-octave and display-step, which are
708 # treated like an ordinary note pitch
709 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
710 event = musicexp.RestEvent()
711 pitch = musicxml_restdisplay_to_lily (rest)
713 elif n.instrument_name:
714 event = musicexp.NoteEvent ()
715 drum_type = instrument_drumtype_dict.get (n.instrument_name)
717 event.drum_type = drum_type
719 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
720 event.drum_type = 'acousticsnare'
723 n.message ("cannot find suitable event")
725 event.duration = musicxml_duration_to_lily (n)
731 def __init__ (self, here, dest):
735 class LilyPondVoiceBuilder:
738 self.pending_dynamics = []
739 self.end_moment = Rational (0)
740 self.begin_moment = Rational (0)
741 self.pending_multibar = Rational (0)
742 self.ignore_skips = False
744 def _insert_multibar (self):
745 r = musicexp.MultiMeasureRest ()
746 r.duration = musicexp.Duration()
747 r.duration.duration_log = 0
748 r.duration.factor = self.pending_multibar
749 self.elements.append (r)
750 self.begin_moment = self.end_moment
751 self.end_moment = self.begin_moment + self.pending_multibar
752 self.pending_multibar = Rational (0)
754 def add_multibar_rest (self, duration):
755 self.pending_multibar += duration
757 def set_duration (self, duration):
758 self.end_moment = self.begin_moment + duration
759 def current_duration (self):
760 return self.end_moment - self.begin_moment
762 def add_music (self, music, duration):
763 assert isinstance (music, musicexp.Music)
764 if self.pending_multibar > Rational (0):
765 self._insert_multibar ()
767 self.elements.append (music)
768 self.begin_moment = self.end_moment
769 self.set_duration (duration)
771 # Insert all pending dynamics right after the note/rest:
772 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
773 for d in self.pending_dynamics:
775 self.pending_dynamics = []
777 # Insert some music command that does not affect the position in the measure
778 def add_command (self, command):
779 assert isinstance (command, musicexp.Music)
780 if self.pending_multibar > Rational (0):
781 self._insert_multibar ()
782 self.elements.append (command)
783 def add_barline (self, barline):
784 # TODO: Implement merging of default barline and custom bar line
785 self.add_music (barline, Rational (0))
786 def add_partial (self, command):
787 self.ignore_skips = True
788 self.add_command (command)
790 def add_dynamics (self, dynamic):
791 # store the dynamic item(s) until we encounter the next note/rest:
792 self.pending_dynamics.append (dynamic)
794 def add_bar_check (self, number):
795 b = musicexp.BarLine ()
796 b.bar_number = number
799 def jumpto (self, moment):
800 current_end = self.end_moment + self.pending_multibar
801 diff = moment - current_end
803 if diff < Rational (0):
804 error_message ('Negative skip %s' % diff)
807 if diff > Rational (0) and not self.ignore_skips:
808 skip = musicexp.SkipEvent()
809 skip.duration.duration_log = 0
810 skip.duration.factor = diff
812 evc = musicexp.EventChord ()
813 evc.elements.append (skip)
814 self.add_music (evc, diff)
816 if diff > Rational (0) and moment == 0:
817 self.ignore_skips = False
819 def last_event_chord (self, starting_at):
823 # if the position matches, find the last EventChord, do not cross a bar line!
824 at = len( self.elements ) - 1
826 not isinstance (self.elements[at], musicexp.EventChord) and
827 not isinstance (self.elements[at], musicexp.BarLine)):
832 and isinstance (self.elements[at], musicexp.EventChord)
833 and self.begin_moment == starting_at):
834 value = self.elements[at]
836 self.jumpto (starting_at)
840 def correct_negative_skip (self, goto):
841 self.end_moment = goto
842 self.begin_moment = goto
843 evc = musicexp.EventChord ()
844 self.elements.append (evc)
846 def musicxml_voice_to_lily_voice (voice):
851 # TODO: Make sure that the keys in the dict don't get reordered, since
852 # we need the correct ordering of the lyrics stanzas! By default,
853 # a dict will reorder its keys
854 for k in voice.get_lyrics_numbers ():
857 voice_builder = LilyPondVoiceBuilder()
859 for n in voice._elements:
860 if n.get_name () == 'forward':
863 if isinstance (n, musicxml.Partial) and n.partial > 0:
864 a = musicxml_partial_to_lily (n.partial)
866 voice_builder.add_partial (a)
869 if isinstance (n, musicxml.Direction):
870 for a in musicxml_direction_to_lily (n):
871 if a.wait_for_note ():
872 voice_builder.add_dynamics (a)
874 voice_builder.add_command (a)
877 if not n.get_maybe_exist_named_child ('chord'):
879 voice_builder.jumpto (n._when)
880 except NegativeSkip, neg:
881 voice_builder.correct_negative_skip (n._when)
882 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
884 if isinstance (n, musicxml.Attributes):
885 if n.is_first () and n._measure_position == Rational (0):
887 number = int (n.get_parent ().number)
891 voice_builder.add_bar_check (number)
893 for a in musicxml_attributes_to_lily (n):
894 voice_builder.add_command (a)
897 if isinstance (n, musicxml.Barline):
898 barlines = musicxml_barline_to_lily (n)
900 if isinstance (a, musicexp.BarLine):
901 voice_builder.add_barline (a)
902 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
903 voice_builder.add_command (a)
906 if not n.__class__.__name__ == 'Note':
907 error_message ('not a Note or Attributes? %s' % n)
910 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
912 and rest.is_whole_measure ()):
914 voice_builder.add_multibar_rest (n._duration)
917 if n.is_first () and n._measure_position == Rational (0):
919 num = int (n.get_parent ().number)
923 voice_builder.add_bar_check (num)
925 main_event = musicxml_note_to_lily_main_event (n)
927 if hasattr (main_event, 'drum_type') and main_event.drum_type:
928 modes_found['drummode'] = True
931 ev_chord = voice_builder.last_event_chord (n._when)
933 ev_chord = musicexp.EventChord()
934 voice_builder.add_music (ev_chord, n._duration)
936 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
939 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
940 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
942 grace_chord = musicexp.EventChord ()
943 ev_chord.append_grace (grace_chord)
944 if hasattr (grace, 'slash'):
945 # TODO: use grace_type = "appoggiatura" for slurred grace notes
946 if grace.slash == "yes":
947 ev_chord.grace_type = "acciaccatura"
948 elif grace.slash == "no":
949 ev_chord.grace_type = "grace"
950 # now that we have inserted the chord into the grace music, insert
951 # everything into that chord instead of the ev_chord
952 ev_chord = grace_chord
953 ev_chord.append (main_event)
955 ev_chord.append (main_event)
956 # When a note/chord has grace notes (duration==0), the duration of the
957 # event chord is not yet known, but the event chord was already added
958 # with duration 0. The following correct this when we hit the real note!
959 if voice_builder.current_duration () == 0 and n._duration > 0:
960 voice_builder.set_duration (n._duration)
962 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
966 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
967 # +tied | +slur | +tuplet | glissando | slide |
968 # ornaments | technical | articulations | dynamics |
969 # +fermata | arpeggiate | non-arpeggiate |
970 # accidental-mark | other-notation
972 if notations.get_tuplet():
973 tuplet_event = notations.get_tuplet()
974 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
977 frac = mod.get_fraction ()
979 tuplet_events.append ((ev_chord, tuplet_event, frac))
981 slurs = [s for s in notations.get_named_children ('slur')
982 if s.get_type () in ('start','stop')]
985 error_message ('more than 1 slur?')
987 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
988 ev_chord.append (lily_ev)
990 mxl_tie = notations.get_tie ()
991 if mxl_tie and mxl_tie.type == 'start':
992 ev_chord.append (musicexp.TieEvent ())
994 fermatas = notations.get_named_children ('fermata')
996 ev = musicxml_fermata_to_lily_event (a)
1000 arpeggiate = notations.get_named_children ('arpeggiate')
1001 for a in arpeggiate:
1002 ev_chord.append (musicexp.ArpeggioEvent ())
1004 glissandos = notations.get_named_children ('glissando')
1005 for a in glissandos:
1006 ev = musicxml_spanner_to_lily_event (a)
1008 ev_chord.append (ev)
1010 # Articulations can contain the following child elements:
1011 # accent | strong-accent | staccato | tenuto |
1012 # detached-legato | staccatissimo | spiccato |
1013 # scoop | plop | doit | falloff | breath-mark |
1014 # caesura | stress | unstress
1015 # Technical can contain the following child elements:
1016 # up-bow | down-bow | harmonic | open-string |
1017 # thumb-position | fingering | pluck | double-tongue |
1018 # triple-tongue | stopped | snap-pizzicato | fret |
1019 # string | hammer-on | pull-off | bend | tap | heel |
1020 # toe | fingernails | other-technical
1021 # Ornaments can contain the following child elements:
1022 # trill-mark | turn | delayed-turn | inverted-turn |
1023 # shake | wavy-line | mordent | inverted-mordent |
1024 # schleifer | tremolo | other-ornament, accidental-mark
1025 ornaments = notations.get_named_children ('ornaments')
1027 for ch in a.get_named_children ('tremolo'):
1028 ev = musicxml_tremolo_to_lily_event (ch)
1030 ev_chord.append (ev)
1032 ornaments += notations.get_named_children ('articulations')
1033 ornaments += notations.get_named_children ('technical')
1036 for ch in a.get_all_children ():
1037 ev = musicxml_articulation_to_lily_event (ch)
1039 ev_chord.append (ev)
1041 dynamics = notations.get_named_children ('dynamics')
1043 for ch in a.get_all_children ():
1044 ev = musicxml_dynamics_to_lily_event (ch)
1046 ev_chord.append (ev)
1048 # Extract the lyrics
1050 note_lyrics_processed = []
1051 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1052 for l in note_lyrics_elements:
1053 if l.get_number () < 0:
1054 for k in lyrics.keys ():
1055 lyrics[k].append (l.lyric_to_text ())
1056 note_lyrics_processed.append (k)
1058 lyrics[l.number].append(l.lyric_to_text ())
1059 note_lyrics_processed.append (l.number)
1060 for lnr in lyrics.keys ():
1061 if not lnr in note_lyrics_processed:
1062 lyrics[lnr].append ("\skip4")
1065 mxl_beams = [b for b in n.get_named_children ('beam')
1066 if (b.get_type () in ('begin', 'end')
1067 and b.is_primary ())]
1069 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1071 ev_chord.append (beam_ev)
1074 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1077 frac = mod.get_fraction ()
1079 tuplet_events.append ((ev_chord, tuplet_event, frac))
1081 ## force trailing mm rests to be written out.
1082 voice_builder.add_music (musicexp.EventChord (), Rational (0))
1084 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1085 ly_voice = group_repeats (ly_voice)
1087 seq_music = musicexp.SequentialMusic ()
1089 if 'drummode' in modes_found.keys ():
1090 ## \key <pitch> barfs in drummode.
1091 ly_voice = [e for e in ly_voice
1092 if not isinstance(e, musicexp.KeySignatureChange)]
1094 seq_music.elements = ly_voice
1096 for k in lyrics.keys ():
1097 lyrics_dict[k] = musicexp.Lyrics ()
1098 lyrics_dict[k].lyrics_syllables = lyrics[k]
1101 if len (modes_found) > 1:
1102 error_message ('Too many modes found %s' % modes_found.keys ())
1104 return_value = seq_music
1105 for mode in modes_found.keys ():
1106 v = musicexp.ModeChangingMusicWrapper()
1107 v.element = return_value
1111 return (return_value, lyrics_dict)
1114 def musicxml_id_to_lily (id):
1115 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1116 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1118 for digit in digits:
1119 d = digits.index (digit)
1120 id = re.sub ('%d' % d, digit, id)
1122 id = re.sub ('[^a-zA-Z]', 'X', id)
1126 def musicxml_pitch_to_lily (mxl_pitch):
1127 p = musicexp.Pitch()
1128 p.alteration = mxl_pitch.get_alteration ()
1129 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1130 p.octave = mxl_pitch.get_octave () - 4
1133 def musicxml_restdisplay_to_lily (mxl_rest):
1135 step = mxl_rest.get_step ()
1137 p = musicexp.Pitch()
1138 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1139 octave = mxl_rest.get_octave ()
1141 p.octave = octave - 4
1144 def voices_in_part (part):
1145 """Return a Name -> Voice dictionary for PART"""
1147 part.extract_voices ()
1148 voice_dict = part.get_voices ()
1152 def voices_in_part_in_parts (parts):
1153 """return a Part -> Name -> Voice dictionary"""
1154 return dict([(p, voices_in_part (p)) for p in parts])
1157 def get_all_voices (parts):
1158 all_voices = voices_in_part_in_parts (parts)
1161 for p, name_voice in all_voices.items ():
1164 for n, v in name_voice.items ():
1165 progress ("Converting to LilyPond expressions...")
1166 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1167 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
1169 all_ly_voices[p] = part_ly_voices
1171 return all_ly_voices
1174 def option_parser ():
1175 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1176 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1178 _ ("""This program is free software. It is covered by the GNU General Public
1179 License and you are welcome to change it and/or distribute copies of it
1180 under certain conditions. Invoke as `%s --warranty' for more
1181 information.""") % 'lilypond'
1183 Copyright (c) 2005--2007 by
1184 Han-Wen Nienhuys <hanwen@xs4all.nl> and
1185 Jan Nieuwenhuizen <janneke@gnu.org>
1187 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1188 p.add_option ('-v', '--verbose',
1189 action="store_true",
1191 help=_ ("be verbose"))
1193 p.add_option ('', '--lxml',
1194 action="store_true",
1197 help=_ ("Use lxml.etree; uses less memory and cpu time."))
1199 p.add_option ('-o', '--output',
1205 help=_ ("set output filename to FILE"))
1206 p.add_option_group ('bugs',
1207 description=(_ ("Report bugs via")
1208 + ''' http://post.gmane.org/post.php'''
1209 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1212 def music_xml_voice_name_to_lily_name (part, name):
1213 str = "Part%sVoice%s" % (part.id, name)
1214 return musicxml_id_to_lily (str)
1216 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1217 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1218 return musicxml_id_to_lily (str)
1220 def print_voice_definitions (printer, part_list, voices):
1222 for (part, nv_dict) in voices.items():
1223 part_dict[part.id] = (part, nv_dict)
1225 for part in part_list:
1226 (p, nv_dict) = part_dict.get (part.id, (None, {}))
1227 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1228 k = music_xml_voice_name_to_lily_name (p, name)
1229 printer.dump ('%s = ' % k)
1230 voice.print_ly (printer)
1233 for l in lyrics.keys ():
1234 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1235 printer.dump ('%s = ' %lname )
1236 lyrics[l].print_ly (printer)
1241 return dict ([(elt,1) for elt in l]).keys ()
1243 # format the information about the staff in the form
1246 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1247 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1251 # raw_voices is of the form [(voicename, lyrics)*]
1252 def format_staff_info (part, staff_id, raw_voices):
1254 for (v, lyrics) in raw_voices:
1255 voice_name = music_xml_voice_name_to_lily_name (part, v)
1256 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1257 for l in lyrics.keys ()]
1258 voices.append ([voice_name, voice_lyrics])
1259 return [staff_id, voices]
1261 def update_score_setup (score_structure, part_list, voices):
1262 part_dict = dict ([(p.id, p) for p in voices.keys ()])
1263 final_part_dict = {}
1265 for part_definition in part_list:
1266 part_name = part_definition.id
1267 part = part_dict.get (part_name)
1269 error_message ('unknown part in part-list: %s' % part_name)
1272 nv_dict = voices.get (part)
1273 staves = reduce (lambda x,y: x+ y,
1274 [mxlvoice._staves.keys ()
1275 for (v, mxlvoice) in nv_dict.values ()],
1278 if len (staves) > 1:
1280 staves = uniq_list (staves)
1283 thisstaff_raw_voices = [(voice_name, lyrics)
1284 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1285 if mxlvoice._start_staff == s]
1286 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1288 thisstaff_raw_voices = [(voice_name, lyrics)
1289 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1290 staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1291 score_structure.setPartInformation (part_name, staves_info)
1293 def print_ly_preamble (printer, filename):
1294 printer.dump_version ()
1295 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1297 def read_musicxml (filename, use_lxml):
1301 tree = lxml.etree.parse (filename)
1302 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1305 from xml.dom import minidom, Node
1307 doc = minidom.parse(filename)
1308 node = doc.documentElement
1309 return musicxml.minidom_demarshal_node (node)
1314 def convert (filename, options):
1315 progress ("Reading MusicXML from %s ..." % filename)
1317 tree = read_musicxml (filename, options.use_lxml)
1319 score_structure = None
1320 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1322 score_structure = extract_score_layout (mxl_pl)
1323 part_list = mxl_pl.get_named_children ("score-part")
1325 # score information is contained in the <work>, <identification> or <movement-title> tags
1326 score_information = extract_score_information (tree)
1327 parts = tree.get_typed_children (musicxml.Part)
1328 voices = get_all_voices (parts)
1329 update_score_setup (score_structure, part_list, voices)
1331 if not options.output_name:
1332 options.output_name = os.path.basename (filename)
1333 options.output_name = os.path.splitext (options.output_name)[0]
1334 elif re.match (".*\.ly", options.output_name):
1335 options.output_name = os.path.splitext (options.output_name)[0]
1338 defs_ly_name = options.output_name + '-defs.ly'
1339 driver_ly_name = options.output_name + '.ly'
1341 printer = musicexp.Output_printer()
1342 progress ("Output to `%s'" % defs_ly_name)
1343 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1345 print_ly_preamble (printer, filename)
1346 score_information.print_ly (printer)
1347 print_voice_definitions (printer, part_list, voices)
1352 progress ("Output to `%s'" % driver_ly_name)
1353 printer = musicexp.Output_printer()
1354 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1355 print_ly_preamble (printer, filename)
1356 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1357 score_structure.print_ly (printer)
1362 def get_existing_filename_with_extension (filename, ext):
1363 if os.path.exists (filename):
1365 newfilename = filename + ".xml"
1366 if os.path.exists (newfilename):
1368 newfilename = filename + "xml"
1369 if os.path.exists (newfilename):
1374 opt_parser = option_parser()
1376 (options, args) = opt_parser.parse_args ()
1378 opt_parser.print_usage()
1381 # Allow the user to leave out the .xml or xml on the filename
1382 filename = get_existing_filename_with_extension (args[0], "xml")
1383 if filename and os.path.exists (filename):
1384 voices = convert (filename, options)
1386 progress ("Unable to find input file %s" % args[0])
1388 if __name__ == '__main__':