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 d.factor = mxl_note._duration / d.get_length ()
87 def group_tuplets (music_list, events):
90 """Collect Musics from
91 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
98 for (ev_chord, tuplet_elt, fraction) in events:
99 while (j < len (music_list)):
100 if music_list[j] == ev_chord:
103 if tuplet_elt.type == 'start':
104 indices.append ((j, None, fraction))
105 elif tuplet_elt.type == 'stop':
106 indices[-1] = (indices[-1][0], j, indices[-1][2])
110 for (i1, i2, frac) in indices:
114 new_list.extend (music_list[last:i1])
115 seq = musicexp.SequentialMusic ()
117 seq.elements = music_list[i1:last]
119 tsm = musicexp.TimeScaledMusic ()
122 tsm.numerator = frac[0]
123 tsm.denominator = frac[1]
125 new_list.append (tsm)
127 new_list.extend (music_list[last:])
131 def musicxml_clef_to_lily (attributes):
132 change = musicexp.ClefChange ()
133 (change.type, change.position, change.octave) = attributes.get_clef_information ()
136 def musicxml_time_to_lily (attributes):
137 (beats, type) = attributes.get_time_signature ()
139 change = musicexp.TimeSignatureChange()
140 change.fraction = (beats, type)
144 def musicxml_key_to_lily (attributes):
145 start_pitch = musicexp.Pitch ()
146 (fifths, mode) = attributes.get_key_signature ()
153 start_pitch.alteration = a
155 error_message ('unknown mode %s' % mode)
157 fifth = musicexp.Pitch()
164 for x in range (fifths):
165 start_pitch = start_pitch.transposed (fifth)
167 start_pitch.octave = 0
169 change = musicexp.KeySignatureChange()
171 change.tonic = start_pitch
174 def musicxml_attributes_to_lily (attrs):
177 'clef': musicxml_clef_to_lily,
178 'time': musicxml_time_to_lily,
179 'key': musicxml_key_to_lily
181 for (k, func) in attr_dispatch.items ():
182 children = attrs.get_named_children (k)
184 ## ugh: you get clefs spread over staves for piano
186 elts.append (func (attrs))
190 spanner_event_dict = {
191 'slur' : musicexp.SlurEvent,
192 'beam' : musicexp.BeamEvent,
193 'glissando' : musicexp.GlissandoEvent,
194 'pedal' : musicexp.PedalEvent,
195 'wavy-line' : musicexp.TrillSpanEvent,
196 'octave-shift' : musicexp.OctaveShiftEvent,
197 'wedge' : musicexp.HairpinEvent
199 spanner_type_dict = {
212 def musicxml_spanner_to_lily_event (mxl_event):
215 name = mxl_event.get_name()
216 func = spanner_event_dict.get (name)
220 error_message ('unknown span event %s' % mxl_event)
223 type = mxl_event.get_type ()
224 span_direction = spanner_type_dict.get (type)
225 # really check for None, because some types will be translated to 0, which
226 # would otherwise also lead to the unknown span warning
227 if span_direction != None:
228 ev.span_direction = span_direction
230 error_message ('unknown span type %s for %s' % (type, name))
232 ev.set_span_type (type)
233 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
235 # assign the size, which is used for octave-shift, etc.
236 ev.size = mxl_event.get_size ()
240 def musicxml_direction_to_indicator (direction):
241 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
243 def musicxml_fermata_to_lily_event (mxl_event):
244 ev = musicexp.ArticulationEvent ()
246 if hasattr (mxl_event, 'type'):
247 dir = musicxml_direction_to_indicator (mxl_event.type)
249 ev.force_direction = dir
252 def musicxml_tremolo_to_lily_event (mxl_event):
253 if mxl_event.get_name () != "tremolo":
255 ev = musicexp.TremoloEvent ()
256 ev.bars = mxl_event.get_text ()
259 def musicxml_bend_to_lily_event (mxl_event):
260 if mxl_event.get_name () != "bend":
262 ev = musicexp.BendEvent ()
263 ev.alter = mxl_event.bend_alter ()
267 short_articulations_dict = {
271 "staccatissimo": "|",
273 "strong-accent": "^",
274 #"portato": "_", # does not exist in MusicXML
275 #"fingering": "", # fingering is special cased, as get_text() will be the event's name
277 # TODO: Some translations are missing!
278 articulations_dict = {
280 "trill-mark": "trill",
282 #"delayed-turn": "?",
283 "inverted-turn": "reverseturn",
286 "mordent": "mordent",
287 "inverted-mordent": "prall",
291 "down-bow": "downbow",
292 "harmonic": "flageolet",
294 #"thumb-position": "",
296 #"double-tongue": "",
297 #"triple-tongue": "",
298 #"snap-pizzicato": "",
303 #"bend": "bendAfter #%s", # bend is special-cased, as we need to process the bend-alter subelement!
309 #"detached-legato": "",
315 "breath-mark": "breathe",
316 #"caesura": "caesura",
320 articulation_spanners = [ "wavy-line" ]
322 def musicxml_articulation_to_lily_event (mxl_event):
323 # wavy-line elements are treated as trill spanners, not as articulation ornaments
324 if mxl_event.get_name () in articulation_spanners:
325 return musicxml_spanner_to_lily_event (mxl_event)
327 # special case, because of the bend-alter subelement
328 if mxl_event.get_name() == "bend":
329 return musicxml_bend_to_lily_event (mxl_event)
331 # If we can write a shorthand, use them!
332 if mxl_event.get_name() == "fingering":
333 ev = musicexp.ShortArticulationEvent ()
334 tp = mxl_event.get_text()
335 # In all other cases, use the dicts to translate the xml tag name to a proper lilypond command
336 elif short_articulations_dict.get (mxl_event.get_name ()):
337 ev = musicexp.ShortArticulationEvent ()
338 tp = short_articulations_dict.get (mxl_event.get_name ())
340 ev = musicexp.ArticulationEvent ()
341 tp = articulations_dict.get (mxl_event.get_name ())
348 # Some articulations use the type attribute, other the placement...
350 if hasattr (mxl_event, 'type'):
351 dir = musicxml_direction_to_indicator (mxl_event.type)
352 if hasattr (mxl_event, 'placement'):
353 dir = musicxml_direction_to_indicator (mxl_event.placement)
354 # \breathe cannot have any direction modifier (^, _, -)!
355 if dir and tp != "breathe":
356 ev.force_direction = dir
360 def musicxml_dynamics_to_lily_event (dynentry):
361 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
362 "f", "ff", "fff", "ffff", "fffff", "ffffff",
363 "mp", "mf", "sf", "sfp", "sfpp", "fp",
364 "rf", "rfz", "sfz", "sffz", "fz" )
365 if not dynentry.get_name() in dynamics_available:
367 event = musicexp.DynamicsEvent ()
368 event.type = dynentry.get_name ()
372 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
374 def musicxml_direction_to_lily (n):
375 # TODO: Handle the <staff> element!
377 dirtype_children = []
378 for dt in n.get_typed_children (musicxml.DirType):
379 dirtype_children += dt.get_all_children ()
381 for entry in dirtype_children:
382 if entry.get_name () == "dynamics":
383 for dynentry in entry.get_all_children ():
384 ev = musicxml_dynamics_to_lily_event (dynentry)
388 # octave shifts. pedal marks, hairpins etc. are spanners:
389 if entry.get_name() in direction_spanners:
390 event = musicxml_spanner_to_lily_event (entry)
397 instrument_drumtype_dict = {
398 'Acoustic Snare Drum': 'acousticsnare',
399 'Side Stick': 'sidestick',
400 'Open Triangle': 'opentriangle',
401 'Mute Triangle': 'mutetriangle',
402 'Tambourine': 'tambourine'
405 def musicxml_note_to_lily_main_event (n):
409 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
412 pitch = musicxml_pitch_to_lily (mxl_pitch)
413 event = musicexp.NoteEvent()
416 acc = n.get_maybe_exist_named_child ('accidental')
418 # let's not force accs everywhere.
419 event.cautionary = acc.editorial
421 elif n.get_maybe_exist_typed_child (musicxml.Rest):
422 event = musicexp.RestEvent()
423 elif n.instrument_name:
424 event = musicexp.NoteEvent ()
425 drum_type = instrument_drumtype_dict.get (n.instrument_name)
427 event.drum_type = drum_type
429 n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
430 event.drum_type = 'acousticsnare'
433 n.message ("cannot find suitable event")
435 event.duration = musicxml_duration_to_lily (n)
441 def __init__ (self, here, dest):
445 class LilyPondVoiceBuilder:
448 self.pending_dynamics = []
449 self.end_moment = Rational (0)
450 self.begin_moment = Rational (0)
451 self.pending_multibar = Rational (0)
453 def _insert_multibar (self):
454 r = musicexp.MultiMeasureRest ()
455 r.duration = musicexp.Duration()
456 r.duration.duration_log = 0
457 r.duration.factor = self.pending_multibar
458 self.elements.append (r)
459 self.begin_moment = self.end_moment
460 self.end_moment = self.begin_moment + self.pending_multibar
461 self.pending_multibar = Rational (0)
463 def add_multibar_rest (self, duration):
464 self.pending_multibar += duration
467 def add_music (self, music, duration):
468 assert isinstance (music, musicexp.Music)
469 if self.pending_multibar > Rational (0):
470 self._insert_multibar ()
472 self.elements.append (music)
473 self.begin_moment = self.end_moment
474 self.end_moment = self.begin_moment + duration
476 # Insert all pending dynamics right after the note/rest:
477 if duration > Rational (0):
478 for d in self.pending_dynamics:
479 self.elements.append (d)
480 self.pending_dynamics = []
482 # Insert some music command that does not affect the position in the measure
483 def add_command (self, command):
484 assert isinstance (command, musicexp.Music)
485 if self.pending_multibar > Rational (0):
486 self._insert_multibar ()
487 self.elements.append (command)
489 def add_dynamics (self, dynamic):
490 # store the dynamic item(s) until we encounter the next note/rest:
491 self.pending_dynamics.append (dynamic)
493 def add_bar_check (self, number):
494 b = musicexp.BarCheck ()
495 b.bar_number = number
496 self.add_music (b, Rational (0))
498 def jumpto (self, moment):
499 current_end = self.end_moment + self.pending_multibar
500 diff = moment - current_end
502 if diff < Rational (0):
503 error_message ('Negative skip %s' % diff)
506 if diff > Rational (0):
507 skip = musicexp.SkipEvent()
508 skip.duration.duration_log = 0
509 skip.duration.factor = diff
511 evc = musicexp.EventChord ()
512 evc.elements.append (skip)
513 self.add_music (evc, diff)
515 def last_event_chord (self, starting_at):
519 # if the position matches, find the last EventChord, do not cross a bar line!
520 at = len( self.elements ) - 1
522 not isinstance (self.elements[at], musicexp.EventChord) and
523 not isinstance (self.elements[at], musicexp.BarCheck)):
528 and isinstance (self.elements[at], musicexp.EventChord)
529 and self.begin_moment == starting_at):
530 value = self.elements[at]
532 self.jumpto (starting_at)
536 def correct_negative_skip (self, goto):
537 self.end_moment = goto
538 self.begin_moment = goto
539 evc = musicexp.EventChord ()
540 self.elements.append (evc)
542 def musicxml_voice_to_lily_voice (voice):
547 for k in voice.get_lyrics_numbers ():
550 voice_builder = LilyPondVoiceBuilder()
552 for n in voice._elements:
553 if n.get_name () == 'forward':
556 if isinstance (n, musicxml.Direction):
557 for a in musicxml_direction_to_lily (n):
558 if a.wait_for_note ():
559 voice_builder.add_dynamics (a)
561 voice_builder.add_command (a)
564 if not n.get_maybe_exist_named_child ('chord'):
566 voice_builder.jumpto (n._when)
567 except NegativeSkip, neg:
568 voice_builder.correct_negative_skip (n._when)
569 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
571 if isinstance (n, musicxml.Attributes):
572 if n.is_first () and n._measure_position == Rational (0):
574 number = int (n.get_parent ().number)
578 voice_builder.add_bar_check (number)
579 for a in musicxml_attributes_to_lily (n):
580 voice_builder.add_music (a, Rational (0))
583 if not n.__class__.__name__ == 'Note':
584 error_message ('not a Note or Attributes? %s' % n)
587 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
589 and rest.is_whole_measure ()):
591 voice_builder.add_multibar_rest (n._duration)
594 if n.is_first () and n._measure_position == Rational (0):
596 num = int (n.get_parent ().number)
599 voice_builder.add_bar_check (num)
601 main_event = musicxml_note_to_lily_main_event (n)
603 if hasattr (main_event, 'drum_type') and main_event.drum_type:
604 modes_found['drummode'] = True
607 ev_chord = voice_builder.last_event_chord (n._when)
609 ev_chord = musicexp.EventChord()
610 voice_builder.add_music (ev_chord, n._duration)
612 ev_chord.append (main_event)
614 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
618 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
619 # +tied | +slur | +tuplet | glissando | slide |
620 # ornaments | technical | articulations | dynamics |
621 # +fermata | arpeggiate | non-arpeggiate |
622 # accidental-mark | other-notation
624 if notations.get_tuplet():
625 tuplet_event = notations.get_tuplet()
626 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
629 frac = mod.get_fraction ()
631 tuplet_events.append ((ev_chord, tuplet_event, frac))
633 slurs = [s for s in notations.get_named_children ('slur')
634 if s.get_type () in ('start','stop')]
637 error_message ('more than 1 slur?')
639 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
640 ev_chord.append (lily_ev)
642 mxl_tie = notations.get_tie ()
643 if mxl_tie and mxl_tie.type == 'start':
644 ev_chord.append (musicexp.TieEvent ())
646 fermatas = notations.get_named_children ('fermata')
648 ev = musicxml_fermata_to_lily_event (a)
652 arpeggiate = notations.get_named_children ('arpeggiate')
654 ev_chord.append (musicexp.ArpeggioEvent ())
656 glissandos = notations.get_named_children ('glissando')
658 ev = musicxml_spanner_to_lily_event (a)
662 # Articulations can contain the following child elements:
663 # accent | strong-accent | staccato | tenuto |
664 # detached-legato | staccatissimo | spiccato |
665 # scoop | plop | doit | falloff | breath-mark |
666 # caesura | stress | unstress
667 # Technical can contain the following child elements:
668 # up-bow | down-bow | harmonic | open-string |
669 # thumb-position | fingering | pluck | double-tongue |
670 # triple-tongue | stopped | snap-pizzicato | fret |
671 # string | hammer-on | pull-off | bend | tap | heel |
672 # toe | fingernails | other-technical
673 # Ornaments can contain the following child elements:
674 # trill-mark | turn | delayed-turn | inverted-turn |
675 # shake | wavy-line | mordent | inverted-mordent |
676 # schleifer | tremolo | other-ornament, accidental-mark
677 ornaments = notations.get_named_children ('ornaments')
679 for ch in a.get_named_children ('tremolo'):
680 ev = musicxml_tremolo_to_lily_event (ch)
684 ornaments += notations.get_named_children ('articulations')
685 ornaments += notations.get_named_children ('technical')
688 for ch in a.get_all_children ():
689 ev = musicxml_articulation_to_lily_event (ch)
693 dynamics = notations.get_named_children ('dynamics')
695 for ch in a.get_all_children ():
696 ev = musicxml_dynamics_to_lily_event (ch)
701 note_lyrics_processed = []
702 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
703 for l in note_lyrics_elements:
704 if l.get_number () < 0:
705 for k in lyrics.keys ():
706 lyrics[k].append (l.lyric_to_text ())
707 note_lyrics_processed.append (k)
709 lyrics[l.number].append(l.lyric_to_text ())
710 note_lyrics_processed.append (l.number)
711 for lnr in lyrics.keys ():
712 if not lnr in note_lyrics_processed:
713 lyrics[lnr].append ("\skip4")
716 mxl_beams = [b for b in n.get_named_children ('beam')
717 if (b.get_type () in ('begin', 'end')
718 and b.is_primary ())]
720 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
722 ev_chord.append (beam_ev)
725 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
728 frac = mod.get_fraction ()
730 tuplet_events.append ((ev_chord, tuplet_event, frac))
732 ## force trailing mm rests to be written out.
733 voice_builder.add_music (musicexp.EventChord (), Rational (0))
735 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
737 seq_music = musicexp.SequentialMusic ()
739 if 'drummode' in modes_found.keys ():
740 ## \key <pitch> barfs in drummode.
741 ly_voice = [e for e in ly_voice
742 if not isinstance(e, musicexp.KeySignatureChange)]
744 seq_music.elements = ly_voice
746 for k in lyrics.keys ():
747 lyrics_dict[k] = musicexp.Lyrics ()
748 lyrics_dict[k].lyrics_syllables = lyrics[k]
751 if len (modes_found) > 1:
752 error_message ('Too many modes found %s' % modes_found.keys ())
754 return_value = seq_music
755 for mode in modes_found.keys ():
756 v = musicexp.ModeChangingMusicWrapper()
757 v.element = return_value
761 return (return_value, lyrics_dict)
764 def musicxml_id_to_lily (id):
765 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
766 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
769 d = digits.index (digit)
770 id = re.sub ('%d' % d, digit, id)
772 id = re.sub ('[^a-zA-Z]', 'X', id)
776 def musicxml_pitch_to_lily (mxl_pitch):
778 p.alteration = mxl_pitch.get_alteration ()
779 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
780 p.octave = mxl_pitch.get_octave () - 4
783 def voices_in_part (part):
784 """Return a Name -> Voice dictionary for PART"""
786 part.extract_voices ()
787 voice_dict = part.get_voices ()
791 def voices_in_part_in_parts (parts):
792 """return a Part -> Name -> Voice dictionary"""
793 return dict([(p, voices_in_part (p)) for p in parts])
796 def get_all_voices (parts):
797 all_voices = voices_in_part_in_parts (parts)
800 for p, name_voice in all_voices.items ():
803 for n, v in name_voice.items ():
804 progress ("Converting to LilyPond expressions...")
805 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
806 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
808 all_ly_voices[p] = part_ly_voices
813 def option_parser ():
814 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
815 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
817 _ ("""This program is free software. It is covered by the GNU General Public
818 License and you are welcome to change it and/or distribute copies of it
819 under certain conditions. Invoke as `%s --warranty' for more
820 information.""") % 'lilypond'
822 Copyright (c) 2005--2007 by
823 Han-Wen Nienhuys <hanwen@xs4all.nl> and
824 Jan Nieuwenhuizen <janneke@gnu.org>
826 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
827 p.add_option ('-v', '--verbose',
830 help=_ ("be verbose"))
832 p.add_option ('', '--lxml',
836 help=_ ("Use lxml.etree; uses less memory and cpu time."))
838 p.add_option ('-o', '--output',
844 help=_ ("set output filename to FILE"))
845 p.add_option_group ('bugs',
846 description=(_ ("Report bugs via")
847 + ''' http://post.gmane.org/post.php'''
848 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
851 def music_xml_voice_name_to_lily_name (part, name):
852 str = "Part%sVoice%s" % (part.id, name)
853 return musicxml_id_to_lily (str)
855 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
856 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
857 return musicxml_id_to_lily (str)
859 def print_voice_definitions (printer, part_list, voices):
861 for (part, nv_dict) in voices.items():
862 part_dict[part.id] = (part, nv_dict)
864 for part in part_list:
865 (part, nv_dict) = part_dict.get (part.id, (None, {}))
866 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
867 k = music_xml_voice_name_to_lily_name (part, name)
868 printer.dump ('%s = ' % k)
869 voice.print_ly (printer)
872 for l in lyrics.keys ():
873 lname = music_xml_lyrics_name_to_lily_name (part, name, l)
874 printer.dump ('%s = ' %lname )
875 lyrics[l].print_ly (printer)
880 return dict ([(elt,1) for elt in l]).keys ()
882 def print_score_setup (printer, part_list, voices):
883 part_dict = dict ([(p.id, p) for p in voices.keys ()])
887 for part_definition in part_list:
888 part_name = part_definition.id
889 part = part_dict.get (part_name)
891 error_message ('unknown part in part-list: %s' % part_name)
894 nv_dict = voices.get (part)
895 staves = reduce (lambda x,y: x+ y,
896 [mxlvoice._staves.keys ()
897 for (v, mxlvoice) in nv_dict.values ()],
901 staves = uniq_list (staves)
903 printer ('\\context PianoStaff << ')
907 staff_voices = [(music_xml_voice_name_to_lily_name (part, voice_name), voice_name, v)
908 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
909 if mxlvoice._start_staff == s]
911 printer ('\\context Staff = "%s" << ' % s)
913 for (v, voice_name, (music, lyrics)) in staff_voices:
914 printer ('\\context Voice = "%s" \\%s' % (v,v))
917 # Assign the lyrics to that voice
918 for l in lyrics.keys ():
919 ll = music_xml_lyrics_name_to_lily_name (part, voice_name, l)
920 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (v, ll))
931 printer ('\\new Staff <<')
933 for (n,v) in nv_dict.items ():
934 ((music, lyrics), voice) = v
935 nn = music_xml_voice_name_to_lily_name (part, n)
936 printer ('\\context Voice = "%s" \\%s' % (nn,nn))
938 # Assign the lyrics to that voice
939 for l in lyrics.keys ():
940 ll = music_xml_lyrics_name_to_lily_name (part, n, l)
941 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (nn, ll))
950 def print_ly_preamble (printer, filename):
951 printer.dump_version ()
952 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
954 def read_musicxml (filename, use_lxml):
958 tree = lxml.etree.parse (filename)
959 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
962 from xml.dom import minidom, Node
964 doc = minidom.parse(filename)
965 node = doc.documentElement
966 return musicxml.minidom_demarshal_node (node)
971 def convert (filename, options):
972 progress ("Reading MusicXML from %s ..." % filename)
974 tree = read_musicxml (filename, options.use_lxml)
977 id_instrument_map = {}
978 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
979 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
980 part_list = mxl_pl.get_named_children ("score-part")
982 # score information is contained in the <work>, <identification> or <movement-title> tags
983 score_information = extract_score_information (tree)
984 parts = tree.get_typed_children (musicxml.Part)
985 voices = get_all_voices (parts)
987 if not options.output_name:
988 options.output_name = os.path.basename (filename)
989 options.output_name = os.path.splitext (options.output_name)[0]
990 elif re.match (".*\.ly", options.output_name):
991 options.output_name = os.path.splitext (options.output_name)[0]
994 defs_ly_name = options.output_name + '-defs.ly'
995 driver_ly_name = options.output_name + '.ly'
997 printer = musicexp.Output_printer()
998 progress ("Output to `%s'" % defs_ly_name)
999 printer.set_file (open (defs_ly_name, 'w'))
1001 print_ly_preamble (printer, filename)
1002 print_ly_information (printer, score_information)
1003 print_voice_definitions (printer, part_list, voices)
1008 progress ("Output to `%s'" % driver_ly_name)
1009 printer = musicexp.Output_printer()
1010 printer.set_file (open (driver_ly_name, 'w'))
1011 print_ly_preamble (printer, filename)
1012 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1013 print_score_setup (printer, part_list, voices)
1018 def get_existing_filename_with_extension (filename, ext):
1019 if os.path.exists (filename):
1021 newfilename = filename + ".xml"
1022 if os.path.exists (newfilename):
1024 newfilename = filename + "xml"
1025 if os.path.exists (newfilename):
1030 opt_parser = option_parser()
1032 (options, args) = opt_parser.parse_args ()
1034 opt_parser.print_usage()
1037 # Allow the user to leave out the .xml or xml on the filename
1038 filename = get_existing_filename_with_extension (args[0], "xml")
1039 if filename and os.path.exists (filename):
1040 voices = convert (filename, options)
1042 progress ("Unable to find input file %s" % args[0])
1044 if __name__ == '__main__':