8 from gettext import gettext as _
19 from rational import Rational
23 sys.stderr.write (str + '\n')
27 # score information is contained in the <work>, <identification> or <movement-title> tags
28 # extract those into a hash, indexed by proper lilypond header attributes
29 def extract_score_information (tree):
30 score_information = {}
31 def set_if_exists (field, value):
33 score_information[field] = value
35 work = tree.get_maybe_exist_named_child ('work')
37 set_if_exists ('title', work.get_work_title ())
38 set_if_exists ('worknumber', work.get_work_number ())
39 set_if_exists ('opus', work.get_opus ())
41 movement_title = tree.get_maybe_exist_named_child ('movement-title')
43 set_if_exists ('title', movement_title.get_text ())
45 identifications = tree.get_named_children ('identification')
46 for ids in identifications:
47 set_if_exists ('copyright', ids.get_rights ())
48 set_if_exists ('composer', ids.get_composer ())
49 set_if_exists ('arranger', ids.get_arranger ())
50 set_if_exists ('editor', ids.get_editor ())
51 set_if_exists ('poet', ids.get_poet ())
53 set_if_exists ('tagline', ids.get_encoding_software ())
54 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
55 set_if_exists ('encodingdate', ids.get_encoding_date ())
56 set_if_exists ('encoder', ids.get_encoding_person ())
57 set_if_exists ('encodingdescription', ids.get_encoding_description ())
59 return score_information
62 def print_ly_information (printer, score_information):
63 printer.dump ('\header {')
65 for (k, text) in score_information.items ():
66 printer.dump ('%s = %s' % (k, musicxml.escape_ly_output_string (text)))
73 def musicxml_duration_to_lily (mxl_note):
74 d = musicexp.Duration ()
75 # if the note has no Type child, then that method spits out a warning and
76 # returns 0, i.e. a whole note
77 d.duration_log = mxl_note.get_duration_log ()
79 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
80 d.factor = mxl_note._duration / d.get_length ()
84 def group_tuplets (music_list, events):
87 """Collect Musics from
88 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
95 for (ev_chord, tuplet_elt, fraction) in events:
96 while (j < len (music_list)):
97 if music_list[j] == ev_chord:
100 if tuplet_elt.type == 'start':
101 indices.append ((j, None, fraction))
102 elif tuplet_elt.type == 'stop':
103 indices[-1] = (indices[-1][0], j, indices[-1][2])
107 for (i1, i2, frac) in indices:
111 new_list.extend (music_list[last:i1])
112 seq = musicexp.SequentialMusic ()
114 seq.elements = music_list[i1:last]
116 tsm = musicexp.TimeScaledMusic ()
119 tsm.numerator = frac[0]
120 tsm.denominator = frac[1]
122 new_list.append (tsm)
124 new_list.extend (music_list[last:])
128 def musicxml_clef_to_lily (attributes):
129 change = musicexp.ClefChange ()
130 (change.type, change.position, change.octave) = attributes.get_clef_information ()
133 def musicxml_time_to_lily (attributes):
134 (beats, type) = attributes.get_time_signature ()
136 change = musicexp.TimeSignatureChange()
137 change.fraction = (beats, type)
141 def musicxml_key_to_lily (attributes):
142 start_pitch = musicexp.Pitch ()
143 (fifths, mode) = attributes.get_key_signature ()
150 start_pitch.alteration = a
152 print 'unknown mode', mode
154 fifth = musicexp.Pitch()
161 for x in range (fifths):
162 start_pitch = start_pitch.transposed (fifth)
164 start_pitch.octave = 0
166 change = musicexp.KeySignatureChange()
168 change.tonic = start_pitch
171 def musicxml_attributes_to_lily (attrs):
174 'clef': musicxml_clef_to_lily,
175 'time': musicxml_time_to_lily,
176 'key': musicxml_key_to_lily
178 for (k, func) in attr_dispatch.items ():
179 children = attrs.get_named_children (k)
181 ## ugh: you get clefs spread over staves for piano
183 elts.append (func (attrs))
187 spanner_event_dict = {
188 'slur' : musicexp.SlurEvent,
189 'beam' : musicexp.BeamEvent,
190 'glissando' : musicexp.GlissandoEvent,
191 'pedal' : musicexp.PedalEvent,
192 'wavy-line' : musicexp.TrillSpanEvent,
193 'octave-shift' : musicexp.OctaveShiftEvent,
194 'wedge' : musicexp.HairpinEvent
196 spanner_type_dict = {
209 def musicxml_spanner_to_lily_event (mxl_event):
212 name = mxl_event.get_name()
213 func = spanner_event_dict.get (name)
217 print 'unknown span event ', mxl_event
220 type = mxl_event.get_type ()
221 span_direction = spanner_type_dict.get (type)
222 # really check for None, because some types will be translated to 0, which
223 # would otherwise also lead to the unknown span warning
224 if span_direction != None:
225 ev.span_direction = span_direction
227 print 'unknown span type', type, 'for', name
229 ev.set_span_type (type)
230 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
232 # assign the size, which is used for octave-shift, etc.
233 ev.size = mxl_event.get_size ()
237 def musicxml_direction_to_indicator (direction):
238 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
240 def musicxml_fermata_to_lily_event (mxl_event):
241 ev = musicexp.ArticulationEvent ()
243 if hasattr (mxl_event, 'type'):
244 dir = musicxml_direction_to_indicator (mxl_event.type)
246 ev.force_direction = dir
249 def musicxml_tremolo_to_lily_event (mxl_event):
250 if mxl_event.get_name () != "tremolo":
252 ev = musicexp.TremoloEvent ()
253 ev.bars = mxl_event.get_text ()
256 def musicxml_bend_to_lily_event (mxl_event):
257 if mxl_event.get_name () != "bend":
259 ev = musicexp.BendEvent ()
260 ev.alter = mxl_event.bend_alter ()
264 # TODO: Some translations are missing!
265 short_articulations_dict = {
269 "staccatissimo": "|",
271 "strong-accent": "^",
272 #"portato": "_", # does not exist in MusicXML
273 #"fingering": "", # fingering is special cased, as get_text() will be the event's name
275 articulations_dict = {
277 "trill-mark": "trill",
279 #"delayed-turn": "?",
280 "inverted-turn": "reverseturn",
283 "mordent": "mordent",
284 "inverted-mordent": "prall",
288 "down-bow": "downbow",
289 "harmonic": "flageolet",
291 #"thumb-position": "",
293 #"double-tongue": "",
294 #"triple-tongue": "",
295 #"snap-pizzicato": "",
300 #"bend": "bendAfter #%s", # bend is special-cased, as we need to process the bend-alter subelement!
306 #"detached-legato": "",
312 "breath-mark": "breathe",
313 #"caesura": "caesura",
317 articulation_spanners = [ "wavy-line" ]
319 def musicxml_articulation_to_lily_event (mxl_event):
320 # wavy-line elements are treated as trill spanners, not as articulation ornaments
321 if mxl_event.get_name () in articulation_spanners:
322 return musicxml_spanner_to_lily_event (mxl_event)
324 # special case, because of the bend-alter subelement
325 if mxl_event.get_name() == "bend":
326 return musicxml_bend_to_lily_event (mxl_event)
328 # If we can write a shorthand, use them!
329 if mxl_event.get_name() == "fingering":
330 ev = musicexp.ShortArticulationEvent ()
331 tp = mxl_event.get_text()
332 # In all other cases, use the dicts to translate the xml tag name to a proper lilypond command
333 elif short_articulations_dict.get (mxl_event.get_name ()):
334 ev = musicexp.ShortArticulationEvent ()
335 tp = short_articulations_dict.get (mxl_event.get_name ())
337 ev = musicexp.ArticulationEvent ()
338 tp = articulations_dict.get (mxl_event.get_name ())
345 # Some articulations use the type attribute, other the placement...
347 if hasattr (mxl_event, 'type'):
348 dir = musicxml_direction_to_indicator (mxl_event.type)
349 if hasattr (mxl_event, 'placement'):
350 dir = musicxml_direction_to_indicator (mxl_event.placement)
351 # \breathe cannot have any direction modifier (^, _, -)!
352 if dir and tp != "breathe":
353 ev.force_direction = dir
357 def musicxml_dynamics_to_lily_event (dynentry):
358 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
359 "f", "ff", "fff", "ffff", "fffff", "ffffff",
360 "mp", "mf", "sf", "sfp", "sfpp", "fp",
361 "rf", "rfz", "sfz", "sffz", "fz" )
362 if not dynentry.get_name() in dynamics_available:
364 event = musicexp.DynamicsEvent ()
365 event.type = dynentry.get_name ()
369 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
371 def musicxml_direction_to_lily (n):
372 # TODO: Handle the <staff> element!
374 dirtype_children = []
375 for dt in n.get_typed_children (musicxml.DirType):
376 dirtype_children += dt.get_all_children ()
378 for entry in dirtype_children:
379 if entry.get_name () == "dynamics":
380 for dynentry in entry.get_all_children ():
381 ev = musicxml_dynamics_to_lily_event (dynentry)
385 # octave shifts. pedal marks, hairpins etc. are spanners:
386 if entry.get_name() in direction_spanners:
387 event = musicxml_spanner_to_lily_event (entry)
394 instrument_drumtype_dict = {
395 'Acoustic Snare Drum': 'acousticsnare',
396 'Side Stick': 'sidestick',
397 'Open Triangle': 'opentriangle',
398 'Mute Triangle': 'mutetriangle',
399 'Tambourine': 'tambourine'
402 def musicxml_note_to_lily_main_event (n):
406 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
409 pitch = musicxml_pitch_to_lily (mxl_pitch)
410 event = musicexp.NoteEvent()
413 acc = n.get_maybe_exist_named_child ('accidental')
415 # let's not force accs everywhere.
416 event.cautionary = acc.editorial
418 elif n.get_maybe_exist_typed_child (musicxml.Rest):
419 event = musicexp.RestEvent()
420 elif n.instrument_name:
421 event = musicexp.NoteEvent ()
422 drum_type = instrument_drumtype_dict.get (n.instrument_name)
424 event.drum_type = drum_type
426 n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
427 event.drum_type = 'acousticsnare'
430 n.message ("cannot find suitable event")
432 event.duration = musicxml_duration_to_lily (n)
438 def __init__ (self, here, dest):
442 class LilyPondVoiceBuilder:
445 self.pending_dynamics = []
446 self.end_moment = Rational (0)
447 self.begin_moment = Rational (0)
448 self.pending_multibar = Rational (0)
450 def _insert_multibar (self):
451 r = musicexp.MultiMeasureRest ()
452 r.duration = musicexp.Duration()
453 r.duration.duration_log = 0
454 r.duration.factor = self.pending_multibar
455 self.elements.append (r)
456 self.begin_moment = self.end_moment
457 self.end_moment = self.begin_moment + self.pending_multibar
458 self.pending_multibar = Rational (0)
460 def add_multibar_rest (self, duration):
461 self.pending_multibar += duration
464 def add_music (self, music, duration):
465 assert isinstance (music, musicexp.Music)
466 if self.pending_multibar > Rational (0):
467 self._insert_multibar ()
469 self.elements.append (music)
470 self.begin_moment = self.end_moment
471 self.end_moment = self.begin_moment + duration
473 # Insert all pending dynamics right after the note/rest:
474 if duration > Rational (0):
475 for d in self.pending_dynamics:
476 self.elements.append (d)
477 self.pending_dynamics = []
479 # Insert some music command that does not affect the position in the measure
480 def add_command (self, command):
481 assert isinstance (command, musicexp.Music)
482 if self.pending_multibar > Rational (0):
483 self._insert_multibar ()
484 self.elements.append (command)
486 def add_dynamics (self, dynamic):
487 # store the dynamic item(s) until we encounter the next note/rest:
488 self.pending_dynamics.append (dynamic)
490 def add_bar_check (self, number):
491 b = musicexp.BarCheck ()
492 b.bar_number = number
493 self.add_music (b, Rational (0))
495 def jumpto (self, moment):
496 current_end = self.end_moment + self.pending_multibar
497 diff = moment - current_end
499 if diff < Rational (0):
500 print 'Negative skip', diff
503 if diff > Rational (0):
504 skip = musicexp.SkipEvent()
505 skip.duration.duration_log = 0
506 skip.duration.factor = diff
508 evc = musicexp.EventChord ()
509 evc.elements.append (skip)
510 self.add_music (evc, diff)
512 def last_event_chord (self, starting_at):
516 # if the position matches, find the last EventChord, do not cross a bar line!
517 at = len( self.elements ) - 1
519 not isinstance (self.elements[at], musicexp.EventChord) and
520 not isinstance (self.elements[at], musicexp.BarCheck)):
525 and isinstance (self.elements[at], musicexp.EventChord)
526 and self.begin_moment == starting_at):
527 value = self.elements[at]
529 self.jumpto (starting_at)
533 def correct_negative_skip (self, goto):
534 self.end_moment = goto
535 self.begin_moment = goto
536 evc = musicexp.EventChord ()
537 self.elements.append (evc)
539 def musicxml_voice_to_lily_voice (voice):
544 for k in voice.get_lyrics_numbers ():
547 voice_builder = LilyPondVoiceBuilder()
549 for n in voice._elements:
550 if n.get_name () == 'forward':
553 if isinstance (n, musicxml.Direction):
554 for a in musicxml_direction_to_lily (n):
555 if a.wait_for_note ():
556 voice_builder.add_dynamics (a)
558 voice_builder.add_command (a)
561 if not n.get_maybe_exist_named_child ('chord'):
563 voice_builder.jumpto (n._when)
564 except NegativeSkip, neg:
565 voice_builder.correct_negative_skip (n._when)
566 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
568 if isinstance (n, musicxml.Attributes):
569 if n.is_first () and n._measure_position == Rational (0):
571 number = int (n.get_parent ().number)
575 voice_builder.add_bar_check (number)
576 for a in musicxml_attributes_to_lily (n):
577 voice_builder.add_music (a, Rational (0))
580 if not n.__class__.__name__ == 'Note':
581 print 'not a Note or Attributes?', n
584 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
586 and rest.is_whole_measure ()):
588 voice_builder.add_multibar_rest (n._duration)
591 if n.is_first () and n._measure_position == Rational (0):
593 num = int (n.get_parent ().number)
596 voice_builder.add_bar_check (num)
598 main_event = musicxml_note_to_lily_main_event (n)
600 if hasattr (main_event, 'drum_type') and main_event.drum_type:
601 modes_found['drummode'] = True
604 ev_chord = voice_builder.last_event_chord (n._when)
606 ev_chord = musicexp.EventChord()
607 voice_builder.add_music (ev_chord, n._duration)
609 ev_chord.append (main_event)
611 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
615 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
616 # +tied | +slur | +tuplet | glissando | slide |
617 # ornaments | technical | articulations | dynamics |
618 # +fermata | arpeggiate | non-arpeggiate |
619 # accidental-mark | other-notation
621 if notations.get_tuplet():
622 tuplet_event = notations.get_tuplet()
623 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
626 frac = mod.get_fraction ()
628 tuplet_events.append ((ev_chord, tuplet_event, frac))
630 slurs = [s for s in notations.get_named_children ('slur')
631 if s.get_type () in ('start','stop')]
634 print 'more than 1 slur?'
636 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
637 ev_chord.append (lily_ev)
639 mxl_tie = notations.get_tie ()
640 if mxl_tie and mxl_tie.type == 'start':
641 ev_chord.append (musicexp.TieEvent ())
643 fermatas = notations.get_named_children ('fermata')
645 ev = musicxml_fermata_to_lily_event (a)
649 arpeggiate = notations.get_named_children ('arpeggiate')
651 ev_chord.append (musicexp.ArpeggioEvent ())
653 glissandos = notations.get_named_children ('glissando')
655 ev = musicxml_spanner_to_lily_event (a)
659 # Articulations can contain the following child elements:
660 # accent | strong-accent | staccato | tenuto |
661 # detached-legato | staccatissimo | spiccato |
662 # scoop | plop | doit | falloff | breath-mark |
663 # caesura | stress | unstress
664 # Technical can contain the following child elements:
665 # up-bow | down-bow | harmonic | open-string |
666 # thumb-position | fingering | pluck | double-tongue |
667 # triple-tongue | stopped | snap-pizzicato | fret |
668 # string | hammer-on | pull-off | bend | tap | heel |
669 # toe | fingernails | other-technical
670 # Ornaments can contain the following child elements:
671 # trill-mark | turn | delayed-turn | inverted-turn |
672 # shake | wavy-line | mordent | inverted-mordent |
673 # schleifer | tremolo | other-ornament, accidental-mark
674 ornaments = notations.get_named_children ('ornaments')
676 for ch in a.get_named_children ('tremolo'):
677 ev = musicxml_tremolo_to_lily_event (ch)
681 ornaments += notations.get_named_children ('articulations')
682 ornaments += notations.get_named_children ('technical')
685 for ch in a.get_all_children ():
686 ev = musicxml_articulation_to_lily_event (ch)
690 dynamics = notations.get_named_children ('dynamics')
692 for ch in a.get_all_children ():
693 ev = musicxml_dynamics_to_lily_event (ch)
698 note_lyrics_processed = []
699 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
700 for l in note_lyrics_elements:
701 if l.get_number () < 0:
702 for k in lyrics.keys ():
703 lyrics[k].append (l.lyric_to_text ())
704 note_lyrics_processed.append (k)
706 lyrics[l.number].append(l.lyric_to_text ())
707 note_lyrics_processed.append (l.number)
708 for lnr in lyrics.keys ():
709 if not lnr in note_lyrics_processed:
710 lyrics[lnr].append ("\skip4")
713 mxl_beams = [b for b in n.get_named_children ('beam')
714 if (b.get_type () in ('begin', 'end')
715 and b.is_primary ())]
717 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
719 ev_chord.append (beam_ev)
722 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
725 frac = mod.get_fraction ()
727 tuplet_events.append ((ev_chord, tuplet_event, frac))
729 ## force trailing mm rests to be written out.
730 voice_builder.add_music (musicexp.EventChord (), Rational (0))
732 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
734 seq_music = musicexp.SequentialMusic ()
736 if 'drummode' in modes_found.keys ():
737 ## \key <pitch> barfs in drummode.
738 ly_voice = [e for e in ly_voice
739 if not isinstance(e, musicexp.KeySignatureChange)]
741 seq_music.elements = ly_voice
743 for k in lyrics.keys ():
744 lyrics_dict[k] = musicexp.Lyrics ()
745 lyrics_dict[k].lyrics_syllables = lyrics[k]
748 if len (modes_found) > 1:
749 print 'Too many modes found', modes_found.keys ()
751 return_value = seq_music
752 for mode in modes_found.keys ():
753 v = musicexp.ModeChangingMusicWrapper()
754 v.element = return_value
758 return (return_value, lyrics_dict)
761 def musicxml_id_to_lily (id):
762 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
763 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
766 d = digits.index (digit)
767 id = re.sub ('%d' % d, digit, id)
769 id = re.sub ('[^a-zA-Z]', 'X', id)
773 def musicxml_pitch_to_lily (mxl_pitch):
775 p.alteration = mxl_pitch.get_alteration ()
776 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
777 p.octave = mxl_pitch.get_octave () - 4
780 def voices_in_part (part):
781 """Return a Name -> Voice dictionary for PART"""
783 part.extract_voices ()
784 voice_dict = part.get_voices ()
788 def voices_in_part_in_parts (parts):
789 """return a Part -> Name -> Voice dictionary"""
790 return dict([(p, voices_in_part (p)) for p in parts])
793 def get_all_voices (parts):
794 all_voices = voices_in_part_in_parts (parts)
797 for p, name_voice in all_voices.items ():
800 for n, v in name_voice.items ():
801 progress ("Converting to LilyPond expressions...")
802 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
803 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
805 all_ly_voices[p] = part_ly_voices
810 def option_parser ():
811 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
812 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
814 _ ("""This program is free software. It is covered by the GNU General Public
815 License and you are welcome to change it and/or distribute copies of it
816 under certain conditions. Invoke as `%s --warranty' for more
817 information.""") % 'lilypond'
819 Copyright (c) 2005--2007 by
820 Han-Wen Nienhuys <hanwen@xs4all.nl> and
821 Jan Nieuwenhuizen <janneke@gnu.org>
823 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
824 p.add_option ('-v', '--verbose',
827 help=_ ("be verbose"))
829 p.add_option ('', '--lxml',
833 help=_ ("Use lxml.etree; uses less memory and cpu time."))
835 p.add_option ('-o', '--output',
841 help=_ ("set output filename to FILE"))
842 p.add_option_group ('bugs',
843 description=(_ ("Report bugs via")
844 + ''' http://post.gmane.org/post.php'''
845 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
848 def music_xml_voice_name_to_lily_name (part, name):
849 str = "Part%sVoice%s" % (part.id, name)
850 return musicxml_id_to_lily (str)
852 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
853 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
854 return musicxml_id_to_lily (str)
856 def print_voice_definitions (printer, part_list, voices):
858 for (part, nv_dict) in voices.items():
859 part_dict[part.id] = (part, nv_dict)
861 for part in part_list:
862 (part, nv_dict) = part_dict.get (part.id, (None, {}))
863 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
864 k = music_xml_voice_name_to_lily_name (part, name)
865 printer.dump ('%s = ' % k)
866 voice.print_ly (printer)
869 for l in lyrics.keys ():
870 lname = music_xml_lyrics_name_to_lily_name (part, name, l)
871 printer.dump ('%s = ' %lname )
872 lyrics[l].print_ly (printer)
877 return dict ([(elt,1) for elt in l]).keys ()
879 def print_score_setup (printer, part_list, voices):
880 part_dict = dict ([(p.id, p) for p in voices.keys ()])
884 for part_definition in part_list:
885 part_name = part_definition.id
886 part = part_dict.get (part_name)
888 print 'unknown part in part-list:', part_name
891 # TODO: Apparently this is broken! There is always only one staff...
892 nv_dict = voices.get (part)
893 staves = reduce (lambda x,y: x+ y,
894 [mxlvoice._staves.keys ()
895 for (v, mxlvoice) in nv_dict.values ()],
899 staves = uniq_list (staves)
901 printer ('\\context PianoStaff << ')
905 staff_voices = [(music_xml_voice_name_to_lily_name (part, voice_name), voice_name, v)
906 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
907 if mxlvoice._start_staff == s]
909 printer ('\\context Staff = "%s" << ' % s)
911 for (v, voice_name, (music, lyrics)) in staff_voices:
912 printer ('\\context Voice = "%s" \\%s' % (v,v))
915 # Assign the lyrics to that voice
916 for l in lyrics.keys ():
917 ll = music_xml_lyrics_name_to_lily_name (part, voice_name, l)
918 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (v, ll))
929 printer ('\\new Staff <<')
931 for (n,v) in nv_dict.items ():
932 ((music, lyrics), voice) = v
933 nn = music_xml_voice_name_to_lily_name (part, n)
934 printer ('\\context Voice = "%s" \\%s' % (nn,nn))
936 # Assign the lyrics to that voice
937 for l in lyrics.keys ():
938 ll = music_xml_lyrics_name_to_lily_name (part, n, l)
939 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (nn, ll))
948 def print_ly_preamble (printer, filename):
949 printer.dump_version ()
950 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
952 def read_musicxml (filename, use_lxml):
956 tree = lxml.etree.parse (filename)
957 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
960 from xml.dom import minidom, Node
962 doc = minidom.parse(filename)
963 node = doc.documentElement
964 return musicxml.minidom_demarshal_node (node)
969 def convert (filename, options):
970 progress ("Reading MusicXML from %s ..." % filename)
972 tree = read_musicxml (filename, options.use_lxml)
975 id_instrument_map = {}
976 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
977 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
978 part_list = mxl_pl.get_named_children ("score-part")
980 # score information is contained in the <work>, <identification> or <movement-title> tags
981 score_information = extract_score_information (tree)
982 parts = tree.get_typed_children (musicxml.Part)
983 voices = get_all_voices (parts)
985 if not options.output_name:
986 options.output_name = os.path.basename (filename)
987 options.output_name = os.path.splitext (options.output_name)[0]
988 elif re.match (".*\.ly", options.output_name):
989 options.output_name = os.path.splitext (options.output_name)[0]
992 defs_ly_name = options.output_name + '-defs.ly'
993 driver_ly_name = options.output_name + '.ly'
995 printer = musicexp.Output_printer()
996 progress ("Output to `%s'" % defs_ly_name)
997 printer.set_file (open (defs_ly_name, 'w'))
999 print_ly_preamble (printer, filename)
1000 print_ly_information (printer, score_information)
1001 print_voice_definitions (printer, part_list, voices)
1006 progress ("Output to `%s'" % driver_ly_name)
1007 printer = musicexp.Output_printer()
1008 printer.set_file (open (driver_ly_name, 'w'))
1009 print_ly_preamble (printer, filename)
1010 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1011 print_score_setup (printer, part_list, voices)
1016 def get_existing_filename_with_extension (filename, ext):
1017 if os.path.exists (filename):
1019 newfilename = filename + ".xml"
1020 if os.path.exists (newfilename):
1022 newfilename = filename + "xml"
1023 if os.path.exists (newfilename):
1028 opt_parser = option_parser()
1030 (options, args) = opt_parser.parse_args ()
1032 opt_parser.print_usage()
1035 # Allow the user to leave out the .xml or xml on the filename
1036 filename = get_existing_filename_with_extension (args[0], "xml")
1037 if filename and os.path.exists (filename):
1038 voices = convert (filename, options)
1040 progress ("Unable to find input file %s" % args[0])
1042 if __name__ == '__main__':