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 def add_dynamics (self, dynamic):
480 # store the dynamic item(s) until we encounter the next note/rest:
481 self.pending_dynamics.append (dynamic)
483 def add_bar_check (self, number):
484 b = musicexp.BarCheck ()
485 b.bar_number = number
486 self.add_music (b, Rational (0))
488 def jumpto (self, moment):
489 current_end = self.end_moment + self.pending_multibar
490 diff = moment - current_end
492 if diff < Rational (0):
493 print 'Negative skip', diff
496 if diff > Rational (0):
497 skip = musicexp.SkipEvent()
498 skip.duration.duration_log = 0
499 skip.duration.factor = diff
501 evc = musicexp.EventChord ()
502 evc.elements.append (skip)
503 self.add_music (evc, diff)
505 def last_event_chord (self, starting_at):
509 # if the position matches, find the last EventChord, do not cross a bar line!
510 at = len( self.elements ) - 1
512 not isinstance (self.elements[at], musicexp.EventChord) and
513 not isinstance (self.elements[at], musicexp.BarCheck)):
518 and isinstance (self.elements[at], musicexp.EventChord)
519 and self.begin_moment == starting_at):
520 value = self.elements[at]
522 self.jumpto (starting_at)
527 def correct_negative_skip (self, goto):
528 self.end_moment = goto
529 self.begin_moment = goto
530 evc = musicexp.EventChord ()
531 self.elements.append (evc)
533 def musicxml_voice_to_lily_voice (voice):
538 for k in voice.get_lyrics_numbers ():
541 voice_builder = LilyPondVoiceBuilder()
543 for n in voice._elements:
544 if n.get_name () == 'forward':
547 if isinstance (n, musicxml.Direction):
548 for a in musicxml_direction_to_lily (n):
549 if a.wait_for_note ():
550 voice_builder.add_dynamics (a)
552 voice_builder.add_music (a, 0)
555 if not n.get_maybe_exist_named_child ('chord'):
557 voice_builder.jumpto (n._when)
558 except NegativeSkip, neg:
559 voice_builder.correct_negative_skip (n._when)
560 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
562 if isinstance (n, musicxml.Attributes):
563 if n.is_first () and n._measure_position == Rational (0):
565 number = int (n.get_parent ().number)
569 voice_builder.add_bar_check (number)
570 for a in musicxml_attributes_to_lily (n):
571 voice_builder.add_music (a, Rational (0))
574 if not n.__class__.__name__ == 'Note':
575 print 'not a Note or Attributes?', n
578 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
580 and rest.is_whole_measure ()):
582 voice_builder.add_multibar_rest (n._duration)
585 if n.is_first () and n._measure_position == Rational (0):
587 num = int (n.get_parent ().number)
590 voice_builder.add_bar_check (num)
592 main_event = musicxml_note_to_lily_main_event (n)
594 if hasattr (main_event, 'drum_type') and main_event.drum_type:
595 modes_found['drummode'] = True
598 ev_chord = voice_builder.last_event_chord (n._when)
600 ev_chord = musicexp.EventChord()
601 voice_builder.add_music (ev_chord, n._duration)
603 ev_chord.append (main_event)
605 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
609 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
610 # +tied | +slur | +tuplet | glissando | slide |
611 # ornaments | technical | articulations | dynamics |
612 # +fermata | arpeggiate | non-arpeggiate |
613 # accidental-mark | other-notation
615 if notations.get_tuplet():
616 tuplet_event = notations.get_tuplet()
617 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
620 frac = mod.get_fraction ()
622 tuplet_events.append ((ev_chord, tuplet_event, frac))
624 slurs = [s for s in notations.get_named_children ('slur')
625 if s.get_type () in ('start','stop')]
628 print 'more than 1 slur?'
630 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
631 ev_chord.append (lily_ev)
633 mxl_tie = notations.get_tie ()
634 if mxl_tie and mxl_tie.type == 'start':
635 ev_chord.append (musicexp.TieEvent ())
637 fermatas = notations.get_named_children ('fermata')
639 ev = musicxml_fermata_to_lily_event (a)
643 arpeggiate = notations.get_named_children ('arpeggiate')
645 ev_chord.append (musicexp.ArpeggioEvent ())
647 glissandos = notations.get_named_children ('glissando')
649 ev = musicxml_spanner_to_lily_event (a)
653 # Articulations can contain the following child elements:
654 # accent | strong-accent | staccato | tenuto |
655 # detached-legato | staccatissimo | spiccato |
656 # scoop | plop | doit | falloff | breath-mark |
657 # caesura | stress | unstress
658 # Technical can contain the following child elements:
659 # up-bow | down-bow | harmonic | open-string |
660 # thumb-position | fingering | pluck | double-tongue |
661 # triple-tongue | stopped | snap-pizzicato | fret |
662 # string | hammer-on | pull-off | bend | tap | heel |
663 # toe | fingernails | other-technical
664 # Ornaments can contain the following child elements:
665 # trill-mark | turn | delayed-turn | inverted-turn |
666 # shake | wavy-line | mordent | inverted-mordent |
667 # schleifer | tremolo | other-ornament, accidental-mark
668 ornaments = notations.get_named_children ('ornaments')
670 for ch in a.get_named_children ('tremolo'):
671 ev = musicxml_tremolo_to_lily_event (ch)
675 ornaments += notations.get_named_children ('articulations')
676 ornaments += notations.get_named_children ('technical')
679 for ch in a.get_all_children ():
680 ev = musicxml_articulation_to_lily_event (ch)
684 dynamics = notations.get_named_children ('dynamics')
686 for ch in a.get_all_children ():
687 ev = musicxml_dynamics_to_lily_event (ch)
692 note_lyrics_processed = []
693 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
694 for l in note_lyrics_elements:
695 if l.get_number () < 0:
696 for k in lyrics.keys ():
697 lyrics[k].append (l.lyric_to_text ())
698 note_lyrics_processed.append (k)
700 lyrics[l.number].append(l.lyric_to_text ())
701 note_lyrics_processed.append (l.number)
702 for lnr in lyrics.keys ():
703 if not lnr in note_lyrics_processed:
704 lyrics[lnr].append ("\skip4")
707 mxl_beams = [b for b in n.get_named_children ('beam')
708 if (b.get_type () in ('begin', 'end')
709 and b.is_primary ())]
711 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
713 ev_chord.append (beam_ev)
716 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
719 frac = mod.get_fraction ()
721 tuplet_events.append ((ev_chord, tuplet_event, frac))
723 ## force trailing mm rests to be written out.
724 voice_builder.add_music (musicexp.EventChord (), Rational (0))
726 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
728 seq_music = musicexp.SequentialMusic ()
730 if 'drummode' in modes_found.keys ():
731 ## \key <pitch> barfs in drummode.
732 ly_voice = [e for e in ly_voice
733 if not isinstance(e, musicexp.KeySignatureChange)]
735 seq_music.elements = ly_voice
737 for k in lyrics.keys ():
738 lyrics_dict[k] = musicexp.Lyrics ()
739 lyrics_dict[k].lyrics_syllables = lyrics[k]
742 if len (modes_found) > 1:
743 print 'Too many modes found', modes_found.keys ()
745 return_value = seq_music
746 for mode in modes_found.keys ():
747 v = musicexp.ModeChangingMusicWrapper()
748 v.element = return_value
752 return (return_value, lyrics_dict)
755 def musicxml_id_to_lily (id):
756 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
757 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
760 d = digits.index (digit)
761 id = re.sub ('%d' % d, digit, id)
763 id = re.sub ('[^a-zA-Z]', 'X', id)
767 def musicxml_pitch_to_lily (mxl_pitch):
769 p.alteration = mxl_pitch.get_alteration ()
770 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
771 p.octave = mxl_pitch.get_octave () - 4
774 def voices_in_part (part):
775 """Return a Name -> Voice dictionary for PART"""
777 part.extract_voices ()
778 voice_dict = part.get_voices ()
782 def voices_in_part_in_parts (parts):
783 """return a Part -> Name -> Voice dictionary"""
784 return dict([(p, voices_in_part (p)) for p in parts])
787 def get_all_voices (parts):
788 all_voices = voices_in_part_in_parts (parts)
791 for p, name_voice in all_voices.items ():
794 for n, v in name_voice.items ():
795 progress ("Converting to LilyPond expressions...")
796 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
797 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
799 all_ly_voices[p] = part_ly_voices
804 def option_parser ():
805 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
806 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
808 _ ("""This program is free software. It is covered by the GNU General Public
809 License and you are welcome to change it and/or distribute copies of it
810 under certain conditions. Invoke as `%s --warranty' for more
811 information.""") % 'lilypond'
813 Copyright (c) 2005--2007 by
814 Han-Wen Nienhuys <hanwen@xs4all.nl> and
815 Jan Nieuwenhuizen <janneke@gnu.org>
817 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
818 p.add_option ('-v', '--verbose',
821 help=_ ("be verbose"))
823 p.add_option ('', '--lxml',
827 help=_ ("Use lxml.etree; uses less memory and cpu time."))
829 p.add_option ('-o', '--output',
835 help=_ ("set output filename to FILE"))
836 p.add_option_group ('bugs',
837 description=(_ ("Report bugs via")
838 + ''' http://post.gmane.org/post.php'''
839 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
842 def music_xml_voice_name_to_lily_name (part, name):
843 str = "Part%sVoice%s" % (part.id, name)
844 return musicxml_id_to_lily (str)
846 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
847 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
848 return musicxml_id_to_lily (str)
850 def print_voice_definitions (printer, part_list, voices):
852 for (part, nv_dict) in voices.items():
853 part_dict[part.id] = (part, nv_dict)
855 for part in part_list:
856 (part, nv_dict) = part_dict.get (part.id, (None, {}))
857 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
858 k = music_xml_voice_name_to_lily_name (part, name)
859 printer.dump ('%s = ' % k)
860 voice.print_ly (printer)
863 for l in lyrics.keys ():
864 lname = music_xml_lyrics_name_to_lily_name (part, name, l)
865 printer.dump ('%s = ' %lname )
866 lyrics[l].print_ly (printer)
871 return dict ([(elt,1) for elt in l]).keys ()
873 def print_score_setup (printer, part_list, voices):
874 part_dict = dict ([(p.id, p) for p in voices.keys ()])
878 for part_definition in part_list:
879 part_name = part_definition.id
880 part = part_dict.get (part_name)
882 print 'unknown part in part-list:', part_name
885 # TODO: Apparently this is broken! There is always only one staff...
886 nv_dict = voices.get (part)
887 staves = reduce (lambda x,y: x+ y,
888 [mxlvoice._staves.keys ()
889 for (v, mxlvoice) in nv_dict.values ()],
893 staves = uniq_list (staves)
895 printer ('\\context PianoStaff << ')
899 staff_voices = [(music_xml_voice_name_to_lily_name (part, voice_name), voice_name, v)
900 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
901 if mxlvoice._start_staff == s]
903 printer ('\\context Staff = "%s" << ' % s)
905 for (v, voice_name, (music, lyrics)) in staff_voices:
906 printer ('\\context Voice = "%s" \\%s' % (v,v))
909 # Assign the lyrics to that voice
910 for l in lyrics.keys ():
911 ll = music_xml_lyrics_name_to_lily_name (part, voice_name, l)
912 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (v, ll))
923 printer ('\\new Staff <<')
925 for (n,v) in nv_dict.items ():
926 ((music, lyrics), voice) = v
927 nn = music_xml_voice_name_to_lily_name (part, n)
928 printer ('\\context Voice = "%s" \\%s' % (nn,nn))
930 # Assign the lyrics to that voice
931 for l in lyrics.keys ():
932 ll = music_xml_lyrics_name_to_lily_name (part, n, l)
933 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (nn, ll))
942 def print_ly_preamble (printer, filename):
943 printer.dump_version ()
944 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
946 def read_musicxml (filename, use_lxml):
950 tree = lxml.etree.parse (filename)
951 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
954 from xml.dom import minidom, Node
956 doc = minidom.parse(filename)
957 node = doc.documentElement
958 return musicxml.minidom_demarshal_node (node)
963 def convert (filename, options):
964 progress ("Reading MusicXML from %s ..." % filename)
966 tree = read_musicxml (filename, options.use_lxml)
969 id_instrument_map = {}
970 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
971 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
972 part_list = mxl_pl.get_named_children ("score-part")
974 # score information is contained in the <work>, <identification> or <movement-title> tags
975 score_information = extract_score_information (tree)
976 parts = tree.get_typed_children (musicxml.Part)
977 voices = get_all_voices (parts)
979 if not options.output_name:
980 options.output_name = os.path.basename (filename)
981 options.output_name = os.path.splitext (options.output_name)[0]
982 elif re.match (".*\.ly", options.output_name):
983 options.output_name = os.path.splitext (options.output_name)[0]
986 defs_ly_name = options.output_name + '-defs.ly'
987 driver_ly_name = options.output_name + '.ly'
989 printer = musicexp.Output_printer()
990 progress ("Output to `%s'" % defs_ly_name)
991 printer.set_file (open (defs_ly_name, 'w'))
993 print_ly_preamble (printer, filename)
994 print_ly_information (printer, score_information)
995 print_voice_definitions (printer, part_list, voices)
1000 progress ("Output to `%s'" % driver_ly_name)
1001 printer = musicexp.Output_printer()
1002 printer.set_file (open (driver_ly_name, 'w'))
1003 print_ly_preamble (printer, filename)
1004 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1005 print_score_setup (printer, part_list, voices)
1010 def get_existing_filename_with_extension (filename, ext):
1011 if os.path.exists (filename):
1013 newfilename = filename + ".xml"
1014 if os.path.exists (newfilename):
1016 newfilename = filename + "xml"
1017 if os.path.exists (newfilename):
1022 opt_parser = option_parser()
1024 (options, args) = opt_parser.parse_args ()
1026 opt_parser.print_usage()
1029 # Allow the user to leave out the .xml or xml on the filename
1030 filename = get_existing_filename_with_extension (args[0], "xml")
1031 if filename and os.path.exists (filename):
1032 voices = convert (filename, options)
1034 progress ("Unable to find input file %s" % args[0])
1036 if __name__ == '__main__':