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 duration_log = mxl_note.get_duration_log ()
78 d.duration_log = mxl_note.get_duration_log ()
84 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
85 d.factor = mxl_note._duration / d.get_length ()
89 def group_tuplets (music_list, events):
92 """Collect Musics from
93 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
100 for (ev_chord, tuplet_elt, fraction) in events:
101 while (j < len (music_list)):
102 if music_list[j] == ev_chord:
105 if tuplet_elt.type == 'start':
106 indices.append ((j, None, fraction))
107 elif tuplet_elt.type == 'stop':
108 indices[-1] = (indices[-1][0], j, indices[-1][2])
112 for (i1, i2, frac) in indices:
116 new_list.extend (music_list[last:i1])
117 seq = musicexp.SequentialMusic ()
119 seq.elements = music_list[i1:last]
121 tsm = musicexp.TimeScaledMusic ()
124 tsm.numerator = frac[0]
125 tsm.denominator = frac[1]
127 new_list.append (tsm)
129 new_list.extend (music_list[last:])
133 def musicxml_clef_to_lily (attributes):
134 change = musicexp.ClefChange ()
135 (change.type, change.position, change.octave) = attributes.get_clef_information ()
138 def musicxml_time_to_lily (attributes):
139 (beats, type) = attributes.get_time_signature ()
141 change = musicexp.TimeSignatureChange()
142 change.fraction = (beats, type)
146 def musicxml_key_to_lily (attributes):
147 start_pitch = musicexp.Pitch ()
148 (fifths, mode) = attributes.get_key_signature ()
155 start_pitch.alteration = a
157 print 'unknown mode', mode
159 fifth = musicexp.Pitch()
166 for x in range (fifths):
167 start_pitch = start_pitch.transposed (fifth)
169 start_pitch.octave = 0
171 change = musicexp.KeySignatureChange()
173 change.tonic = start_pitch
176 def musicxml_attributes_to_lily (attrs):
179 'clef': musicxml_clef_to_lily,
180 'time': musicxml_time_to_lily,
181 'key': musicxml_key_to_lily
183 for (k, func) in attr_dispatch.items ():
184 children = attrs.get_named_children (k)
186 ## ugh: you get clefs spread over staves for piano
188 elts.append (func (attrs))
192 spanner_event_dict = {
193 'slur' : musicexp.SlurEvent,
194 'beam' : musicexp.BeamEvent,
195 'glissando' : musicexp.GlissandoEvent,
196 'pedal' : musicexp.PedalEvent,
197 'wavy-line' : musicexp.TrillSpanEvent,
198 'octave-shift' : musicexp.OctaveShiftEvent
200 spanner_type_dict = {
208 spanner_line_type_dict = {
215 def musicxml_spanner_to_lily_event (mxl_event):
218 name = mxl_event.get_name()
219 func = spanner_event_dict.get (name)
223 print 'unknown span event ', mxl_event
226 key = mxl_event.get_type ()
227 span_direction = spanner_type_dict.get (key)
229 ev.span_direction = span_direction
231 print 'unknown span type', key, 'for', name
233 if hasattr (mxl_event, 'line-type'):
234 span_line_type = spanner_line_type_dict.get (getattr (mxl_event, 'line-type'))
236 ev.line_type = span_line_type
237 # assign the size, which is used for octave-shift, etc.
238 ev.size = mxl_event.get_size ()
242 def musicxml_direction_to_indicator (direction):
243 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
245 def musicxml_fermata_to_lily_event (mxl_event):
246 ev = musicexp.ArticulationEvent ()
248 if hasattr (mxl_event, 'type'):
249 dir = musicxml_direction_to_indicator (mxl_event.type)
251 ev.force_direction = dir
254 def musicxml_tremolo_to_lily_event (mxl_event):
255 if mxl_event.get_name () != "tremolo":
257 ev = musicexp.TremoloEvent ()
258 ev.bars = mxl_event.get_text ()
261 def musicxml_bend_to_lily_event (mxl_event):
262 if mxl_event.get_name () != "bend":
264 ev = musicexp.BendEvent ()
265 ev.alter = mxl_event.bend_alter ()
269 # TODO: Some translations are missing!
270 short_articulations_dict = {
274 "staccatissimo": "|",
276 "strong-accent": "^",
277 #"portato": "_", # does not exist in MusicXML
278 #"fingering": "", # fingering is special cased, as get_text() will be the event's name
280 articulations_dict = {
282 "trill-mark": "trill",
284 #"delayed-turn": "?",
285 "inverted-turn": "reverseturn",
288 "mordent": "mordent",
289 "inverted-mordent": "prall",
293 "down-bow": "downbow",
294 "harmonic": "flageolet",
296 #"thumb-position": "",
298 #"double-tongue": "",
299 #"triple-tongue": "",
300 #"snap-pizzicato": "",
305 #"bend": "bendAfter #%s", # bend is special-cased, as we need to process the bend-alter subelement!
311 #"detached-legato": "",
317 "breath-mark": "breathe",
318 #"caesura": "caesura",
322 articulation_spanners = [ "wavy-line" ]
324 def musicxml_articulation_to_lily_event (mxl_event):
325 # wavy-line elements are treated as trill spanners, not as articulation ornaments
326 if mxl_event.get_name () in articulation_spanners:
327 return musicxml_spanner_to_lily_event (mxl_event)
329 # special case, because of the bend-alter subelement
330 if mxl_event.get_name() == "bend":
331 return musicxml_bend_to_lily_event (mxl_event)
333 # If we can write a shorthand, use them!
334 if mxl_event.get_name() == "fingering":
335 ev = musicexp.ShortArticulationEvent ()
336 tp = mxl_event.get_text()
337 # In all other cases, use the dicts to translate the xml tag name to a proper lilypond command
338 elif short_articulations_dict.get (mxl_event.get_name ()):
339 ev = musicexp.ShortArticulationEvent ()
340 tp = short_articulations_dict.get (mxl_event.get_name ())
342 ev = musicexp.ArticulationEvent ()
343 tp = articulations_dict.get (mxl_event.get_name ())
350 # Some articulations use the type attribute, other the placement...
352 if hasattr (mxl_event, 'type'):
353 dir = musicxml_direction_to_indicator (mxl_event.type)
354 if hasattr (mxl_event, 'placement'):
355 dir = musicxml_direction_to_indicator (mxl_event.placement)
356 # \breathe cannot have any direction modifier (^, _, -)!
357 if dir and tp != "breathe":
358 ev.force_direction = dir
362 def musicxml_dynamics_to_lily_event (dynentry):
363 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
364 "f", "ff", "fff", "ffff", "fffff", "ffffff",
365 "mp", "mf", "sf", "sfp", "sfpp", "fp",
366 "rf", "rfz", "sfz", "sffz", "fz" )
367 if not dynentry.get_name() in dynamics_available:
369 event = musicexp.DynamicsEvent ()
370 event.type = dynentry.get_name ()
374 direction_spanners = [ 'octave-shift', 'pedal' ]
376 def musicxml_direction_to_lily (n):
377 # TODO: Handle the <staff> element!
379 dirtype_children = []
380 for dt in n.get_typed_children (musicxml.DirType):
381 dirtype_children += dt.get_all_children ()
383 for entry in dirtype_children:
384 if entry.get_name () == "dynamics":
385 for dynentry in entry.get_all_children ():
386 ev = musicxml_dynamics_to_lily_event (dynentry)
390 if entry.get_name() == "wedge":
391 if hasattr (entry, 'type'):
392 wedgetype = entry.type;
393 wedgetypeval = {"crescendo" : 1, "decrescendo" : -1,
394 "diminuendo" : -1, "stop" : 0 }.get (wedgetype)
395 # Really check for != None, becaus otherwise 0 will also cause
396 # the code to be executed!
397 if wedgetypeval != None:
398 event = musicexp.HairpinEvent (wedgetypeval)
402 # octave shifts. pedal marks etc. are spanners:
403 if entry.get_name() in direction_spanners:
404 event = musicxml_spanner_to_lily_event (entry)
411 instrument_drumtype_dict = {
412 'Acoustic Snare Drum': 'acousticsnare',
413 'Side Stick': 'sidestick',
414 'Open Triangle': 'opentriangle',
415 'Mute Triangle': 'mutetriangle',
416 'Tambourine': 'tambourine'
419 def musicxml_note_to_lily_main_event (n):
423 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
426 pitch = musicxml_pitch_to_lily (mxl_pitch)
427 event = musicexp.NoteEvent()
430 acc = n.get_maybe_exist_named_child ('accidental')
432 # let's not force accs everywhere.
433 event.cautionary = acc.editorial
435 elif n.get_maybe_exist_typed_child (musicxml.Rest):
436 event = musicexp.RestEvent()
437 elif n.instrument_name:
438 event = musicexp.NoteEvent ()
439 drum_type = instrument_drumtype_dict.get (n.instrument_name)
441 event.drum_type = drum_type
443 n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
444 event.drum_type = 'acousticsnare'
447 n.message ("cannot find suitable event")
449 event.duration = musicxml_duration_to_lily (n)
455 def __init__ (self, here, dest):
459 class LilyPondVoiceBuilder:
462 self.pending_dynamics = []
463 self.end_moment = Rational (0)
464 self.begin_moment = Rational (0)
465 self.pending_multibar = Rational (0)
467 def _insert_multibar (self):
468 r = musicexp.MultiMeasureRest ()
469 r.duration = musicexp.Duration()
470 r.duration.duration_log = 0
471 r.duration.factor = self.pending_multibar
472 self.elements.append (r)
473 self.begin_moment = self.end_moment
474 self.end_moment = self.begin_moment + self.pending_multibar
475 self.pending_multibar = Rational (0)
477 def add_multibar_rest (self, duration):
478 self.pending_multibar += duration
481 def add_music (self, music, duration):
482 assert isinstance (music, musicexp.Music)
483 if self.pending_multibar > Rational (0):
484 self._insert_multibar ()
486 self.elements.append (music)
487 self.begin_moment = self.end_moment
488 self.end_moment = self.begin_moment + duration
490 # Insert all pending dynamics right after the note/rest:
491 if duration > Rational (0):
492 for d in self.pending_dynamics:
493 self.elements.append (d)
494 self.pending_dynamics = []
496 def add_dynamics (self, dynamic):
497 # store the dynamic item(s) until we encounter the next note/rest:
498 self.pending_dynamics.append (dynamic)
500 def add_bar_check (self, number):
501 b = musicexp.BarCheck ()
502 b.bar_number = number
503 self.add_music (b, Rational (0))
505 def jumpto (self, moment):
506 current_end = self.end_moment + self.pending_multibar
507 diff = moment - current_end
509 if diff < Rational (0):
510 print 'Negative skip', diff
513 if diff > Rational (0):
514 skip = musicexp.SkipEvent()
515 skip.duration.duration_log = 0
516 skip.duration.factor = diff
518 evc = musicexp.EventChord ()
519 evc.elements.append (skip)
520 self.add_music (evc, diff)
522 def last_event_chord (self, starting_at):
526 # if the position matches, find the last EventChord, do not cross a bar line!
527 at = len( self.elements ) - 1
529 not isinstance (self.elements[at], musicexp.EventChord) and
530 not isinstance (self.elements[at], musicexp.BarCheck)):
535 and isinstance (self.elements[at], musicexp.EventChord)
536 and self.begin_moment == starting_at):
537 value = self.elements[at]
539 self.jumpto (starting_at)
544 def correct_negative_skip (self, goto):
545 self.end_moment = goto
546 self.begin_moment = goto
547 evc = musicexp.EventChord ()
548 self.elements.append (evc)
550 def musicxml_voice_to_lily_voice (voice):
555 for k in voice.get_lyrics_numbers ():
558 voice_builder = LilyPondVoiceBuilder()
560 for n in voice._elements:
561 if n.get_name () == 'forward':
564 if isinstance (n, musicxml.Direction):
565 for a in musicxml_direction_to_lily (n):
566 if a.wait_for_note ():
567 voice_builder.add_dynamics (a)
569 voice_builder.add_music (a, 0)
572 if not n.get_maybe_exist_named_child ('chord'):
574 voice_builder.jumpto (n._when)
575 except NegativeSkip, neg:
576 voice_builder.correct_negative_skip (n._when)
577 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
579 if isinstance (n, musicxml.Attributes):
580 if n.is_first () and n._measure_position == Rational (0):
582 number = int (n.get_parent ().number)
586 voice_builder.add_bar_check (number)
587 for a in musicxml_attributes_to_lily (n):
588 voice_builder.add_music (a, Rational (0))
591 if not n.__class__.__name__ == 'Note':
592 print 'not a Note or Attributes?', n
595 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
597 and rest.is_whole_measure ()):
599 voice_builder.add_multibar_rest (n._duration)
602 if n.is_first () and n._measure_position == Rational (0):
604 num = int (n.get_parent ().number)
607 voice_builder.add_bar_check (num)
609 main_event = musicxml_note_to_lily_main_event (n)
611 if hasattr (main_event, 'drum_type') and main_event.drum_type:
612 modes_found['drummode'] = True
615 ev_chord = voice_builder.last_event_chord (n._when)
617 ev_chord = musicexp.EventChord()
618 voice_builder.add_music (ev_chord, n._duration)
620 ev_chord.append (main_event)
622 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
626 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
627 # +tied | +slur | +tuplet | glissando | slide |
628 # ornaments | technical | articulations | dynamics |
629 # +fermata | arpeggiate | non-arpeggiate |
630 # accidental-mark | other-notation
632 if notations.get_tuplet():
633 tuplet_event = notations.get_tuplet()
634 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
637 frac = mod.get_fraction ()
639 tuplet_events.append ((ev_chord, tuplet_event, frac))
641 slurs = [s for s in notations.get_named_children ('slur')
642 if s.get_type () in ('start','stop')]
645 print 'more than 1 slur?'
647 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
648 ev_chord.append (lily_ev)
650 mxl_tie = notations.get_tie ()
651 if mxl_tie and mxl_tie.type == 'start':
652 ev_chord.append (musicexp.TieEvent ())
654 fermatas = notations.get_named_children ('fermata')
656 ev = musicxml_fermata_to_lily_event (a)
660 arpeggiate = notations.get_named_children ('arpeggiate')
662 ev_chord.append (musicexp.ArpeggioEvent ())
664 glissandos = notations.get_named_children ('glissando')
666 ev = musicxml_spanner_to_lily_event (a)
670 # Articulations can contain the following child elements:
671 # accent | strong-accent | staccato | tenuto |
672 # detached-legato | staccatissimo | spiccato |
673 # scoop | plop | doit | falloff | breath-mark |
674 # caesura | stress | unstress
675 # Technical can contain the following child elements:
676 # up-bow | down-bow | harmonic | open-string |
677 # thumb-position | fingering | pluck | double-tongue |
678 # triple-tongue | stopped | snap-pizzicato | fret |
679 # string | hammer-on | pull-off | bend | tap | heel |
680 # toe | fingernails | other-technical
681 # Ornaments can contain the following child elements:
682 # trill-mark | turn | delayed-turn | inverted-turn |
683 # shake | wavy-line | mordent | inverted-mordent |
684 # schleifer | tremolo | other-ornament, accidental-mark
685 ornaments = notations.get_named_children ('ornaments')
687 for ch in a.get_named_children ('tremolo'):
688 ev = musicxml_tremolo_to_lily_event (ch)
692 ornaments += notations.get_named_children ('articulations')
693 ornaments += notations.get_named_children ('technical')
696 for ch in a.get_all_children ():
697 ev = musicxml_articulation_to_lily_event (ch)
701 dynamics = notations.get_named_children ('dynamics')
703 for ch in a.get_all_children ():
704 ev = musicxml_dynamics_to_lily_event (ch)
709 note_lyrics_processed = []
710 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
711 for l in note_lyrics_elements:
712 if l.get_number () < 0:
713 for k in lyrics.keys ():
714 lyrics[k].append (l.lyric_to_text ())
715 note_lyrics_processed.append (k)
717 lyrics[l.number].append(l.lyric_to_text ())
718 note_lyrics_processed.append (l.number)
719 for lnr in lyrics.keys ():
720 if not lnr in note_lyrics_processed:
721 lyrics[lnr].append ("\skip4")
724 mxl_beams = [b for b in n.get_named_children ('beam')
725 if (b.get_type () in ('begin', 'end')
726 and b.is_primary ())]
728 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
730 ev_chord.append (beam_ev)
733 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
736 frac = mod.get_fraction ()
738 tuplet_events.append ((ev_chord, tuplet_event, frac))
740 ## force trailing mm rests to be written out.
741 voice_builder.add_music (musicexp.EventChord (), Rational (0))
743 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
745 seq_music = musicexp.SequentialMusic ()
747 if 'drummode' in modes_found.keys ():
748 ## \key <pitch> barfs in drummode.
749 ly_voice = [e for e in ly_voice
750 if not isinstance(e, musicexp.KeySignatureChange)]
752 seq_music.elements = ly_voice
754 for k in lyrics.keys ():
755 lyrics_dict[k] = musicexp.Lyrics ()
756 lyrics_dict[k].lyrics_syllables = lyrics[k]
759 if len (modes_found) > 1:
760 print 'Too many modes found', modes_found.keys ()
762 return_value = seq_music
763 for mode in modes_found.keys ():
764 v = musicexp.ModeChangingMusicWrapper()
765 v.element = return_value
769 return (return_value, lyrics_dict)
772 def musicxml_id_to_lily (id):
773 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
774 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
777 d = digits.index (digit)
778 id = re.sub ('%d' % d, digit, id)
780 id = re.sub ('[^a-zA-Z]', 'X', id)
784 def musicxml_pitch_to_lily (mxl_pitch):
786 p.alteration = mxl_pitch.get_alteration ()
787 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
788 p.octave = mxl_pitch.get_octave () - 4
791 def voices_in_part (part):
792 """Return a Name -> Voice dictionary for PART"""
794 part.extract_voices ()
795 voice_dict = part.get_voices ()
799 def voices_in_part_in_parts (parts):
800 """return a Part -> Name -> Voice dictionary"""
801 return dict([(p, voices_in_part (p)) for p in parts])
804 def get_all_voices (parts):
805 all_voices = voices_in_part_in_parts (parts)
808 for p, name_voice in all_voices.items ():
811 for n, v in name_voice.items ():
812 progress ("Converting to LilyPond expressions...")
813 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
814 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
816 all_ly_voices[p] = part_ly_voices
821 def option_parser ():
822 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
823 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
825 _ ("""This program is free software. It is covered by the GNU General Public
826 License and you are welcome to change it and/or distribute copies of it
827 under certain conditions. Invoke as `%s --warranty' for more
828 information.""") % 'lilypond'
830 Copyright (c) 2005--2007 by
831 Han-Wen Nienhuys <hanwen@xs4all.nl> and
832 Jan Nieuwenhuizen <janneke@gnu.org>
834 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
835 p.add_option ('-v', '--verbose',
838 help=_ ("be verbose"))
840 p.add_option ('', '--lxml',
844 help=_ ("Use lxml.etree; uses less memory and cpu time."))
846 p.add_option ('-o', '--output',
852 help=_ ("set output filename to FILE"))
853 p.add_option_group ('bugs',
854 description=(_ ("Report bugs via")
855 + ''' http://post.gmane.org/post.php'''
856 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
859 def music_xml_voice_name_to_lily_name (part, name):
860 str = "Part%sVoice%s" % (part.id, name)
861 return musicxml_id_to_lily (str)
863 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
864 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
865 return musicxml_id_to_lily (str)
867 def print_voice_definitions (printer, part_list, voices):
869 for (part, nv_dict) in voices.items():
870 part_dict[part.id] = (part, nv_dict)
872 for part in part_list:
873 (part, nv_dict) = part_dict.get (part.id, (None, {}))
874 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
875 k = music_xml_voice_name_to_lily_name (part, name)
876 printer.dump ('%s = ' % k)
877 voice.print_ly (printer)
880 for l in lyrics.keys ():
881 lname = music_xml_lyrics_name_to_lily_name (part, name, l)
882 printer.dump ('%s = ' %lname )
883 lyrics[l].print_ly (printer)
888 return dict ([(elt,1) for elt in l]).keys ()
890 def print_score_setup (printer, part_list, voices):
891 part_dict = dict ([(p.id, p) for p in voices.keys ()])
895 for part_definition in part_list:
896 part_name = part_definition.id
897 part = part_dict.get (part_name)
899 print 'unknown part in part-list:', part_name
902 # TODO: Apparently this is broken! There is always only one staff...
903 nv_dict = voices.get (part)
904 staves = reduce (lambda x,y: x+ y,
905 [mxlvoice._staves.keys ()
906 for (v, mxlvoice) in nv_dict.values ()],
910 staves = uniq_list (staves)
912 printer ('\\context PianoStaff << ')
916 staff_voices = [(music_xml_voice_name_to_lily_name (part, voice_name), voice_name, v)
917 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
918 if mxlvoice._start_staff == s]
920 printer ('\\context Staff = "%s" << ' % s)
922 for (v, voice_name, (music, lyrics)) in staff_voices:
923 printer ('\\context Voice = "%s" \\%s' % (v,v))
926 # Assign the lyrics to that voice
927 for l in lyrics.keys ():
928 ll = music_xml_lyrics_name_to_lily_name (part, voice_name, l)
929 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (v, ll))
940 printer ('\\new Staff <<')
942 for (n,v) in nv_dict.items ():
943 ((music, lyrics), voice) = v
944 nn = music_xml_voice_name_to_lily_name (part, n)
945 printer ('\\context Voice = "%s" \\%s' % (nn,nn))
947 # Assign the lyrics to that voice
948 for l in lyrics.keys ():
949 ll = music_xml_lyrics_name_to_lily_name (part, n, l)
950 printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (nn, ll))
959 def print_ly_preamble (printer, filename):
960 printer.dump_version ()
961 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
963 def read_musicxml (filename, use_lxml):
967 tree = lxml.etree.parse (filename)
968 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
971 from xml.dom import minidom, Node
973 doc = minidom.parse(filename)
974 node = doc.documentElement
975 return musicxml.minidom_demarshal_node (node)
980 def convert (filename, options):
981 progress ("Reading MusicXML from %s ..." % filename)
983 tree = read_musicxml (filename, options.use_lxml)
986 id_instrument_map = {}
987 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
988 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
989 part_list = mxl_pl.get_named_children ("score-part")
991 # score information is contained in the <work>, <identification> or <movement-title> tags
992 score_information = extract_score_information (tree)
993 parts = tree.get_typed_children (musicxml.Part)
994 voices = get_all_voices (parts)
996 if not options.output_name:
997 options.output_name = os.path.basename (filename)
998 options.output_name = os.path.splitext (options.output_name)[0]
999 elif re.match (".*\.ly", options.output_name):
1000 options.output_name = os.path.splitext (options.output_name)[0]
1003 defs_ly_name = options.output_name + '-defs.ly'
1004 driver_ly_name = options.output_name + '.ly'
1006 printer = musicexp.Output_printer()
1007 progress ("Output to `%s'" % defs_ly_name)
1008 printer.set_file (open (defs_ly_name, 'w'))
1010 print_ly_preamble (printer, filename)
1011 print_ly_information (printer, score_information)
1012 print_voice_definitions (printer, part_list, voices)
1017 progress ("Output to `%s'" % driver_ly_name)
1018 printer = musicexp.Output_printer()
1019 printer.set_file (open (driver_ly_name, 'w'))
1020 print_ly_preamble (printer, filename)
1021 printer.dump (r'\include "%s"' % defs_ly_name)
1022 print_score_setup (printer, part_list, voices)
1027 def get_existing_filename_with_extension (filename, ext):
1028 if not os.path.exists (filename):
1029 if filename[-1] == '.':
1031 elif not re.match ("\.xml$", filename):
1036 opt_parser = option_parser()
1038 (options, args) = opt_parser.parse_args ()
1040 opt_parser.print_usage()
1043 # Allow the user to leave out the .xml on the filename
1044 filename = get_existing_filename_with_extension (args[0], "xml")
1045 if not os.path.exists (filename):
1046 print "Unable to find input file %s" % args[0]
1048 voices = convert (filename, options)
1050 if __name__ == '__main__':