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 ())
67 def musicxml_duration_to_lily (mxl_note):
68 d = musicexp.Duration ()
69 # if the note has no Type child, then that method spits out a warning and
70 # returns 0, i.e. a whole note
71 d.duration_log = mxl_note.get_duration_log ()
73 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
74 # Grace notes by specification have duration 0, so no time modification
75 # factor is possible. It even messes up the output with *0/1
76 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
77 d.factor = mxl_note._duration / d.get_length ()
81 def group_tuplets (music_list, events):
84 """Collect Musics from
85 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
92 for (ev_chord, tuplet_elt, fraction) in events:
93 while (j < len (music_list)):
94 if music_list[j] == ev_chord:
97 if tuplet_elt.type == 'start':
98 indices.append ((j, None, fraction))
99 elif tuplet_elt.type == 'stop':
100 indices[-1] = (indices[-1][0], j, indices[-1][2])
104 for (i1, i2, frac) in indices:
108 new_list.extend (music_list[last:i1])
109 seq = musicexp.SequentialMusic ()
111 seq.elements = music_list[i1:last]
113 tsm = musicexp.TimeScaledMusic ()
116 tsm.numerator = frac[0]
117 tsm.denominator = frac[1]
119 new_list.append (tsm)
121 new_list.extend (music_list[last:])
125 def musicxml_clef_to_lily (attributes):
126 change = musicexp.ClefChange ()
127 (change.type, change.position, change.octave) = attributes.get_clef_information ()
130 def musicxml_time_to_lily (attributes):
131 (beats, type) = attributes.get_time_signature ()
133 change = musicexp.TimeSignatureChange()
134 change.fraction = (beats, type)
138 def musicxml_key_to_lily (attributes):
139 start_pitch = musicexp.Pitch ()
140 (fifths, mode) = attributes.get_key_signature ()
147 start_pitch.alteration = a
149 error_message ('unknown mode %s' % mode)
151 fifth = musicexp.Pitch()
158 for x in range (fifths):
159 start_pitch = start_pitch.transposed (fifth)
161 start_pitch.octave = 0
163 change = musicexp.KeySignatureChange()
165 change.tonic = start_pitch
168 def musicxml_attributes_to_lily (attrs):
171 'clef': musicxml_clef_to_lily,
172 'time': musicxml_time_to_lily,
173 'key': musicxml_key_to_lily
175 for (k, func) in attr_dispatch.items ():
176 children = attrs.get_named_children (k)
178 ## ugh: you get clefs spread over staves for piano
180 elts.append (func (attrs))
184 spanner_event_dict = {
185 'slur' : musicexp.SlurEvent,
186 'beam' : musicexp.BeamEvent,
187 'glissando' : musicexp.GlissandoEvent,
188 'pedal' : musicexp.PedalEvent,
189 'wavy-line' : musicexp.TrillSpanEvent,
190 'octave-shift' : musicexp.OctaveShiftEvent,
191 'wedge' : musicexp.HairpinEvent
193 spanner_type_dict = {
206 def musicxml_spanner_to_lily_event (mxl_event):
209 name = mxl_event.get_name()
210 func = spanner_event_dict.get (name)
214 error_message ('unknown span event %s' % mxl_event)
217 type = mxl_event.get_type ()
218 span_direction = spanner_type_dict.get (type)
219 # really check for None, because some types will be translated to 0, which
220 # would otherwise also lead to the unknown span warning
221 if span_direction != None:
222 ev.span_direction = span_direction
224 error_message ('unknown span type %s for %s' % (type, name))
226 ev.set_span_type (type)
227 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
229 # assign the size, which is used for octave-shift, etc.
230 ev.size = mxl_event.get_size ()
234 def musicxml_direction_to_indicator (direction):
235 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
237 def musicxml_fermata_to_lily_event (mxl_event):
238 ev = musicexp.ArticulationEvent ()
240 if hasattr (mxl_event, 'type'):
241 dir = musicxml_direction_to_indicator (mxl_event.type)
243 ev.force_direction = dir
246 def musicxml_tremolo_to_lily_event (mxl_event):
247 if mxl_event.get_name () != "tremolo":
249 ev = musicexp.TremoloEvent ()
250 ev.bars = mxl_event.get_text ()
253 def musicxml_bend_to_lily_event (mxl_event):
254 if mxl_event.get_name () != "bend":
256 ev = musicexp.BendEvent ()
257 ev.alter = mxl_event.bend_alter ()
261 short_articulations_dict = {
265 "staccatissimo": "|",
267 "strong-accent": "^",
268 #"portato": "_", # does not exist in MusicXML
269 #"fingering": "", # fingering is special cased, as get_text() will be the event's name
271 # TODO: Some translations are missing!
272 articulations_dict = {
274 "trill-mark": "trill",
276 #"delayed-turn": "?",
277 "inverted-turn": "reverseturn",
280 "mordent": "mordent",
281 "inverted-mordent": "prall",
285 "down-bow": "downbow",
286 "harmonic": "flageolet",
288 #"thumb-position": "",
290 #"double-tongue": "",
291 #"triple-tongue": "",
292 #"snap-pizzicato": "",
297 #"bend": "bendAfter #%s", # bend is special-cased, as we need to process the bend-alter subelement!
303 #"detached-legato": "",
309 "breath-mark": "breathe",
310 #"caesura": "caesura",
314 articulation_spanners = [ "wavy-line" ]
316 def musicxml_articulation_to_lily_event (mxl_event):
317 # wavy-line elements are treated as trill spanners, not as articulation ornaments
318 if mxl_event.get_name () in articulation_spanners:
319 return musicxml_spanner_to_lily_event (mxl_event)
321 # special case, because of the bend-alter subelement
322 if mxl_event.get_name() == "bend":
323 return musicxml_bend_to_lily_event (mxl_event)
325 # If we can write a shorthand, use them!
326 if mxl_event.get_name() == "fingering":
327 ev = musicexp.ShortArticulationEvent ()
328 tp = mxl_event.get_text()
329 # In all other cases, use the dicts to translate the xml tag name to a proper lilypond command
330 elif short_articulations_dict.get (mxl_event.get_name ()):
331 ev = musicexp.ShortArticulationEvent ()
332 tp = short_articulations_dict.get (mxl_event.get_name ())
334 ev = musicexp.ArticulationEvent ()
335 tp = articulations_dict.get (mxl_event.get_name ())
342 # Some articulations use the type attribute, other the placement...
344 if hasattr (mxl_event, 'type'):
345 dir = musicxml_direction_to_indicator (mxl_event.type)
346 if hasattr (mxl_event, 'placement'):
347 dir = musicxml_direction_to_indicator (mxl_event.placement)
348 # \breathe cannot have any direction modifier (^, _, -)!
349 if dir and tp != "breathe":
350 ev.force_direction = dir
354 def musicxml_dynamics_to_lily_event (dynentry):
355 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
356 "f", "ff", "fff", "ffff", "fffff", "ffffff",
357 "mp", "mf", "sf", "sfp", "sfpp", "fp",
358 "rf", "rfz", "sfz", "sffz", "fz" )
359 if not dynentry.get_name() in dynamics_available:
361 event = musicexp.DynamicsEvent ()
362 event.type = dynentry.get_name ()
366 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
368 def musicxml_direction_to_lily (n):
369 # TODO: Handle the <staff> element!
371 dirtype_children = []
372 for dt in n.get_typed_children (musicxml.DirType):
373 dirtype_children += dt.get_all_children ()
375 for entry in dirtype_children:
376 if entry.get_name () == "dynamics":
377 for dynentry in entry.get_all_children ():
378 ev = musicxml_dynamics_to_lily_event (dynentry)
382 # octave shifts. pedal marks, hairpins etc. are spanners:
383 if entry.get_name() in direction_spanners:
384 event = musicxml_spanner_to_lily_event (entry)
391 instrument_drumtype_dict = {
392 'Acoustic Snare Drum': 'acousticsnare',
393 'Side Stick': 'sidestick',
394 'Open Triangle': 'opentriangle',
395 'Mute Triangle': 'mutetriangle',
396 'Tambourine': 'tambourine'
399 def musicxml_note_to_lily_main_event (n):
403 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
406 pitch = musicxml_pitch_to_lily (mxl_pitch)
407 event = musicexp.NoteEvent()
410 acc = n.get_maybe_exist_named_child ('accidental')
412 # let's not force accs everywhere.
413 event.cautionary = acc.editorial
415 elif n.get_maybe_exist_typed_child (musicxml.Rest):
416 # rests can have display-octave and display-step, which are
417 # treated like an ordinary note pitch
418 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
419 event = musicexp.RestEvent()
420 pitch = musicxml_restdisplay_to_lily (rest)
422 elif n.instrument_name:
423 event = musicexp.NoteEvent ()
424 drum_type = instrument_drumtype_dict.get (n.instrument_name)
426 event.drum_type = drum_type
428 n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
429 event.drum_type = 'acousticsnare'
432 n.message ("cannot find suitable event")
434 event.duration = musicxml_duration_to_lily (n)
440 def __init__ (self, here, dest):
444 class LilyPondVoiceBuilder:
447 self.pending_dynamics = []
448 self.end_moment = Rational (0)
449 self.begin_moment = Rational (0)
450 self.pending_multibar = Rational (0)
452 def _insert_multibar (self):
453 r = musicexp.MultiMeasureRest ()
454 r.duration = musicexp.Duration()
455 r.duration.duration_log = 0
456 r.duration.factor = self.pending_multibar
457 self.elements.append (r)
458 self.begin_moment = self.end_moment
459 self.end_moment = self.begin_moment + self.pending_multibar
460 self.pending_multibar = Rational (0)
462 def add_multibar_rest (self, duration):
463 self.pending_multibar += duration
465 def set_duration (self, duration):
466 self.end_moment = self.begin_moment + duration
467 def current_duration (self):
468 return self.end_moment - self.begin_moment
470 def add_music (self, music, duration):
471 assert isinstance (music, musicexp.Music)
472 if self.pending_multibar > Rational (0):
473 self._insert_multibar ()
475 self.elements.append (music)
476 self.begin_moment = self.end_moment
477 self.set_duration (duration)
479 # Insert all pending dynamics right after the note/rest:
480 if duration > Rational (0):
481 for d in self.pending_dynamics:
482 self.elements.append (d)
483 self.pending_dynamics = []
485 # Insert some music command that does not affect the position in the measure
486 def add_command (self, command):
487 assert isinstance (command, musicexp.Music)
488 if self.pending_multibar > Rational (0):
489 self._insert_multibar ()
490 self.elements.append (command)
492 def add_dynamics (self, dynamic):
493 # store the dynamic item(s) until we encounter the next note/rest:
494 self.pending_dynamics.append (dynamic)
496 def add_bar_check (self, number):
497 b = musicexp.BarCheck ()
498 b.bar_number = number
499 self.add_music (b, Rational (0))
501 def jumpto (self, moment):
502 current_end = self.end_moment + self.pending_multibar
503 diff = moment - current_end
505 if diff < Rational (0):
506 error_message ('Negative skip %s' % diff)
509 if diff > Rational (0):
510 skip = musicexp.SkipEvent()
511 skip.duration.duration_log = 0
512 skip.duration.factor = diff
514 evc = musicexp.EventChord ()
515 evc.elements.append (skip)
516 self.add_music (evc, diff)
518 def last_event_chord (self, starting_at):
522 # if the position matches, find the last EventChord, do not cross a bar line!
523 at = len( self.elements ) - 1
525 not isinstance (self.elements[at], musicexp.EventChord) and
526 not isinstance (self.elements[at], musicexp.BarCheck)):
531 and isinstance (self.elements[at], musicexp.EventChord)
532 and self.begin_moment == starting_at):
533 value = self.elements[at]
535 self.jumpto (starting_at)
539 def correct_negative_skip (self, goto):
540 self.end_moment = goto
541 self.begin_moment = goto
542 evc = musicexp.EventChord ()
543 self.elements.append (evc)
545 def musicxml_voice_to_lily_voice (voice):
550 for k in voice.get_lyrics_numbers ():
553 voice_builder = LilyPondVoiceBuilder()
555 for n in voice._elements:
556 if n.get_name () == 'forward':
559 if isinstance (n, musicxml.Direction):
560 for a in musicxml_direction_to_lily (n):
561 if a.wait_for_note ():
562 voice_builder.add_dynamics (a)
564 voice_builder.add_command (a)
567 if not n.get_maybe_exist_named_child ('chord'):
569 voice_builder.jumpto (n._when)
570 except NegativeSkip, neg:
571 voice_builder.correct_negative_skip (n._when)
572 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
574 if isinstance (n, musicxml.Attributes):
575 if n.is_first () and n._measure_position == Rational (0):
577 number = int (n.get_parent ().number)
581 voice_builder.add_bar_check (number)
582 for a in musicxml_attributes_to_lily (n):
583 voice_builder.add_music (a, Rational (0))
586 if not n.__class__.__name__ == 'Note':
587 error_message ('not a Note or Attributes? %s' % n)
590 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
592 and rest.is_whole_measure ()):
594 voice_builder.add_multibar_rest (n._duration)
597 if n.is_first () and n._measure_position == Rational (0):
599 num = int (n.get_parent ().number)
602 voice_builder.add_bar_check (num)
604 main_event = musicxml_note_to_lily_main_event (n)
606 if hasattr (main_event, 'drum_type') and main_event.drum_type:
607 modes_found['drummode'] = True
610 ev_chord = voice_builder.last_event_chord (n._when)
612 ev_chord = musicexp.EventChord()
613 voice_builder.add_music (ev_chord, n._duration)
614 # When a note/chord has grace notes (duration==0), the duration of the
615 # event chord is not yet known, but the event chord was already added
616 # with duration 0. The following correct this when we hit the real note!
617 if voice_builder.current_duration () == 0 and n._duration > 0:
618 voice_builder.set_duration (n._duration)
619 if n.get_maybe_exist_typed_child (musicxml.Grace):
620 ev_chord.append_grace (main_event)
622 ev_chord.append (main_event)
624 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
628 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
629 # +tied | +slur | +tuplet | glissando | slide |
630 # ornaments | technical | articulations | dynamics |
631 # +fermata | arpeggiate | non-arpeggiate |
632 # accidental-mark | other-notation
634 if notations.get_tuplet():
635 tuplet_event = notations.get_tuplet()
636 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
639 frac = mod.get_fraction ()
641 tuplet_events.append ((ev_chord, tuplet_event, frac))
643 slurs = [s for s in notations.get_named_children ('slur')
644 if s.get_type () in ('start','stop')]
647 error_message ('more than 1 slur?')
649 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
650 ev_chord.append (lily_ev)
652 mxl_tie = notations.get_tie ()
653 if mxl_tie and mxl_tie.type == 'start':
654 ev_chord.append (musicexp.TieEvent ())
656 fermatas = notations.get_named_children ('fermata')
658 ev = musicxml_fermata_to_lily_event (a)
662 arpeggiate = notations.get_named_children ('arpeggiate')
664 ev_chord.append (musicexp.ArpeggioEvent ())
666 glissandos = notations.get_named_children ('glissando')
668 ev = musicxml_spanner_to_lily_event (a)
672 # Articulations can contain the following child elements:
673 # accent | strong-accent | staccato | tenuto |
674 # detached-legato | staccatissimo | spiccato |
675 # scoop | plop | doit | falloff | breath-mark |
676 # caesura | stress | unstress
677 # Technical can contain the following child elements:
678 # up-bow | down-bow | harmonic | open-string |
679 # thumb-position | fingering | pluck | double-tongue |
680 # triple-tongue | stopped | snap-pizzicato | fret |
681 # string | hammer-on | pull-off | bend | tap | heel |
682 # toe | fingernails | other-technical
683 # Ornaments can contain the following child elements:
684 # trill-mark | turn | delayed-turn | inverted-turn |
685 # shake | wavy-line | mordent | inverted-mordent |
686 # schleifer | tremolo | other-ornament, accidental-mark
687 ornaments = notations.get_named_children ('ornaments')
689 for ch in a.get_named_children ('tremolo'):
690 ev = musicxml_tremolo_to_lily_event (ch)
694 ornaments += notations.get_named_children ('articulations')
695 ornaments += notations.get_named_children ('technical')
698 for ch in a.get_all_children ():
699 ev = musicxml_articulation_to_lily_event (ch)
703 dynamics = notations.get_named_children ('dynamics')
705 for ch in a.get_all_children ():
706 ev = musicxml_dynamics_to_lily_event (ch)
712 note_lyrics_processed = []
713 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
714 for l in note_lyrics_elements:
715 if l.get_number () < 0:
716 for k in lyrics.keys ():
717 lyrics[k].append (l.lyric_to_text ())
718 note_lyrics_processed.append (k)
720 lyrics[l.number].append(l.lyric_to_text ())
721 note_lyrics_processed.append (l.number)
722 for lnr in lyrics.keys ():
723 if not lnr in note_lyrics_processed:
724 lyrics[lnr].append ("\skip4")
727 mxl_beams = [b for b in n.get_named_children ('beam')
728 if (b.get_type () in ('begin', 'end')
729 and b.is_primary ())]
731 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
733 ev_chord.append (beam_ev)
736 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
739 frac = mod.get_fraction ()
741 tuplet_events.append ((ev_chord, tuplet_event, frac))
743 ## force trailing mm rests to be written out.
744 voice_builder.add_music (musicexp.EventChord (), Rational (0))
746 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
748 seq_music = musicexp.SequentialMusic ()
750 if 'drummode' in modes_found.keys ():
751 ## \key <pitch> barfs in drummode.
752 ly_voice = [e for e in ly_voice
753 if not isinstance(e, musicexp.KeySignatureChange)]
755 seq_music.elements = ly_voice
757 for k in lyrics.keys ():
758 lyrics_dict[k] = musicexp.Lyrics ()
759 lyrics_dict[k].lyrics_syllables = lyrics[k]
762 if len (modes_found) > 1:
763 error_message ('Too many modes found %s' % modes_found.keys ())
765 return_value = seq_music
766 for mode in modes_found.keys ():
767 v = musicexp.ModeChangingMusicWrapper()
768 v.element = return_value
772 return (return_value, lyrics_dict)
775 def musicxml_id_to_lily (id):
776 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
777 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
780 d = digits.index (digit)
781 id = re.sub ('%d' % d, digit, id)
783 id = re.sub ('[^a-zA-Z]', 'X', id)
787 def musicxml_pitch_to_lily (mxl_pitch):
789 p.alteration = mxl_pitch.get_alteration ()
790 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
791 p.octave = mxl_pitch.get_octave () - 4
794 def musicxml_restdisplay_to_lily (mxl_rest):
796 step = mxl_rest.get_step ()
799 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
800 octave = mxl_rest.get_octave ()
802 p.octave = octave - 4
805 def voices_in_part (part):
806 """Return a Name -> Voice dictionary for PART"""
808 part.extract_voices ()
809 voice_dict = part.get_voices ()
813 def voices_in_part_in_parts (parts):
814 """return a Part -> Name -> Voice dictionary"""
815 return dict([(p, voices_in_part (p)) for p in parts])
818 def get_all_voices (parts):
819 all_voices = voices_in_part_in_parts (parts)
822 for p, name_voice in all_voices.items ():
825 for n, v in name_voice.items ():
826 progress ("Converting to LilyPond expressions...")
827 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
828 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
830 all_ly_voices[p] = part_ly_voices
835 def option_parser ():
836 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
837 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
839 _ ("""This program is free software. It is covered by the GNU General Public
840 License and you are welcome to change it and/or distribute copies of it
841 under certain conditions. Invoke as `%s --warranty' for more
842 information.""") % 'lilypond'
844 Copyright (c) 2005--2007 by
845 Han-Wen Nienhuys <hanwen@xs4all.nl> and
846 Jan Nieuwenhuizen <janneke@gnu.org>
848 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
849 p.add_option ('-v', '--verbose',
852 help=_ ("be verbose"))
854 p.add_option ('', '--lxml',
858 help=_ ("Use lxml.etree; uses less memory and cpu time."))
860 p.add_option ('-o', '--output',
866 help=_ ("set output filename to FILE"))
867 p.add_option_group ('bugs',
868 description=(_ ("Report bugs via")
869 + ''' http://post.gmane.org/post.php'''
870 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
873 def music_xml_voice_name_to_lily_name (part, name):
874 str = "Part%sVoice%s" % (part.id, name)
875 return musicxml_id_to_lily (str)
877 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
878 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
879 return musicxml_id_to_lily (str)
881 def print_voice_definitions (printer, part_list, voices):
883 for (part, nv_dict) in voices.items():
884 part_dict[part.id] = (part, nv_dict)
886 for part in part_list:
887 (part, nv_dict) = part_dict.get (part.id, (None, {}))
888 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
889 k = music_xml_voice_name_to_lily_name (part, name)
890 printer.dump ('%s = ' % k)
891 voice.print_ly (printer)
894 for l in lyrics.keys ():
895 lname = music_xml_lyrics_name_to_lily_name (part, name, l)
896 printer.dump ('%s = ' %lname )
897 lyrics[l].print_ly (printer)
902 return dict ([(elt,1) for elt in l]).keys ()
904 def print_score_setup (printer, part_list, voices):
905 part_dict = dict ([(p.id, p) for p in voices.keys ()])
909 for part_definition in part_list:
910 part_name = part_definition.id
911 part = part_dict.get (part_name)
913 error_message ('unknown part in part-list: %s' % part_name)
916 nv_dict = voices.get (part)
917 staves = reduce (lambda x,y: x+ y,
918 [mxlvoice._staves.keys ()
919 for (v, mxlvoice) in nv_dict.values ()],
923 staves = uniq_list (staves)
925 printer ('\\context PianoStaff << ')
929 staff_voices = [(music_xml_voice_name_to_lily_name (part, voice_name), voice_name, v)
930 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
931 if mxlvoice._start_staff == s]
933 printer ('\\context Staff = "%s" << ' % s)
935 for (v, voice_name, (music, lyrics)) in staff_voices:
936 printer ('\\context Voice = "%s" \\%s' % (v,v))
939 # Assign the lyrics to that voice
940 for l in lyrics.keys ():
941 ll = music_xml_lyrics_name_to_lily_name (part, voice_name, l)
942 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (v, ll))
953 printer ('\\new Staff <<')
955 for (n,v) in nv_dict.items ():
956 ((music, lyrics), voice) = v
957 nn = music_xml_voice_name_to_lily_name (part, n)
958 printer ('\\context Voice = "%s" \\%s' % (nn,nn))
960 # Assign the lyrics to that voice
961 for l in lyrics.keys ():
962 ll = music_xml_lyrics_name_to_lily_name (part, n, l)
963 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (nn, ll))
972 def print_ly_preamble (printer, filename):
973 printer.dump_version ()
974 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
976 def read_musicxml (filename, use_lxml):
980 tree = lxml.etree.parse (filename)
981 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
984 from xml.dom import minidom, Node
986 doc = minidom.parse(filename)
987 node = doc.documentElement
988 return musicxml.minidom_demarshal_node (node)
993 def convert (filename, options):
994 progress ("Reading MusicXML from %s ..." % filename)
996 tree = read_musicxml (filename, options.use_lxml)
999 id_instrument_map = {}
1000 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
1001 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1002 part_list = mxl_pl.get_named_children ("score-part")
1004 # score information is contained in the <work>, <identification> or <movement-title> tags
1005 score_information = extract_score_information (tree)
1006 parts = tree.get_typed_children (musicxml.Part)
1007 voices = get_all_voices (parts)
1009 if not options.output_name:
1010 options.output_name = os.path.basename (filename)
1011 options.output_name = os.path.splitext (options.output_name)[0]
1012 elif re.match (".*\.ly", options.output_name):
1013 options.output_name = os.path.splitext (options.output_name)[0]
1016 defs_ly_name = options.output_name + '-defs.ly'
1017 driver_ly_name = options.output_name + '.ly'
1019 printer = musicexp.Output_printer()
1020 progress ("Output to `%s'" % defs_ly_name)
1021 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1023 print_ly_preamble (printer, filename)
1024 score_information.print_ly (printer)
1025 print_voice_definitions (printer, part_list, voices)
1030 progress ("Output to `%s'" % driver_ly_name)
1031 printer = musicexp.Output_printer()
1032 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1033 print_ly_preamble (printer, filename)
1034 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1035 print_score_setup (printer, part_list, voices)
1040 def get_existing_filename_with_extension (filename, ext):
1041 if os.path.exists (filename):
1043 newfilename = filename + ".xml"
1044 if os.path.exists (newfilename):
1046 newfilename = filename + "xml"
1047 if os.path.exists (newfilename):
1052 opt_parser = option_parser()
1054 (options, args) = opt_parser.parse_args ()
1056 opt_parser.print_usage()
1059 # Allow the user to leave out the .xml or xml on the filename
1060 filename = get_existing_filename_with_extension (args[0], "xml")
1061 if filename and os.path.exists (filename):
1062 voices = convert (filename, options)
1064 progress ("Unable to find input file %s" % args[0])
1066 if __name__ == '__main__':