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 def group_tuplets (music_list, events):
179 """Collect Musics from
180 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
187 for (ev_chord, tuplet_elt, fraction) in events:
188 while (j < len (music_list)):
189 if music_list[j] == ev_chord:
192 if tuplet_elt.type == 'start':
193 indices.append ((j, None, fraction))
194 elif tuplet_elt.type == 'stop':
195 indices[-1] = (indices[-1][0], j, indices[-1][2])
199 for (i1, i2, frac) in indices:
203 new_list.extend (music_list[last:i1])
204 seq = musicexp.SequentialMusic ()
206 seq.elements = music_list[i1:last]
208 tsm = musicexp.TimeScaledMusic ()
211 tsm.numerator = frac[0]
212 tsm.denominator = frac[1]
214 new_list.append (tsm)
216 new_list.extend (music_list[last:])
220 def musicxml_clef_to_lily (attributes):
221 change = musicexp.ClefChange ()
222 (change.type, change.position, change.octave) = attributes.get_clef_information ()
225 def musicxml_time_to_lily (attributes):
226 (beats, type) = attributes.get_time_signature ()
228 change = musicexp.TimeSignatureChange()
229 change.fraction = (beats, type)
233 def musicxml_key_to_lily (attributes):
234 start_pitch = musicexp.Pitch ()
235 (fifths, mode) = attributes.get_key_signature ()
242 start_pitch.alteration = a
244 error_message ('unknown mode %s' % mode)
246 fifth = musicexp.Pitch()
253 for x in range (fifths):
254 start_pitch = start_pitch.transposed (fifth)
256 start_pitch.octave = 0
258 change = musicexp.KeySignatureChange()
260 change.tonic = start_pitch
263 def musicxml_attributes_to_lily (attrs):
266 'clef': musicxml_clef_to_lily,
267 'time': musicxml_time_to_lily,
268 'key': musicxml_key_to_lily
270 for (k, func) in attr_dispatch.items ():
271 children = attrs.get_named_children (k)
273 elts.append (func (attrs))
277 spanner_event_dict = {
278 'slur' : musicexp.SlurEvent,
279 'beam' : musicexp.BeamEvent,
280 'glissando' : musicexp.GlissandoEvent,
281 'pedal' : musicexp.PedalEvent,
282 'wavy-line' : musicexp.TrillSpanEvent,
283 'octave-shift' : musicexp.OctaveShiftEvent,
284 'wedge' : musicexp.HairpinEvent
286 spanner_type_dict = {
299 def musicxml_spanner_to_lily_event (mxl_event):
302 name = mxl_event.get_name()
303 func = spanner_event_dict.get (name)
307 error_message ('unknown span event %s' % mxl_event)
310 type = mxl_event.get_type ()
311 span_direction = spanner_type_dict.get (type)
312 # really check for None, because some types will be translated to 0, which
313 # would otherwise also lead to the unknown span warning
314 if span_direction != None:
315 ev.span_direction = span_direction
317 error_message ('unknown span type %s for %s' % (type, name))
319 ev.set_span_type (type)
320 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
322 # assign the size, which is used for octave-shift, etc.
323 ev.size = mxl_event.get_size ()
327 def musicxml_direction_to_indicator (direction):
328 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
330 def musicxml_fermata_to_lily_event (mxl_event):
331 ev = musicexp.ArticulationEvent ()
333 if hasattr (mxl_event, 'type'):
334 dir = musicxml_direction_to_indicator (mxl_event.type)
336 ev.force_direction = dir
339 def musicxml_tremolo_to_lily_event (mxl_event):
340 ev = musicexp.TremoloEvent ()
341 ev.bars = mxl_event.get_text ()
344 def musicxml_bend_to_lily_event (mxl_event):
345 ev = musicexp.BendEvent ()
346 ev.alter = mxl_event.bend_alter ()
350 def musicxml_fingering_event (mxl_event):
351 ev = musicexp.ShortArticulationEvent ()
352 ev.type = mxl_event.get_text ()
355 def musicxml_accidental_mark (mxl_event):
356 ev = musicexp.MarkupEvent ()
357 contents = { "sharp": "\\sharp",
358 "natural": "\\natural",
360 "double-sharp": "\\doublesharp",
361 "sharp-sharp": "\\sharp\\sharp",
362 "flat-flat": "\\flat\\flat",
363 "flat-flat": "\\doubleflat",
364 "natural-sharp": "\\natural\\sharp",
365 "natural-flat": "\\natural\\flat",
366 "quarter-flat": "\\semiflat",
367 "quarter-sharp": "\\semisharp",
368 "three-quarters-flat": "\\sesquiflat",
369 "three-quarters-sharp": "\\sesquisharp",
370 }.get (mxl_event.get_text ())
372 ev.contents = contents
377 # translate articulations, ornaments and other notations into ArticulationEvents
379 # -) string (ArticulationEvent with that name)
380 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
381 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
382 # TODO: Some translations are missing!
383 articulations_dict = {
384 "accent": (musicexp.ShortArticulationEvent, ">"),
385 "accidental-mark": musicxml_accidental_mark,
386 "bend": musicxml_bend_to_lily_event,
387 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
388 #"caesura": "caesura",
389 #"delayed-turn": "?",
390 #"detached-legato": "",
392 #"double-tongue": "",
393 "down-bow": "downbow",
395 "fingering": musicxml_fingering_event,
399 "harmonic": "flageolet",
401 "inverted-mordent": "prall",
402 "inverted-turn": "reverseturn",
403 "mordent": "mordent",
407 #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
412 #"snap-pizzicato": "",
414 "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
415 "staccato": (musicexp.ShortArticulationEvent, "."),
416 "stopped": (musicexp.ShortArticulationEvent, "+"),
419 "strong-accent": (musicexp.ShortArticulationEvent, "^"),
421 "tenuto": (musicexp.ShortArticulationEvent, "-"),
422 #"thumb-position": "",
425 "tremolo": musicxml_tremolo_to_lily_event,
426 "trill-mark": "trill",
427 #"triple-tongue": "",
432 articulation_spanners = [ "wavy-line" ]
434 def musicxml_articulation_to_lily_event (mxl_event):
435 # wavy-line elements are treated as trill spanners, not as articulation ornaments
436 if mxl_event.get_name () in articulation_spanners:
437 return musicxml_spanner_to_lily_event (mxl_event)
439 tmp_tp = articulations_dict.get (mxl_event.get_name ())
443 if isinstance (tmp_tp, str):
444 ev = musicexp.ArticulationEvent ()
446 elif isinstance (tmp_tp, tuple):
450 ev = tmp_tp (mxl_event)
452 # Some articulations use the type attribute, other the placement...
454 if hasattr (mxl_event, 'type'):
455 dir = musicxml_direction_to_indicator (mxl_event.type)
456 if hasattr (mxl_event, 'placement'):
457 dir = musicxml_direction_to_indicator (mxl_event.placement)
461 def musicxml_dynamics_to_lily_event (dynentry):
462 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
463 "f", "ff", "fff", "ffff", "fffff", "ffffff",
464 "mp", "mf", "sf", "sfp", "sfpp", "fp",
465 "rf", "rfz", "sfz", "sffz", "fz" )
466 if not dynentry.get_name() in dynamics_available:
468 event = musicexp.DynamicsEvent ()
469 event.type = dynentry.get_name ()
473 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
475 def musicxml_direction_to_lily (n):
476 # TODO: Handle the <staff> element!
478 dirtype_children = []
479 for dt in n.get_typed_children (musicxml.DirType):
480 dirtype_children += dt.get_all_children ()
482 for entry in dirtype_children:
483 if entry.get_name () == "dynamics":
484 for dynentry in entry.get_all_children ():
485 ev = musicxml_dynamics_to_lily_event (dynentry)
489 # octave shifts. pedal marks, hairpins etc. are spanners:
490 if entry.get_name() in direction_spanners:
491 event = musicxml_spanner_to_lily_event (entry)
498 instrument_drumtype_dict = {
499 'Acoustic Snare Drum': 'acousticsnare',
500 'Side Stick': 'sidestick',
501 'Open Triangle': 'opentriangle',
502 'Mute Triangle': 'mutetriangle',
503 'Tambourine': 'tambourine',
504 'Bass Drum': 'bassdrum',
507 def musicxml_note_to_lily_main_event (n):
511 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
514 pitch = musicxml_pitch_to_lily (mxl_pitch)
515 event = musicexp.NoteEvent()
518 acc = n.get_maybe_exist_named_child ('accidental')
520 # let's not force accs everywhere.
521 event.cautionary = acc.editorial
523 elif n.get_maybe_exist_typed_child (musicxml.Rest):
524 # rests can have display-octave and display-step, which are
525 # treated like an ordinary note pitch
526 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
527 event = musicexp.RestEvent()
528 pitch = musicxml_restdisplay_to_lily (rest)
530 elif n.instrument_name:
531 event = musicexp.NoteEvent ()
532 drum_type = instrument_drumtype_dict.get (n.instrument_name)
534 event.drum_type = drum_type
536 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
537 event.drum_type = 'acousticsnare'
540 n.message ("cannot find suitable event")
542 event.duration = musicxml_duration_to_lily (n)
548 def __init__ (self, here, dest):
552 class LilyPondVoiceBuilder:
555 self.pending_dynamics = []
556 self.end_moment = Rational (0)
557 self.begin_moment = Rational (0)
558 self.pending_multibar = Rational (0)
559 self.ignore_skips = False
561 def _insert_multibar (self):
562 r = musicexp.MultiMeasureRest ()
563 r.duration = musicexp.Duration()
564 r.duration.duration_log = 0
565 r.duration.factor = self.pending_multibar
566 self.elements.append (r)
567 self.begin_moment = self.end_moment
568 self.end_moment = self.begin_moment + self.pending_multibar
569 self.pending_multibar = Rational (0)
571 def add_multibar_rest (self, duration):
572 self.pending_multibar += duration
574 def set_duration (self, duration):
575 self.end_moment = self.begin_moment + duration
576 def current_duration (self):
577 return self.end_moment - self.begin_moment
579 def add_music (self, music, duration):
580 assert isinstance (music, musicexp.Music)
581 if self.pending_multibar > Rational (0):
582 self._insert_multibar ()
584 self.elements.append (music)
585 self.begin_moment = self.end_moment
586 self.set_duration (duration)
588 # Insert all pending dynamics right after the note/rest:
589 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
590 for d in self.pending_dynamics:
592 self.pending_dynamics = []
594 # Insert some music command that does not affect the position in the measure
595 def add_command (self, command):
596 assert isinstance (command, musicexp.Music)
597 if self.pending_multibar > Rational (0):
598 self._insert_multibar ()
599 self.elements.append (command)
600 def add_partial (self, command):
601 self.ignore_skips = True
602 self.add_command (command)
604 def add_dynamics (self, dynamic):
605 # store the dynamic item(s) until we encounter the next note/rest:
606 self.pending_dynamics.append (dynamic)
608 def add_bar_check (self, number):
609 b = musicexp.BarCheck ()
610 b.bar_number = number
613 def jumpto (self, moment):
614 current_end = self.end_moment + self.pending_multibar
615 diff = moment - current_end
617 if diff < Rational (0):
618 error_message ('Negative skip %s' % diff)
621 if diff > Rational (0) and not self.ignore_skips:
622 skip = musicexp.SkipEvent()
623 skip.duration.duration_log = 0
624 skip.duration.factor = diff
626 evc = musicexp.EventChord ()
627 evc.elements.append (skip)
628 self.add_music (evc, diff)
630 if diff > Rational (0) and moment == 0:
631 self.ignore_skips = False
633 def last_event_chord (self, starting_at):
637 # if the position matches, find the last EventChord, do not cross a bar line!
638 at = len( self.elements ) - 1
640 not isinstance (self.elements[at], musicexp.EventChord) and
641 not isinstance (self.elements[at], musicexp.BarCheck)):
646 and isinstance (self.elements[at], musicexp.EventChord)
647 and self.begin_moment == starting_at):
648 value = self.elements[at]
650 self.jumpto (starting_at)
654 def correct_negative_skip (self, goto):
655 self.end_moment = goto
656 self.begin_moment = goto
657 evc = musicexp.EventChord ()
658 self.elements.append (evc)
660 def musicxml_voice_to_lily_voice (voice):
665 # TODO: Make sure that the keys in the dict don't get reordered, since
666 # we need the correct ordering of the lyrics stanzas! By default,
667 # a dict will reorder its keys
668 for k in voice.get_lyrics_numbers ():
671 voice_builder = LilyPondVoiceBuilder()
673 for n in voice._elements:
674 if n.get_name () == 'forward':
677 if isinstance (n, musicxml.Partial) and n.partial > 0:
678 a = musicxml_partial_to_lily (n.partial)
680 voice_builder.add_partial (a)
683 if isinstance (n, musicxml.Direction):
684 for a in musicxml_direction_to_lily (n):
685 if a.wait_for_note ():
686 voice_builder.add_dynamics (a)
688 voice_builder.add_command (a)
691 if not n.get_maybe_exist_named_child ('chord'):
693 voice_builder.jumpto (n._when)
694 except NegativeSkip, neg:
695 voice_builder.correct_negative_skip (n._when)
696 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
698 if isinstance (n, musicxml.Attributes):
699 if n.is_first () and n._measure_position == Rational (0):
701 number = int (n.get_parent ().number)
705 voice_builder.add_bar_check (number)
707 for a in musicxml_attributes_to_lily (n):
708 voice_builder.add_command (a)
711 if not n.__class__.__name__ == 'Note':
712 error_message ('not a Note or Attributes? %s' % n)
715 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
717 and rest.is_whole_measure ()):
719 voice_builder.add_multibar_rest (n._duration)
722 if n.is_first () and n._measure_position == Rational (0):
724 num = int (n.get_parent ().number)
728 voice_builder.add_bar_check (num)
730 main_event = musicxml_note_to_lily_main_event (n)
732 if hasattr (main_event, 'drum_type') and main_event.drum_type:
733 modes_found['drummode'] = True
736 ev_chord = voice_builder.last_event_chord (n._when)
738 ev_chord = musicexp.EventChord()
739 voice_builder.add_music (ev_chord, n._duration)
741 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
744 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
745 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
747 grace_chord = musicexp.EventChord ()
748 ev_chord.append_grace (grace_chord)
749 if hasattr (grace, 'slash'):
750 # TODO: use grace_type = "appoggiatura" for slurred grace notes
751 if grace.slash == "yes":
752 ev_chord.grace_type = "acciaccatura"
753 elif grace.slash == "no":
754 ev_chord.grace_type = "grace"
755 # now that we have inserted the chord into the grace music, insert
756 # everything into that chord instead of the ev_chord
757 ev_chord = grace_chord
758 ev_chord.append (main_event)
760 ev_chord.append (main_event)
761 # When a note/chord has grace notes (duration==0), the duration of the
762 # event chord is not yet known, but the event chord was already added
763 # with duration 0. The following correct this when we hit the real note!
764 if voice_builder.current_duration () == 0 and n._duration > 0:
765 voice_builder.set_duration (n._duration)
767 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
771 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
772 # +tied | +slur | +tuplet | glissando | slide |
773 # ornaments | technical | articulations | dynamics |
774 # +fermata | arpeggiate | non-arpeggiate |
775 # accidental-mark | other-notation
777 if notations.get_tuplet():
778 tuplet_event = notations.get_tuplet()
779 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
782 frac = mod.get_fraction ()
784 tuplet_events.append ((ev_chord, tuplet_event, frac))
786 slurs = [s for s in notations.get_named_children ('slur')
787 if s.get_type () in ('start','stop')]
790 error_message ('more than 1 slur?')
792 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
793 ev_chord.append (lily_ev)
795 mxl_tie = notations.get_tie ()
796 if mxl_tie and mxl_tie.type == 'start':
797 ev_chord.append (musicexp.TieEvent ())
799 fermatas = notations.get_named_children ('fermata')
801 ev = musicxml_fermata_to_lily_event (a)
805 arpeggiate = notations.get_named_children ('arpeggiate')
807 ev_chord.append (musicexp.ArpeggioEvent ())
809 glissandos = notations.get_named_children ('glissando')
811 ev = musicxml_spanner_to_lily_event (a)
815 # Articulations can contain the following child elements:
816 # accent | strong-accent | staccato | tenuto |
817 # detached-legato | staccatissimo | spiccato |
818 # scoop | plop | doit | falloff | breath-mark |
819 # caesura | stress | unstress
820 # Technical can contain the following child elements:
821 # up-bow | down-bow | harmonic | open-string |
822 # thumb-position | fingering | pluck | double-tongue |
823 # triple-tongue | stopped | snap-pizzicato | fret |
824 # string | hammer-on | pull-off | bend | tap | heel |
825 # toe | fingernails | other-technical
826 # Ornaments can contain the following child elements:
827 # trill-mark | turn | delayed-turn | inverted-turn |
828 # shake | wavy-line | mordent | inverted-mordent |
829 # schleifer | tremolo | other-ornament, accidental-mark
830 ornaments = notations.get_named_children ('ornaments')
832 for ch in a.get_named_children ('tremolo'):
833 ev = musicxml_tremolo_to_lily_event (ch)
837 ornaments += notations.get_named_children ('articulations')
838 ornaments += notations.get_named_children ('technical')
841 for ch in a.get_all_children ():
842 ev = musicxml_articulation_to_lily_event (ch)
846 dynamics = notations.get_named_children ('dynamics')
848 for ch in a.get_all_children ():
849 ev = musicxml_dynamics_to_lily_event (ch)
855 note_lyrics_processed = []
856 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
857 for l in note_lyrics_elements:
858 if l.get_number () < 0:
859 for k in lyrics.keys ():
860 lyrics[k].append (l.lyric_to_text ())
861 note_lyrics_processed.append (k)
863 lyrics[l.number].append(l.lyric_to_text ())
864 note_lyrics_processed.append (l.number)
865 for lnr in lyrics.keys ():
866 if not lnr in note_lyrics_processed:
867 lyrics[lnr].append ("\skip4")
870 mxl_beams = [b for b in n.get_named_children ('beam')
871 if (b.get_type () in ('begin', 'end')
872 and b.is_primary ())]
874 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
876 ev_chord.append (beam_ev)
879 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
882 frac = mod.get_fraction ()
884 tuplet_events.append ((ev_chord, tuplet_event, frac))
886 ## force trailing mm rests to be written out.
887 voice_builder.add_music (musicexp.EventChord (), Rational (0))
889 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
891 seq_music = musicexp.SequentialMusic ()
893 if 'drummode' in modes_found.keys ():
894 ## \key <pitch> barfs in drummode.
895 ly_voice = [e for e in ly_voice
896 if not isinstance(e, musicexp.KeySignatureChange)]
898 seq_music.elements = ly_voice
900 for k in lyrics.keys ():
901 lyrics_dict[k] = musicexp.Lyrics ()
902 lyrics_dict[k].lyrics_syllables = lyrics[k]
905 if len (modes_found) > 1:
906 error_message ('Too many modes found %s' % modes_found.keys ())
908 return_value = seq_music
909 for mode in modes_found.keys ():
910 v = musicexp.ModeChangingMusicWrapper()
911 v.element = return_value
915 return (return_value, lyrics_dict)
918 def musicxml_id_to_lily (id):
919 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
920 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
923 d = digits.index (digit)
924 id = re.sub ('%d' % d, digit, id)
926 id = re.sub ('[^a-zA-Z]', 'X', id)
930 def musicxml_pitch_to_lily (mxl_pitch):
932 p.alteration = mxl_pitch.get_alteration ()
933 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
934 p.octave = mxl_pitch.get_octave () - 4
937 def musicxml_restdisplay_to_lily (mxl_rest):
939 step = mxl_rest.get_step ()
942 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
943 octave = mxl_rest.get_octave ()
945 p.octave = octave - 4
948 def voices_in_part (part):
949 """Return a Name -> Voice dictionary for PART"""
951 part.extract_voices ()
952 voice_dict = part.get_voices ()
956 def voices_in_part_in_parts (parts):
957 """return a Part -> Name -> Voice dictionary"""
958 return dict([(p, voices_in_part (p)) for p in parts])
961 def get_all_voices (parts):
962 all_voices = voices_in_part_in_parts (parts)
965 for p, name_voice in all_voices.items ():
968 for n, v in name_voice.items ():
969 progress ("Converting to LilyPond expressions...")
970 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
971 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
973 all_ly_voices[p] = part_ly_voices
978 def option_parser ():
979 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
980 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
982 _ ("""This program is free software. It is covered by the GNU General Public
983 License and you are welcome to change it and/or distribute copies of it
984 under certain conditions. Invoke as `%s --warranty' for more
985 information.""") % 'lilypond'
987 Copyright (c) 2005--2007 by
988 Han-Wen Nienhuys <hanwen@xs4all.nl> and
989 Jan Nieuwenhuizen <janneke@gnu.org>
991 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
992 p.add_option ('-v', '--verbose',
995 help=_ ("be verbose"))
997 p.add_option ('', '--lxml',
1001 help=_ ("Use lxml.etree; uses less memory and cpu time."))
1003 p.add_option ('-o', '--output',
1009 help=_ ("set output filename to FILE"))
1010 p.add_option_group ('bugs',
1011 description=(_ ("Report bugs via")
1012 + ''' http://post.gmane.org/post.php'''
1013 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1016 def music_xml_voice_name_to_lily_name (part, name):
1017 str = "Part%sVoice%s" % (part.id, name)
1018 return musicxml_id_to_lily (str)
1020 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1021 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1022 return musicxml_id_to_lily (str)
1024 def print_voice_definitions (printer, part_list, voices):
1026 for (part, nv_dict) in voices.items():
1027 part_dict[part.id] = (part, nv_dict)
1029 for part in part_list:
1030 (p, nv_dict) = part_dict.get (part.id, (None, {}))
1031 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1032 k = music_xml_voice_name_to_lily_name (p, name)
1033 printer.dump ('%s = ' % k)
1034 voice.print_ly (printer)
1037 for l in lyrics.keys ():
1038 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1039 printer.dump ('%s = ' %lname )
1040 lyrics[l].print_ly (printer)
1045 return dict ([(elt,1) for elt in l]).keys ()
1047 # format the information about the staff in the form
1050 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1051 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1055 # raw_voices is of the form [(voicename, lyrics)*]
1056 def format_staff_info (part, staff_id, raw_voices):
1058 for (v, lyrics) in raw_voices:
1059 voice_name = music_xml_voice_name_to_lily_name (part, v)
1060 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1061 for l in lyrics.keys ()]
1062 voices.append ([voice_name, voice_lyrics])
1063 return [staff_id, voices]
1065 def update_score_setup (score_structure, part_list, voices):
1066 part_dict = dict ([(p.id, p) for p in voices.keys ()])
1067 final_part_dict = {}
1069 for part_definition in part_list:
1070 part_name = part_definition.id
1071 part = part_dict.get (part_name)
1073 error_message ('unknown part in part-list: %s' % part_name)
1076 nv_dict = voices.get (part)
1077 staves = reduce (lambda x,y: x+ y,
1078 [mxlvoice._staves.keys ()
1079 for (v, mxlvoice) in nv_dict.values ()],
1082 if len (staves) > 1:
1084 staves = uniq_list (staves)
1087 thisstaff_raw_voices = [(voice_name, lyrics)
1088 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1089 if mxlvoice._start_staff == s]
1090 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1092 thisstaff_raw_voices = [(voice_name, lyrics)
1093 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1094 staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1095 score_structure.setPartInformation (part_name, staves_info)
1097 def print_ly_preamble (printer, filename):
1098 printer.dump_version ()
1099 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1101 def read_musicxml (filename, use_lxml):
1105 tree = lxml.etree.parse (filename)
1106 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1109 from xml.dom import minidom, Node
1111 doc = minidom.parse(filename)
1112 node = doc.documentElement
1113 return musicxml.minidom_demarshal_node (node)
1118 def convert (filename, options):
1119 progress ("Reading MusicXML from %s ..." % filename)
1121 tree = read_musicxml (filename, options.use_lxml)
1123 score_structure = None
1124 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1126 score_structure = extract_score_layout (mxl_pl)
1127 part_list = mxl_pl.get_named_children ("score-part")
1129 # score information is contained in the <work>, <identification> or <movement-title> tags
1130 score_information = extract_score_information (tree)
1131 parts = tree.get_typed_children (musicxml.Part)
1132 voices = get_all_voices (parts)
1133 update_score_setup (score_structure, part_list, voices)
1135 if not options.output_name:
1136 options.output_name = os.path.basename (filename)
1137 options.output_name = os.path.splitext (options.output_name)[0]
1138 elif re.match (".*\.ly", options.output_name):
1139 options.output_name = os.path.splitext (options.output_name)[0]
1142 defs_ly_name = options.output_name + '-defs.ly'
1143 driver_ly_name = options.output_name + '.ly'
1145 printer = musicexp.Output_printer()
1146 progress ("Output to `%s'" % defs_ly_name)
1147 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1149 print_ly_preamble (printer, filename)
1150 score_information.print_ly (printer)
1151 print_voice_definitions (printer, part_list, voices)
1156 progress ("Output to `%s'" % driver_ly_name)
1157 printer = musicexp.Output_printer()
1158 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1159 print_ly_preamble (printer, filename)
1160 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1161 score_structure.print_ly (printer)
1166 def get_existing_filename_with_extension (filename, ext):
1167 if os.path.exists (filename):
1169 newfilename = filename + ".xml"
1170 if os.path.exists (newfilename):
1172 newfilename = filename + "xml"
1173 if os.path.exists (newfilename):
1178 opt_parser = option_parser()
1180 (options, args) = opt_parser.parse_args ()
1182 opt_parser.print_usage()
1185 # Allow the user to leave out the .xml or xml on the filename
1186 filename = get_existing_filename_with_extension (args[0], "xml")
1187 if filename and os.path.exists (filename):
1188 voices = convert (filename, options)
1190 progress ("Unable to find input file %s" % args[0])
1192 if __name__ == '__main__':