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 mxl_note.get_maybe_exist_typed_child (musicxml.Type):
76 d.duration_log = mxl_note.get_duration_log ()
80 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
81 d.factor = mxl_note._duration / d.get_length ()
85 def group_tuplets (music_list, events):
88 """Collect Musics from
89 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
96 for (ev_chord, tuplet_elt, fraction) in events:
97 while (j < len (music_list)):
98 if music_list[j] == ev_chord:
101 if tuplet_elt.type == 'start':
102 indices.append ((j, None, fraction))
103 elif tuplet_elt.type == 'stop':
104 indices[-1] = (indices[-1][0], j, indices[-1][2])
108 for (i1, i2, frac) in indices:
112 new_list.extend (music_list[last:i1])
113 seq = musicexp.SequentialMusic ()
115 seq.elements = music_list[i1:last]
117 tsm = musicexp.TimeScaledMusic ()
120 tsm.numerator = frac[0]
121 tsm.denominator = frac[1]
123 new_list.append (tsm)
125 new_list.extend (music_list[last:])
129 def musicxml_clef_to_lily (attributes):
130 change = musicexp.ClefChange ()
131 (change.type, change.position, change.octave) = attributes.get_clef_information ()
134 def musicxml_time_to_lily (attributes):
135 (beats, type) = attributes.get_time_signature ()
137 change = musicexp.TimeSignatureChange()
138 change.fraction = (beats, type)
142 def musicxml_key_to_lily (attributes):
143 start_pitch = musicexp.Pitch ()
144 (fifths, mode) = attributes.get_key_signature ()
151 start_pitch.alteration = a
153 print 'unknown mode', mode
155 fifth = musicexp.Pitch()
162 for x in range (fifths):
163 start_pitch = start_pitch.transposed (fifth)
165 start_pitch.octave = 0
167 change = musicexp.KeySignatureChange()
169 change.tonic = start_pitch
172 def musicxml_attributes_to_lily (attrs):
175 'clef': musicxml_clef_to_lily,
176 'time': musicxml_time_to_lily,
177 'key': musicxml_key_to_lily
179 for (k, func) in attr_dispatch.items ():
180 children = attrs.get_named_children (k)
182 ## ugh: you get clefs spread over staves for piano
184 elts.append (func (attrs))
188 spanner_event_dict = {
189 'slur' : musicexp.SlurEvent,
190 'beam' : musicexp.BeamEvent,
191 'glissando' : musicexp.GlissandoEvent,
192 'pedal' : musicexp.PedalEvent,
193 'wavy-line' : musicexp.TrillSpanEvent,
194 'octave-shift' : musicexp.OctaveShiftEvent
196 spanner_type_dict = {
204 spanner_line_type_dict = {
211 def musicxml_spanner_to_lily_event (mxl_event):
214 name = mxl_event.get_name()
215 func = spanner_event_dict.get (name)
219 print 'unknown span event ', mxl_event
222 key = mxl_event.get_type ()
223 span_direction = spanner_type_dict.get (key)
225 ev.span_direction = span_direction
227 print 'unknown span type', key, 'for', name
229 if hasattr (mxl_event, 'line-type'):
230 span_line_type = spanner_line_type_dict.get (getattr (mxl_event, 'line-type'))
232 ev.line_type = span_line_type
233 # assign the size, which is used for octave-shift, etc.
234 ev.size = mxl_event.get_size ()
238 def musicxml_direction_to_indicator (direction):
239 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
241 def musicxml_fermata_to_lily_event (mxl_event):
242 ev = musicexp.ArticulationEvent ()
244 if hasattr (mxl_event, 'type'):
245 dir = musicxml_direction_to_indicator (mxl_event.type)
247 ev.force_direction = dir
250 def musicxml_tremolo_to_lily_event (mxl_event):
251 if mxl_event.get_name () != "tremolo":
253 ev = musicexp.TremoloEvent ()
254 ev.bars = mxl_event.get_text ()
257 def musicxml_bend_to_lily_event (mxl_event):
258 if mxl_event.get_name () != "bend":
260 ev = musicexp.BendEvent ()
261 ev.alter = mxl_event.bend_alter ()
265 # TODO: Some translations are missing!
266 short_articulations_dict = {
270 "staccatissimo": "|",
272 "strong-accent": "^",
273 #"portato": "_", # does not exist in MusicXML
274 #"fingering": "", # fingering is special cased, as get_text() will be the event's name
276 articulations_dict = {
278 "trill-mark": "trill",
280 #"delayed-turn": "?",
281 "inverted-turn": "reverseturn",
284 "mordent": "mordent",
285 "inverted-mordent": "prall",
289 "down-bow": "downbow",
290 "harmonic": "flageolet",
292 #"thumb-position": "",
294 #"double-tongue": "",
295 #"triple-tongue": "",
296 #"snap-pizzicato": "",
301 #"bend": "bendAfter #%s", # bend is special-cased, as we need to process the bend-alter subelement!
307 #"detached-legato": "",
313 "breath-mark": "breathe",
314 #"caesura": "caesura",
318 articulation_spanners = [ "wavy-line" ]
320 def musicxml_articulation_to_lily_event (mxl_event):
321 # wavy-line elements are treated as trill spanners, not as articulation ornaments
322 if mxl_event.get_name () in articulation_spanners:
323 return musicxml_spanner_to_lily_event (mxl_event)
325 # special case, because of the bend-alter subelement
326 if mxl_event.get_name() == "bend":
327 return musicxml_bend_to_lily_event (mxl_event)
329 # If we can write a shorthand, use them!
330 if mxl_event.get_name() == "fingering":
331 ev = musicexp.ShortArticulationEvent ()
332 tp = mxl_event.get_text()
333 # In all other cases, use the dicts to translate the xml tag name to a proper lilypond command
334 elif short_articulations_dict.get (mxl_event.get_name ()):
335 ev = musicexp.ShortArticulationEvent ()
336 tp = short_articulations_dict.get (mxl_event.get_name ())
338 ev = musicexp.ArticulationEvent ()
339 tp = articulations_dict.get (mxl_event.get_name ())
346 # Some articulations use the type attribute, other the placement...
348 if hasattr (mxl_event, 'type'):
349 dir = musicxml_direction_to_indicator (mxl_event.type)
350 if hasattr (mxl_event, 'placement'):
351 dir = musicxml_direction_to_indicator (mxl_event.placement)
352 # \breathe cannot have any direction modifier (^, _, -)!
353 if dir and tp != "breathe":
354 ev.force_direction = dir
358 def musicxml_dynamics_to_lily_event (dynentry):
359 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
360 "f", "ff", "fff", "ffff", "fffff", "ffffff",
361 "mp", "mf", "sf", "sfp", "sfpp", "fp",
362 "rf", "rfz", "sfz", "sffz", "fz" )
363 if not dynentry.get_name() in dynamics_available:
365 event = musicexp.DynamicsEvent ()
366 event.type = dynentry.get_name ()
370 direction_spanners = [ 'octave-shift', 'pedal' ]
372 def musicxml_direction_to_lily (n):
373 # TODO: Handle the <staff> element!
375 dirtype_children = []
376 for dt in n.get_typed_children (musicxml.DirType):
377 dirtype_children += dt.get_all_children ()
379 for entry in dirtype_children:
380 if entry.get_name () == "dynamics":
381 for dynentry in entry.get_all_children ():
382 ev = musicxml_dynamics_to_lily_event (dynentry)
386 if entry.get_name() == "wedge":
387 if hasattr (entry, 'type'):
388 wedgetype = entry.type;
389 wedgetypeval = {"crescendo" : 1, "decrescendo" : -1,
390 "diminuendo" : -1, "stop" : 0 }.get (wedgetype)
391 # Really check for != None, becaus otherwise 0 will also cause
392 # the code to be executed!
393 if wedgetypeval != None:
394 event = musicexp.HairpinEvent (wedgetypeval)
398 # octave shifts. pedal marks etc. are spanners:
399 if entry.get_name() in direction_spanners:
400 event = musicxml_spanner_to_lily_event (entry)
407 instrument_drumtype_dict = {
408 'Acoustic Snare Drum': 'acousticsnare',
409 'Side Stick': 'sidestick',
410 'Open Triangle': 'opentriangle',
411 'Mute Triangle': 'mutetriangle',
412 'Tambourine': 'tambourine'
415 def musicxml_note_to_lily_main_event (n):
419 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
422 pitch = musicxml_pitch_to_lily (mxl_pitch)
423 event = musicexp.NoteEvent()
426 acc = n.get_maybe_exist_named_child ('accidental')
428 # let's not force accs everywhere.
429 event.cautionary = acc.editorial
431 elif n.get_maybe_exist_typed_child (musicxml.Rest):
432 event = musicexp.RestEvent()
433 elif n.instrument_name:
434 event = musicexp.NoteEvent ()
435 drum_type = instrument_drumtype_dict.get (n.instrument_name)
437 event.drum_type = drum_type
439 n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
440 event.drum_type = 'acousticsnare'
443 n.message ("cannot find suitable event")
445 event.duration = musicxml_duration_to_lily (n)
451 def __init__ (self, here, dest):
455 class LilyPondVoiceBuilder:
458 self.pending_dynamics = []
459 self.end_moment = Rational (0)
460 self.begin_moment = Rational (0)
461 self.pending_multibar = Rational (0)
463 def _insert_multibar (self):
464 r = musicexp.MultiMeasureRest ()
465 r.duration = musicexp.Duration()
466 r.duration.duration_log = 0
467 r.duration.factor = self.pending_multibar
468 self.elements.append (r)
469 self.begin_moment = self.end_moment
470 self.end_moment = self.begin_moment + self.pending_multibar
471 self.pending_multibar = Rational (0)
473 def add_multibar_rest (self, duration):
474 self.pending_multibar += duration
477 def add_music (self, music, duration):
478 assert isinstance (music, musicexp.Music)
479 if self.pending_multibar > Rational (0):
480 self._insert_multibar ()
482 self.elements.append (music)
483 self.begin_moment = self.end_moment
484 self.end_moment = self.begin_moment + duration
486 # Insert all pending dynamics right after the note/rest:
487 if duration > Rational (0):
488 for d in self.pending_dynamics:
489 self.elements.append (d)
490 self.pending_dynamics = []
492 def add_dynamics (self, dynamic):
493 # store the dynamic item(s) until we encounter the next note/rest:
494 self.pending_dynamics.append (dynamic)
496 def add_bar_check (self, number):
497 b = musicexp.BarCheck ()
498 b.bar_number = number
499 self.add_music (b, Rational (0))
501 def jumpto (self, moment):
502 current_end = self.end_moment + self.pending_multibar
503 diff = moment - current_end
505 if diff < Rational (0):
506 print 'Negative skip', diff
509 if diff > Rational (0):
510 skip = musicexp.SkipEvent()
511 skip.duration.duration_log = 0
512 skip.duration.factor = diff
514 evc = musicexp.EventChord ()
515 evc.elements.append (skip)
516 self.add_music (evc, diff)
518 def last_event_chord (self, starting_at):
522 and isinstance (self.elements[-1], musicexp.EventChord)
523 and self.begin_moment == starting_at):
524 value = self.elements[-1]
526 self.jumpto (starting_at)
531 def correct_negative_skip (self, goto):
532 self.end_moment = goto
533 self.begin_moment = goto
534 evc = musicexp.EventChord ()
535 self.elements.append (evc)
537 def musicxml_voice_to_lily_voice (voice):
542 for k in voice.get_lyrics_numbers ():
545 voice_builder = LilyPondVoiceBuilder()
547 for n in voice._elements:
548 if n.get_name () == 'forward':
551 if isinstance (n, musicxml.Direction):
552 for a in musicxml_direction_to_lily (n):
553 if a.wait_for_note ():
554 voice_builder.add_dynamics (a)
556 voice_builder.add_music (a, 0)
559 if not n.get_maybe_exist_named_child ('chord'):
561 voice_builder.jumpto (n._when)
562 except NegativeSkip, neg:
563 voice_builder.correct_negative_skip (n._when)
564 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
566 if isinstance (n, musicxml.Attributes):
567 if n.is_first () and n._measure_position == Rational (0):
569 number = int (n.get_parent ().number)
573 voice_builder.add_bar_check (number)
574 for a in musicxml_attributes_to_lily (n):
575 voice_builder.add_music (a, Rational (0))
578 if not n.__class__.__name__ == 'Note':
579 print 'not a Note or Attributes?', n
582 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
584 and rest.is_whole_measure ()):
586 voice_builder.add_multibar_rest (n._duration)
589 if n.is_first () and n._measure_position == Rational (0):
591 num = int (n.get_parent ().number)
594 voice_builder.add_bar_check (num)
596 main_event = musicxml_note_to_lily_main_event (n)
598 if hasattr (main_event, 'drum_type') and main_event.drum_type:
599 modes_found['drummode'] = True
602 ev_chord = voice_builder.last_event_chord (n._when)
604 ev_chord = musicexp.EventChord()
605 voice_builder.add_music (ev_chord, n._duration)
607 ev_chord.append (main_event)
609 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
613 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
614 # +tied | +slur | +tuplet | glissando | slide |
615 # ornaments | technical | articulations | dynamics |
616 # +fermata | arpeggiate | non-arpeggiate |
617 # accidental-mark | other-notation
619 if notations.get_tuplet():
620 tuplet_event = notations.get_tuplet()
621 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
624 frac = mod.get_fraction ()
626 tuplet_events.append ((ev_chord, tuplet_event, frac))
628 slurs = [s for s in notations.get_named_children ('slur')
629 if s.get_type () in ('start','stop')]
632 print 'more than 1 slur?'
634 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
635 ev_chord.append (lily_ev)
637 mxl_tie = notations.get_tie ()
638 if mxl_tie and mxl_tie.type == 'start':
639 ev_chord.append (musicexp.TieEvent ())
641 fermatas = notations.get_named_children ('fermata')
643 ev = musicxml_fermata_to_lily_event (a)
647 arpeggiate = notations.get_named_children ('arpeggiate')
649 ev_chord.append (musicexp.ArpeggioEvent ())
651 glissandos = notations.get_named_children ('glissando')
653 ev = musicxml_spanner_to_lily_event (a)
657 # Articulations can contain the following child elements:
658 # accent | strong-accent | staccato | tenuto |
659 # detached-legato | staccatissimo | spiccato |
660 # scoop | plop | doit | falloff | breath-mark |
661 # caesura | stress | unstress
662 # Technical can contain the following child elements:
663 # up-bow | down-bow | harmonic | open-string |
664 # thumb-position | fingering | pluck | double-tongue |
665 # triple-tongue | stopped | snap-pizzicato | fret |
666 # string | hammer-on | pull-off | bend | tap | heel |
667 # toe | fingernails | other-technical
668 # Ornaments can contain the following child elements:
669 # trill-mark | turn | delayed-turn | inverted-turn |
670 # shake | wavy-line | mordent | inverted-mordent |
671 # schleifer | tremolo | other-ornament, accidental-mark
672 ornaments = notations.get_named_children ('ornaments')
674 for ch in a.get_named_children ('tremolo'):
675 ev = musicxml_tremolo_to_lily_event (ch)
679 ornaments += notations.get_named_children ('articulations')
680 ornaments += notations.get_named_children ('technical')
683 for ch in a.get_all_children ():
684 ev = musicxml_articulation_to_lily_event (ch)
688 dynamics = notations.get_named_children ('dynamics')
690 for ch in a.get_all_children ():
691 ev = musicxml_dynamics_to_lily_event (ch)
696 note_lyrics_processed = []
697 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
698 for l in note_lyrics_elements:
699 if l.get_number () < 0:
700 for k in lyrics.keys ():
701 lyrics[k].append (l.lyric_to_text ())
702 note_lyrics_processed.append (k)
704 lyrics[l.number].append(l.lyric_to_text ())
705 note_lyrics_processed.append (l.number)
706 for lnr in lyrics.keys ():
707 if not lnr in note_lyrics_processed:
708 lyrics[lnr].append ("\"\"")
711 mxl_beams = [b for b in n.get_named_children ('beam')
712 if (b.get_type () in ('begin', 'end')
713 and b.is_primary ())]
715 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
717 ev_chord.append (beam_ev)
720 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
723 frac = mod.get_fraction ()
725 tuplet_events.append ((ev_chord, tuplet_event, frac))
727 ## force trailing mm rests to be written out.
728 voice_builder.add_music (musicexp.EventChord (), Rational (0))
730 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
732 seq_music = musicexp.SequentialMusic ()
734 if 'drummode' in modes_found.keys ():
735 ## \key <pitch> barfs in drummode.
736 ly_voice = [e for e in ly_voice
737 if not isinstance(e, musicexp.KeySignatureChange)]
739 seq_music.elements = ly_voice
741 for k in lyrics.keys ():
742 lyrics_dict[k] = musicexp.Lyrics ()
743 lyrics_dict[k].lyrics_syllables = lyrics[k]
746 if len (modes_found) > 1:
747 print 'Too many modes found', modes_found.keys ()
749 return_value = seq_music
750 for mode in modes_found.keys ():
751 v = musicexp.ModeChangingMusicWrapper()
752 v.element = return_value
756 return (return_value, lyrics_dict)
759 def musicxml_id_to_lily (id):
760 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
761 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
764 d = digits.index (digit)
765 id = re.sub ('%d' % d, digit, id)
767 id = re.sub ('[^a-zA-Z]', 'X', id)
771 def musicxml_pitch_to_lily (mxl_pitch):
773 p.alteration = mxl_pitch.get_alteration ()
774 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
775 p.octave = mxl_pitch.get_octave () - 4
778 def voices_in_part (part):
779 """Return a Name -> Voice dictionary for PART"""
781 part.extract_voices ()
782 voice_dict = part.get_voices ()
786 def voices_in_part_in_parts (parts):
787 """return a Part -> Name -> Voice dictionary"""
788 return dict([(p, voices_in_part (p)) for p in parts])
791 def get_all_voices (parts):
792 all_voices = voices_in_part_in_parts (parts)
795 for p, name_voice in all_voices.items ():
798 for n, v in name_voice.items ():
799 progress ("Converting to LilyPond expressions...")
800 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
801 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
803 all_ly_voices[p] = part_ly_voices
808 def option_parser ():
809 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
810 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
812 _ ("""This program is free software. It is covered by the GNU General Public
813 License and you are welcome to change it and/or distribute copies of it
814 under certain conditions. Invoke as `%s --warranty' for more
815 information.""") % 'lilypond'
817 Copyright (c) 2005--2007 by
818 Han-Wen Nienhuys <hanwen@xs4all.nl> and
819 Jan Nieuwenhuizen <janneke@gnu.org>
821 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
822 p.add_option ('-v', '--verbose',
825 help=_ ("be verbose"))
827 p.add_option ('', '--lxml',
831 help=_ ("Use lxml.etree; uses less memory and cpu time."))
833 p.add_option ('-o', '--output',
839 help=_ ("set output filename to FILE"))
840 p.add_option_group ('bugs',
841 description=(_ ("Report bugs via")
842 + ''' http://post.gmane.org/post.php'''
843 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
846 def music_xml_voice_name_to_lily_name (part, name):
847 str = "Part%sVoice%s" % (part.id, name)
848 return musicxml_id_to_lily (str)
850 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
851 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
852 return musicxml_id_to_lily (str)
854 def print_voice_definitions (printer, part_list, voices):
856 for (part, nv_dict) in voices.items():
857 part_dict[part.id] = (part, nv_dict)
859 for part in part_list:
860 (part, nv_dict) = part_dict.get (part.id, (None, {}))
861 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
862 k = music_xml_voice_name_to_lily_name (part, name)
863 printer.dump ('%s = ' % k)
864 voice.print_ly (printer)
867 for l in lyrics.keys ():
868 lname = music_xml_lyrics_name_to_lily_name (part, name, l)
869 printer.dump ('%s = ' %lname )
870 lyrics[l].print_ly (printer)
875 return dict ([(elt,1) for elt in l]).keys ()
877 def print_score_setup (printer, part_list, voices):
878 part_dict = dict ([(p.id, p) for p in voices.keys ()])
882 for part_definition in part_list:
883 part_name = part_definition.id
884 part = part_dict.get (part_name)
886 print 'unknown part in part-list:', part_name
889 # TODO: Apparently this is broken! There is always only one staff...
890 nv_dict = voices.get (part)
891 staves = reduce (lambda x,y: x+ y,
892 [mxlvoice._staves.keys ()
893 for (v, mxlvoice) in nv_dict.values ()],
897 staves = uniq_list (staves)
899 printer ('\\context PianoStaff << ')
903 staff_voices = [(music_xml_voice_name_to_lily_name (part, voice_name), voice_name, v)
904 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
905 if mxlvoice._start_staff == s]
907 printer ('\\context Staff = "%s" << ' % s)
909 for (v, voice_name, (music, lyrics)) in staff_voices:
910 printer ('\\context Voice = "%s" \\%s' % (v,v))
913 # Assign the lyrics to that voice
914 for l in lyrics.keys ():
915 ll = music_xml_lyrics_name_to_lily_name (part, voice_name, l)
916 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (v, ll))
927 printer ('\\new Staff <<')
929 for (n,v) in nv_dict.items ():
930 ((music, lyrics), voice) = v
931 nn = music_xml_voice_name_to_lily_name (part, n)
932 printer ('\\context Voice = "%s" \\%s' % (nn,nn))
934 # Assign the lyrics to that voice
935 for l in lyrics.keys ():
936 ll = music_xml_lyrics_name_to_lily_name (part, n, l)
937 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (nn, ll))
946 def print_ly_preamble (printer, filename):
947 printer.dump_version ()
948 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
950 def read_musicxml (filename, use_lxml):
954 tree = lxml.etree.parse (filename)
955 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
958 from xml.dom import minidom, Node
960 doc = minidom.parse(filename)
961 node = doc.documentElement
962 return musicxml.minidom_demarshal_node (node)
967 def convert (filename, options):
968 progress ("Reading MusicXML from %s ..." % filename)
970 tree = read_musicxml (filename, options.use_lxml)
973 id_instrument_map = {}
974 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
975 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
976 part_list = mxl_pl.get_named_children ("score-part")
978 # score information is contained in the <work>, <identification> or <movement-title> tags
979 score_information = extract_score_information (tree)
980 parts = tree.get_typed_children (musicxml.Part)
981 voices = get_all_voices (parts)
983 if not options.output_name:
984 options.output_name = os.path.basename (filename)
985 options.output_name = os.path.splitext (options.output_name)[0]
988 defs_ly_name = options.output_name + '-defs.ly'
989 driver_ly_name = options.output_name + '.ly'
991 printer = musicexp.Output_printer()
992 progress ("Output to `%s'" % defs_ly_name)
993 printer.set_file (open (defs_ly_name, 'w'))
995 print_ly_preamble (printer, filename)
996 print_ly_information (printer, score_information)
997 print_voice_definitions (printer, part_list, voices)
1002 progress ("Output to `%s'" % driver_ly_name)
1003 printer = musicexp.Output_printer()
1004 printer.set_file (open (driver_ly_name, 'w'))
1005 print_ly_preamble (printer, filename)
1006 printer.dump (r'\include "%s"' % defs_ly_name)
1007 print_score_setup (printer, part_list, voices)
1014 opt_parser = option_parser()
1016 (options, args) = opt_parser.parse_args ()
1018 opt_parser.print_usage()
1021 voices = convert (args[0], options)
1023 if __name__ == '__main__':