8 from gettext import gettext as _
19 from rational import Rational
23 sys.stderr.write (str + '\n')
26 def error_message (str):
27 sys.stderr.write (str + '\n')
30 # score information is contained in the <work>, <identification> or <movement-title> tags
31 # extract those into a hash, indexed by proper lilypond header attributes
32 def extract_score_information (tree):
33 score_information = {}
34 def set_if_exists (field, value):
36 score_information[field] = value
38 work = tree.get_maybe_exist_named_child ('work')
40 set_if_exists ('title', work.get_work_title ())
41 set_if_exists ('worknumber', work.get_work_number ())
42 set_if_exists ('opus', work.get_opus ())
44 movement_title = tree.get_maybe_exist_named_child ('movement-title')
46 set_if_exists ('title', movement_title.get_text ())
48 identifications = tree.get_named_children ('identification')
49 for ids in identifications:
50 set_if_exists ('copyright', ids.get_rights ())
51 set_if_exists ('composer', ids.get_composer ())
52 set_if_exists ('arranger', ids.get_arranger ())
53 set_if_exists ('editor', ids.get_editor ())
54 set_if_exists ('poet', ids.get_poet ())
56 set_if_exists ('tagline', ids.get_encoding_software ())
57 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
58 set_if_exists ('encodingdate', ids.get_encoding_date ())
59 set_if_exists ('encoder', ids.get_encoding_person ())
60 set_if_exists ('encodingdescription', ids.get_encoding_description ())
62 return score_information
65 def print_ly_information (printer, score_information):
66 printer.dump ('\header {')
68 for (k, text) in score_information.items ():
69 printer.dump ('%s = %s' % (k, musicxml.escape_ly_output_string (text)))
76 def musicxml_duration_to_lily (mxl_note):
77 d = musicexp.Duration ()
78 # if the note has no Type child, then that method spits out a warning and
79 # returns 0, i.e. a whole note
80 d.duration_log = mxl_note.get_duration_log ()
82 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
83 # Grace notes by specification have duration 0, so no time modification
84 # factor is possible. It even messes up the output with *0/1
85 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
86 d.factor = mxl_note._duration / d.get_length ()
90 def group_tuplets (music_list, events):
93 """Collect Musics from
94 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
101 for (ev_chord, tuplet_elt, fraction) in events:
102 while (j < len (music_list)):
103 if music_list[j] == ev_chord:
106 if tuplet_elt.type == 'start':
107 indices.append ((j, None, fraction))
108 elif tuplet_elt.type == 'stop':
109 indices[-1] = (indices[-1][0], j, indices[-1][2])
113 for (i1, i2, frac) in indices:
117 new_list.extend (music_list[last:i1])
118 seq = musicexp.SequentialMusic ()
120 seq.elements = music_list[i1:last]
122 tsm = musicexp.TimeScaledMusic ()
125 tsm.numerator = frac[0]
126 tsm.denominator = frac[1]
128 new_list.append (tsm)
130 new_list.extend (music_list[last:])
134 def musicxml_clef_to_lily (attributes):
135 change = musicexp.ClefChange ()
136 (change.type, change.position, change.octave) = attributes.get_clef_information ()
139 def musicxml_time_to_lily (attributes):
140 (beats, type) = attributes.get_time_signature ()
142 change = musicexp.TimeSignatureChange()
143 change.fraction = (beats, type)
147 def musicxml_key_to_lily (attributes):
148 start_pitch = musicexp.Pitch ()
149 (fifths, mode) = attributes.get_key_signature ()
156 start_pitch.alteration = a
158 error_message ('unknown mode %s' % mode)
160 fifth = musicexp.Pitch()
167 for x in range (fifths):
168 start_pitch = start_pitch.transposed (fifth)
170 start_pitch.octave = 0
172 change = musicexp.KeySignatureChange()
174 change.tonic = start_pitch
177 def musicxml_attributes_to_lily (attrs):
180 'clef': musicxml_clef_to_lily,
181 'time': musicxml_time_to_lily,
182 'key': musicxml_key_to_lily
184 for (k, func) in attr_dispatch.items ():
185 children = attrs.get_named_children (k)
187 ## ugh: you get clefs spread over staves for piano
189 elts.append (func (attrs))
193 spanner_event_dict = {
194 'slur' : musicexp.SlurEvent,
195 'beam' : musicexp.BeamEvent,
196 'glissando' : musicexp.GlissandoEvent,
197 'pedal' : musicexp.PedalEvent,
198 'wavy-line' : musicexp.TrillSpanEvent,
199 'octave-shift' : musicexp.OctaveShiftEvent,
200 'wedge' : musicexp.HairpinEvent
202 spanner_type_dict = {
215 def musicxml_spanner_to_lily_event (mxl_event):
218 name = mxl_event.get_name()
219 func = spanner_event_dict.get (name)
223 error_message ('unknown span event %s' % mxl_event)
226 type = mxl_event.get_type ()
227 span_direction = spanner_type_dict.get (type)
228 # really check for None, because some types will be translated to 0, which
229 # would otherwise also lead to the unknown span warning
230 if span_direction != None:
231 ev.span_direction = span_direction
233 error_message ('unknown span type %s for %s' % (type, name))
235 ev.set_span_type (type)
236 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
238 # assign the size, which is used for octave-shift, etc.
239 ev.size = mxl_event.get_size ()
243 def musicxml_direction_to_indicator (direction):
244 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
246 def musicxml_fermata_to_lily_event (mxl_event):
247 ev = musicexp.ArticulationEvent ()
249 if hasattr (mxl_event, 'type'):
250 dir = musicxml_direction_to_indicator (mxl_event.type)
252 ev.force_direction = dir
255 def musicxml_tremolo_to_lily_event (mxl_event):
256 if mxl_event.get_name () != "tremolo":
258 ev = musicexp.TremoloEvent ()
259 ev.bars = mxl_event.get_text ()
262 def musicxml_bend_to_lily_event (mxl_event):
263 if mxl_event.get_name () != "bend":
265 ev = musicexp.BendEvent ()
266 ev.alter = mxl_event.bend_alter ()
270 short_articulations_dict = {
274 "staccatissimo": "|",
276 "strong-accent": "^",
277 #"portato": "_", # does not exist in MusicXML
278 #"fingering": "", # fingering is special cased, as get_text() will be the event's name
280 # TODO: Some translations are missing!
281 articulations_dict = {
283 "trill-mark": "trill",
285 #"delayed-turn": "?",
286 "inverted-turn": "reverseturn",
289 "mordent": "mordent",
290 "inverted-mordent": "prall",
294 "down-bow": "downbow",
295 "harmonic": "flageolet",
297 #"thumb-position": "",
299 #"double-tongue": "",
300 #"triple-tongue": "",
301 #"snap-pizzicato": "",
306 #"bend": "bendAfter #%s", # bend is special-cased, as we need to process the bend-alter subelement!
312 #"detached-legato": "",
318 "breath-mark": "breathe",
319 #"caesura": "caesura",
323 articulation_spanners = [ "wavy-line" ]
325 def musicxml_articulation_to_lily_event (mxl_event):
326 # wavy-line elements are treated as trill spanners, not as articulation ornaments
327 if mxl_event.get_name () in articulation_spanners:
328 return musicxml_spanner_to_lily_event (mxl_event)
330 # special case, because of the bend-alter subelement
331 if mxl_event.get_name() == "bend":
332 return musicxml_bend_to_lily_event (mxl_event)
334 # If we can write a shorthand, use them!
335 if mxl_event.get_name() == "fingering":
336 ev = musicexp.ShortArticulationEvent ()
337 tp = mxl_event.get_text()
338 # In all other cases, use the dicts to translate the xml tag name to a proper lilypond command
339 elif short_articulations_dict.get (mxl_event.get_name ()):
340 ev = musicexp.ShortArticulationEvent ()
341 tp = short_articulations_dict.get (mxl_event.get_name ())
343 ev = musicexp.ArticulationEvent ()
344 tp = articulations_dict.get (mxl_event.get_name ())
351 # Some articulations use the type attribute, other the placement...
353 if hasattr (mxl_event, 'type'):
354 dir = musicxml_direction_to_indicator (mxl_event.type)
355 if hasattr (mxl_event, 'placement'):
356 dir = musicxml_direction_to_indicator (mxl_event.placement)
357 # \breathe cannot have any direction modifier (^, _, -)!
358 if dir and tp != "breathe":
359 ev.force_direction = dir
363 def musicxml_dynamics_to_lily_event (dynentry):
364 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
365 "f", "ff", "fff", "ffff", "fffff", "ffffff",
366 "mp", "mf", "sf", "sfp", "sfpp", "fp",
367 "rf", "rfz", "sfz", "sffz", "fz" )
368 if not dynentry.get_name() in dynamics_available:
370 event = musicexp.DynamicsEvent ()
371 event.type = dynentry.get_name ()
375 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
377 def musicxml_direction_to_lily (n):
378 # TODO: Handle the <staff> element!
380 dirtype_children = []
381 for dt in n.get_typed_children (musicxml.DirType):
382 dirtype_children += dt.get_all_children ()
384 for entry in dirtype_children:
385 if entry.get_name () == "dynamics":
386 for dynentry in entry.get_all_children ():
387 ev = musicxml_dynamics_to_lily_event (dynentry)
391 # octave shifts. pedal marks, hairpins etc. are spanners:
392 if entry.get_name() in direction_spanners:
393 event = musicxml_spanner_to_lily_event (entry)
400 instrument_drumtype_dict = {
401 'Acoustic Snare Drum': 'acousticsnare',
402 'Side Stick': 'sidestick',
403 'Open Triangle': 'opentriangle',
404 'Mute Triangle': 'mutetriangle',
405 'Tambourine': 'tambourine'
408 def musicxml_note_to_lily_main_event (n):
412 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
415 pitch = musicxml_pitch_to_lily (mxl_pitch)
416 event = musicexp.NoteEvent()
419 acc = n.get_maybe_exist_named_child ('accidental')
421 # let's not force accs everywhere.
422 event.cautionary = acc.editorial
424 elif n.get_maybe_exist_typed_child (musicxml.Rest):
425 # rests can have display-octave and display-step, which are
426 # treated like an ordinary note pitch
427 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
428 event = musicexp.RestEvent()
429 pitch = musicxml_restdisplay_to_lily (rest)
431 elif n.instrument_name:
432 event = musicexp.NoteEvent ()
433 drum_type = instrument_drumtype_dict.get (n.instrument_name)
435 event.drum_type = drum_type
437 n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
438 event.drum_type = 'acousticsnare'
441 n.message ("cannot find suitable event")
443 event.duration = musicxml_duration_to_lily (n)
449 def __init__ (self, here, dest):
453 class LilyPondVoiceBuilder:
456 self.pending_dynamics = []
457 self.end_moment = Rational (0)
458 self.begin_moment = Rational (0)
459 self.pending_multibar = Rational (0)
461 def _insert_multibar (self):
462 r = musicexp.MultiMeasureRest ()
463 r.duration = musicexp.Duration()
464 r.duration.duration_log = 0
465 r.duration.factor = self.pending_multibar
466 self.elements.append (r)
467 self.begin_moment = self.end_moment
468 self.end_moment = self.begin_moment + self.pending_multibar
469 self.pending_multibar = Rational (0)
471 def add_multibar_rest (self, duration):
472 self.pending_multibar += duration
474 def set_duration (self, duration):
475 self.end_moment = self.begin_moment + duration
476 def current_duration (self):
477 return self.end_moment - self.begin_moment
479 def add_music (self, music, duration):
480 assert isinstance (music, musicexp.Music)
481 if self.pending_multibar > Rational (0):
482 self._insert_multibar ()
484 self.elements.append (music)
485 self.begin_moment = self.end_moment
486 self.set_duration (duration)
488 # Insert all pending dynamics right after the note/rest:
489 if duration > Rational (0):
490 for d in self.pending_dynamics:
491 self.elements.append (d)
492 self.pending_dynamics = []
494 # Insert some music command that does not affect the position in the measure
495 def add_command (self, command):
496 assert isinstance (command, musicexp.Music)
497 if self.pending_multibar > Rational (0):
498 self._insert_multibar ()
499 self.elements.append (command)
501 def add_dynamics (self, dynamic):
502 # store the dynamic item(s) until we encounter the next note/rest:
503 self.pending_dynamics.append (dynamic)
505 def add_bar_check (self, number):
506 b = musicexp.BarCheck ()
507 b.bar_number = number
508 self.add_music (b, Rational (0))
510 def jumpto (self, moment):
511 current_end = self.end_moment + self.pending_multibar
512 diff = moment - current_end
514 if diff < Rational (0):
515 error_message ('Negative skip %s' % diff)
518 if diff > Rational (0):
519 skip = musicexp.SkipEvent()
520 skip.duration.duration_log = 0
521 skip.duration.factor = diff
523 evc = musicexp.EventChord ()
524 evc.elements.append (skip)
525 self.add_music (evc, diff)
527 def last_event_chord (self, starting_at):
531 # if the position matches, find the last EventChord, do not cross a bar line!
532 at = len( self.elements ) - 1
534 not isinstance (self.elements[at], musicexp.EventChord) and
535 not isinstance (self.elements[at], musicexp.BarCheck)):
540 and isinstance (self.elements[at], musicexp.EventChord)
541 and self.begin_moment == starting_at):
542 value = self.elements[at]
544 self.jumpto (starting_at)
548 def correct_negative_skip (self, goto):
549 self.end_moment = goto
550 self.begin_moment = goto
551 evc = musicexp.EventChord ()
552 self.elements.append (evc)
554 def musicxml_voice_to_lily_voice (voice):
559 for k in voice.get_lyrics_numbers ():
562 voice_builder = LilyPondVoiceBuilder()
564 for n in voice._elements:
565 if n.get_name () == 'forward':
568 if isinstance (n, musicxml.Direction):
569 for a in musicxml_direction_to_lily (n):
570 if a.wait_for_note ():
571 voice_builder.add_dynamics (a)
573 voice_builder.add_command (a)
576 if not n.get_maybe_exist_named_child ('chord'):
578 voice_builder.jumpto (n._when)
579 except NegativeSkip, neg:
580 voice_builder.correct_negative_skip (n._when)
581 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
583 if isinstance (n, musicxml.Attributes):
584 if n.is_first () and n._measure_position == Rational (0):
586 number = int (n.get_parent ().number)
590 voice_builder.add_bar_check (number)
591 for a in musicxml_attributes_to_lily (n):
592 voice_builder.add_music (a, Rational (0))
595 if not n.__class__.__name__ == 'Note':
596 error_message ('not a Note or Attributes? %s' % n)
599 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
601 and rest.is_whole_measure ()):
603 voice_builder.add_multibar_rest (n._duration)
606 if n.is_first () and n._measure_position == Rational (0):
608 num = int (n.get_parent ().number)
611 voice_builder.add_bar_check (num)
613 main_event = musicxml_note_to_lily_main_event (n)
615 if hasattr (main_event, 'drum_type') and main_event.drum_type:
616 modes_found['drummode'] = True
619 ev_chord = voice_builder.last_event_chord (n._when)
621 ev_chord = musicexp.EventChord()
622 voice_builder.add_music (ev_chord, n._duration)
623 # When a note/chord has grace notes (duration==0), the duration of the
624 # event chord is not yet known, but the event chord was already added
625 # with duration 0. The following correct this when we hit the real note!
626 if voice_builder.current_duration () == 0 and n._duration > 0:
627 voice_builder.set_duration (n._duration)
628 if n.get_maybe_exist_typed_child (musicxml.Grace):
629 ev_chord.append_grace (main_event)
631 ev_chord.append (main_event)
633 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
637 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
638 # +tied | +slur | +tuplet | glissando | slide |
639 # ornaments | technical | articulations | dynamics |
640 # +fermata | arpeggiate | non-arpeggiate |
641 # accidental-mark | other-notation
643 if notations.get_tuplet():
644 tuplet_event = notations.get_tuplet()
645 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
648 frac = mod.get_fraction ()
650 tuplet_events.append ((ev_chord, tuplet_event, frac))
652 slurs = [s for s in notations.get_named_children ('slur')
653 if s.get_type () in ('start','stop')]
656 error_message ('more than 1 slur?')
658 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
659 ev_chord.append (lily_ev)
661 mxl_tie = notations.get_tie ()
662 if mxl_tie and mxl_tie.type == 'start':
663 ev_chord.append (musicexp.TieEvent ())
665 fermatas = notations.get_named_children ('fermata')
667 ev = musicxml_fermata_to_lily_event (a)
671 arpeggiate = notations.get_named_children ('arpeggiate')
673 ev_chord.append (musicexp.ArpeggioEvent ())
675 glissandos = notations.get_named_children ('glissando')
677 ev = musicxml_spanner_to_lily_event (a)
681 # Articulations can contain the following child elements:
682 # accent | strong-accent | staccato | tenuto |
683 # detached-legato | staccatissimo | spiccato |
684 # scoop | plop | doit | falloff | breath-mark |
685 # caesura | stress | unstress
686 # Technical can contain the following child elements:
687 # up-bow | down-bow | harmonic | open-string |
688 # thumb-position | fingering | pluck | double-tongue |
689 # triple-tongue | stopped | snap-pizzicato | fret |
690 # string | hammer-on | pull-off | bend | tap | heel |
691 # toe | fingernails | other-technical
692 # Ornaments can contain the following child elements:
693 # trill-mark | turn | delayed-turn | inverted-turn |
694 # shake | wavy-line | mordent | inverted-mordent |
695 # schleifer | tremolo | other-ornament, accidental-mark
696 ornaments = notations.get_named_children ('ornaments')
698 for ch in a.get_named_children ('tremolo'):
699 ev = musicxml_tremolo_to_lily_event (ch)
703 ornaments += notations.get_named_children ('articulations')
704 ornaments += notations.get_named_children ('technical')
707 for ch in a.get_all_children ():
708 ev = musicxml_articulation_to_lily_event (ch)
712 dynamics = notations.get_named_children ('dynamics')
714 for ch in a.get_all_children ():
715 ev = musicxml_dynamics_to_lily_event (ch)
720 note_lyrics_processed = []
721 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
722 for l in note_lyrics_elements:
723 if l.get_number () < 0:
724 for k in lyrics.keys ():
725 lyrics[k].append (l.lyric_to_text ())
726 note_lyrics_processed.append (k)
728 lyrics[l.number].append(l.lyric_to_text ())
729 note_lyrics_processed.append (l.number)
730 for lnr in lyrics.keys ():
731 if not lnr in note_lyrics_processed:
732 lyrics[lnr].append ("\skip4")
735 mxl_beams = [b for b in n.get_named_children ('beam')
736 if (b.get_type () in ('begin', 'end')
737 and b.is_primary ())]
739 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
741 ev_chord.append (beam_ev)
744 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
747 frac = mod.get_fraction ()
749 tuplet_events.append ((ev_chord, tuplet_event, frac))
751 ## force trailing mm rests to be written out.
752 voice_builder.add_music (musicexp.EventChord (), Rational (0))
754 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
756 seq_music = musicexp.SequentialMusic ()
758 if 'drummode' in modes_found.keys ():
759 ## \key <pitch> barfs in drummode.
760 ly_voice = [e for e in ly_voice
761 if not isinstance(e, musicexp.KeySignatureChange)]
763 seq_music.elements = ly_voice
765 for k in lyrics.keys ():
766 lyrics_dict[k] = musicexp.Lyrics ()
767 lyrics_dict[k].lyrics_syllables = lyrics[k]
770 if len (modes_found) > 1:
771 error_message ('Too many modes found %s' % modes_found.keys ())
773 return_value = seq_music
774 for mode in modes_found.keys ():
775 v = musicexp.ModeChangingMusicWrapper()
776 v.element = return_value
780 return (return_value, lyrics_dict)
783 def musicxml_id_to_lily (id):
784 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
785 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
788 d = digits.index (digit)
789 id = re.sub ('%d' % d, digit, id)
791 id = re.sub ('[^a-zA-Z]', 'X', id)
795 def musicxml_pitch_to_lily (mxl_pitch):
797 p.alteration = mxl_pitch.get_alteration ()
798 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
799 p.octave = mxl_pitch.get_octave () - 4
802 def musicxml_restdisplay_to_lily (mxl_rest):
804 step = mxl_rest.get_step ()
807 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
808 octave = mxl_rest.get_octave ()
810 p.octave = octave - 4
813 def voices_in_part (part):
814 """Return a Name -> Voice dictionary for PART"""
816 part.extract_voices ()
817 voice_dict = part.get_voices ()
821 def voices_in_part_in_parts (parts):
822 """return a Part -> Name -> Voice dictionary"""
823 return dict([(p, voices_in_part (p)) for p in parts])
826 def get_all_voices (parts):
827 all_voices = voices_in_part_in_parts (parts)
830 for p, name_voice in all_voices.items ():
833 for n, v in name_voice.items ():
834 progress ("Converting to LilyPond expressions...")
835 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
836 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
838 all_ly_voices[p] = part_ly_voices
843 def option_parser ():
844 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
845 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
847 _ ("""This program is free software. It is covered by the GNU General Public
848 License and you are welcome to change it and/or distribute copies of it
849 under certain conditions. Invoke as `%s --warranty' for more
850 information.""") % 'lilypond'
852 Copyright (c) 2005--2007 by
853 Han-Wen Nienhuys <hanwen@xs4all.nl> and
854 Jan Nieuwenhuizen <janneke@gnu.org>
856 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
857 p.add_option ('-v', '--verbose',
860 help=_ ("be verbose"))
862 p.add_option ('', '--lxml',
866 help=_ ("Use lxml.etree; uses less memory and cpu time."))
868 p.add_option ('-o', '--output',
874 help=_ ("set output filename to FILE"))
875 p.add_option_group ('bugs',
876 description=(_ ("Report bugs via")
877 + ''' http://post.gmane.org/post.php'''
878 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
881 def music_xml_voice_name_to_lily_name (part, name):
882 str = "Part%sVoice%s" % (part.id, name)
883 return musicxml_id_to_lily (str)
885 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
886 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
887 return musicxml_id_to_lily (str)
889 def print_voice_definitions (printer, part_list, voices):
891 for (part, nv_dict) in voices.items():
892 part_dict[part.id] = (part, nv_dict)
894 for part in part_list:
895 (part, nv_dict) = part_dict.get (part.id, (None, {}))
896 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
897 k = music_xml_voice_name_to_lily_name (part, name)
898 printer.dump ('%s = ' % k)
899 voice.print_ly (printer)
902 for l in lyrics.keys ():
903 lname = music_xml_lyrics_name_to_lily_name (part, name, l)
904 printer.dump ('%s = ' %lname )
905 lyrics[l].print_ly (printer)
910 return dict ([(elt,1) for elt in l]).keys ()
912 def print_score_setup (printer, part_list, voices):
913 part_dict = dict ([(p.id, p) for p in voices.keys ()])
917 for part_definition in part_list:
918 part_name = part_definition.id
919 part = part_dict.get (part_name)
921 error_message ('unknown part in part-list: %s' % part_name)
924 nv_dict = voices.get (part)
925 staves = reduce (lambda x,y: x+ y,
926 [mxlvoice._staves.keys ()
927 for (v, mxlvoice) in nv_dict.values ()],
931 staves = uniq_list (staves)
933 printer ('\\context PianoStaff << ')
937 staff_voices = [(music_xml_voice_name_to_lily_name (part, voice_name), voice_name, v)
938 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
939 if mxlvoice._start_staff == s]
941 printer ('\\context Staff = "%s" << ' % s)
943 for (v, voice_name, (music, lyrics)) in staff_voices:
944 printer ('\\context Voice = "%s" \\%s' % (v,v))
947 # Assign the lyrics to that voice
948 for l in lyrics.keys ():
949 ll = music_xml_lyrics_name_to_lily_name (part, voice_name, l)
950 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (v, ll))
961 printer ('\\new Staff <<')
963 for (n,v) in nv_dict.items ():
964 ((music, lyrics), voice) = v
965 nn = music_xml_voice_name_to_lily_name (part, n)
966 printer ('\\context Voice = "%s" \\%s' % (nn,nn))
968 # Assign the lyrics to that voice
969 for l in lyrics.keys ():
970 ll = music_xml_lyrics_name_to_lily_name (part, n, l)
971 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (nn, ll))
980 def print_ly_preamble (printer, filename):
981 printer.dump_version ()
982 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
984 def read_musicxml (filename, use_lxml):
988 tree = lxml.etree.parse (filename)
989 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
992 from xml.dom import minidom, Node
994 doc = minidom.parse(filename)
995 node = doc.documentElement
996 return musicxml.minidom_demarshal_node (node)
1001 def convert (filename, options):
1002 progress ("Reading MusicXML from %s ..." % filename)
1004 tree = read_musicxml (filename, options.use_lxml)
1007 id_instrument_map = {}
1008 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
1009 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1010 part_list = mxl_pl.get_named_children ("score-part")
1012 # score information is contained in the <work>, <identification> or <movement-title> tags
1013 score_information = extract_score_information (tree)
1014 parts = tree.get_typed_children (musicxml.Part)
1015 voices = get_all_voices (parts)
1017 if not options.output_name:
1018 options.output_name = os.path.basename (filename)
1019 options.output_name = os.path.splitext (options.output_name)[0]
1020 elif re.match (".*\.ly", options.output_name):
1021 options.output_name = os.path.splitext (options.output_name)[0]
1024 defs_ly_name = options.output_name + '-defs.ly'
1025 driver_ly_name = options.output_name + '.ly'
1027 printer = musicexp.Output_printer()
1028 progress ("Output to `%s'" % defs_ly_name)
1029 printer.set_file (open (defs_ly_name, 'w'))
1031 print_ly_preamble (printer, filename)
1032 print_ly_information (printer, score_information)
1033 print_voice_definitions (printer, part_list, voices)
1038 progress ("Output to `%s'" % driver_ly_name)
1039 printer = musicexp.Output_printer()
1040 printer.set_file (open (driver_ly_name, 'w'))
1041 print_ly_preamble (printer, filename)
1042 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1043 print_score_setup (printer, part_list, voices)
1048 def get_existing_filename_with_extension (filename, ext):
1049 if os.path.exists (filename):
1051 newfilename = filename + ".xml"
1052 if os.path.exists (newfilename):
1054 newfilename = filename + "xml"
1055 if os.path.exists (newfilename):
1060 opt_parser = option_parser()
1062 (options, args) = opt_parser.parse_args ()
1064 opt_parser.print_usage()
1067 # Allow the user to leave out the .xml or xml on the filename
1068 filename = get_existing_filename_with_extension (args[0], "xml")
1069 if filename and os.path.exists (filename):
1070 voices = convert (filename, options)
1072 progress ("Unable to find input file %s" % args[0])
1074 if __name__ == '__main__':