8 from gettext import gettext as _
19 from rational import Rational
23 sys.stderr.write (str + '\n')
27 def musicxml_duration_to_lily (mxl_note):
28 d = musicexp.Duration ()
29 if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
30 d.duration_log = mxl_note.get_duration_log ()
34 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
35 d.factor = mxl_note._duration / d.get_length ()
39 def group_tuplets (music_list, events):
42 """Collect Musics from
43 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
50 for (ev_chord, tuplet_elt, fraction) in events:
51 while (j < len (music_list)):
52 if music_list[j]== ev_chord:
55 if tuplet_elt.type == 'start':
56 indices.append ((j, None, fraction))
57 elif tuplet_elt.type == 'stop':
58 indices[-1] = (indices[-1][0], j, indices[-1][2])
62 for (i1, i2, frac) in indices:
66 new_list.extend (music_list[last:i1])
67 seq = musicexp.SequentialMusic ()
69 seq.elements = music_list[i1:last]
71 tsm = musicexp.TimeScaledMusic ()
74 tsm.numerator = frac[0]
75 tsm.denominator = frac[1]
79 new_list.extend (music_list[last:])
83 def musicxml_clef_to_lily (attributes):
84 change = musicexp.ClefChange ()
85 change.type = attributes.get_clef_sign ()
88 def musicxml_time_to_lily (attributes):
89 (beats, type) = attributes.get_time_signature ()
91 change = musicexp.TimeSignatureChange()
92 change.fraction = (beats, type)
96 def musicxml_key_to_lily (attributes):
97 start_pitch = musicexp.Pitch ()
98 (fifths, mode) = attributes.get_key_signature ()
105 start_pitch.alteration = a
107 print 'unknown mode', mode
109 fifth = musicexp.Pitch()
116 for x in range (fifths):
117 start_pitch = start_pitch.transposed (fifth)
119 start_pitch.octave = 0
121 change = musicexp.KeySignatureChange()
123 change.tonic = start_pitch
126 def musicxml_attributes_to_lily (attrs):
129 'clef': musicxml_clef_to_lily,
130 'time': musicxml_time_to_lily,
131 'key': musicxml_key_to_lily
133 for (k, func) in attr_dispatch.items ():
134 children = attrs.get_named_children (k)
136 ## ugh: you get clefs spread over staves for piano
138 elts.append (func (attrs))
142 spanner_event_dict = {
143 'slur' : musicexp.SlurEvent,
144 'beam' : musicexp.BeamEvent,
146 spanner_type_dict = {
153 def musicxml_spanner_to_lily_event (mxl_event):
156 name = mxl_event.get_name()
158 func = spanner_event_dict[name]
161 print 'unknown span event ', mxl_event
164 key = mxl_event.get_type ()
165 ev.span_direction = spanner_type_dict[key]
167 print 'unknown span type', key, 'for', name
171 def musicxml_direction_to_indicator (direction):
172 val = { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction)
178 def musicxml_fermata_to_lily_event (mxl_event):
179 ev = musicexp.ArticulationEvent ()
181 if hasattr (mxl_event, 'type'):
182 dir = musicxml_direction_to_indicator (mxl_event.type)
184 ev.force_direction = dir
187 def musicxml_tremolo_to_lily_event(mxl_event):
188 if mxl_event.get_name () != "tremolo":
190 ev = musicexp.TremoloEvent ()
191 ev.bars = mxl_event.get_text ()
194 # TODO: Some translations are missing!
195 articulations_dict = {
197 "trill-mark": "trill",
199 #"delayed-turn": "?",
200 "inverted-turn": "reverseturn",
203 "mordent": "mordent",
204 #"inverted-mordent": "?",
208 "down-bow": "downbow",
211 #"thumb-position": "",
214 #"double-tongue": "",
215 #"triple-tongue": "",
217 #"snap-pizzicato": "",
229 "strong-accent": "marcato",
230 "staccato": "staccato",
232 #"detached-legato": "",
233 "staccatissimo": "staccatissimo",
239 "breath-mark": "breathe",
240 #"caesura": "caesura",
245 def musicxml_articulation_to_lily_event(mxl_event):
246 ev = musicexp.ArticulationEvent ()
247 tp = articulations_dict.get (mxl_event.get_name ())
253 # Some articulations use the type attribute, other the placement...
255 if hasattr (mxl_event, 'type'):
256 dir = musicxml_direction_to_indicator (mxl_event.type)
257 if hasattr (mxl_event, 'placement'):
258 dir = musicxml_direction_to_indicator (mxl_event.placement)
260 ev.force_direction = dir
264 def musicxml_direction_to_lily( n ):
265 # TODO: Handle the <staff> element!
267 dirtype = n.get_maybe_exist_typed_child (musicxml.DirType)
271 for entry in dirtype.get_all_children ():
272 if entry.get_name () == "dynamics":
273 for dynentry in entry.get_all_children ():
274 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
275 "f", "ff", "fff", "ffff", "fffff", "ffffff",
276 "mp", "mf", "sf", "sfp", "sfpp", "fp",
277 "rf", "rfz", "sfz", "sffz", "fz" )
278 if not dynentry.get_name() in dynamics_available:
280 event = musicexp.DynamicsEvent ()
281 event.type = dynentry.get_name ()
284 if entry.get_name() == "wedge":
285 if hasattr (entry, 'type'):
286 wedgetype = entry.type;
287 wedgetypeval = {"crescendo" : 1, "decrescendo" : -1,
288 "diminuendo" : -1, "stop" : 0 }.get (wedgetype)
289 if wedgetypeval != None:
290 event = musicexp.HairpinEvent (wedgetypeval)
295 instrument_drumtype_dict = {
296 'Acoustic Snare Drum': 'acousticsnare',
297 'Side Stick': 'sidestick',
298 'Open Triangle': 'opentriangle',
299 'Mute Triangle': 'mutetriangle',
300 'Tambourine': 'tambourine'
303 def musicxml_note_to_lily_main_event (n):
307 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
310 pitch = musicxml_pitch_to_lily (mxl_pitch)
311 event = musicexp.NoteEvent()
314 acc = n.get_maybe_exist_named_child ('accidental')
316 # let's not force accs everywhere.
317 event.cautionary = acc.editorial
319 elif n.get_maybe_exist_typed_child (musicxml.Rest):
320 event = musicexp.RestEvent()
321 elif n.instrument_name:
322 event = musicexp.NoteEvent ()
324 event.drum_type = instrument_drumtype_dict[n.instrument_name]
326 n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
327 event.drum_type = 'acousticsnare'
330 n.message ("cannot find suitable event")
332 event.duration = musicxml_duration_to_lily (n)
338 def __init__ (self, here, dest):
342 class LilyPondVoiceBuilder:
345 self.pending_dynamics = []
346 self.end_moment = Rational (0)
347 self.begin_moment = Rational (0)
348 self.pending_multibar = Rational (0)
350 def _insert_multibar (self):
351 r = musicexp.MultiMeasureRest ()
352 r.duration = musicexp.Duration()
353 r.duration.duration_log = 0
354 r.duration.factor = self.pending_multibar
355 self.elements.append (r)
356 self.begin_moment = self.end_moment
357 self.end_moment = self.begin_moment + self.pending_multibar
358 self.pending_multibar = Rational (0)
360 def add_multibar_rest (self, duration):
361 self.pending_multibar += duration
364 def add_music (self, music, duration):
365 assert isinstance (music, musicexp.Music)
366 if self.pending_multibar > Rational (0):
367 self._insert_multibar ()
369 self.elements.append (music)
370 self.begin_moment = self.end_moment
371 self.end_moment = self.begin_moment + duration
373 # Insert all pending dynamics right after the note/rest:
374 if duration > Rational (0):
375 for d in self.pending_dynamics:
376 self.elements.append (d)
377 self.pending_dynamics = []
379 def add_dynamics (self, dynamic):
380 # store the dynamic item(s) until we encounter the next note/rest:
381 self.pending_dynamics.append (dynamic)
383 def add_bar_check (self, number):
384 b = musicexp.BarCheck ()
385 b.bar_number = number
386 self.add_music (b, Rational (0))
388 def jumpto (self, moment):
389 current_end = self.end_moment + self.pending_multibar
390 diff = moment - current_end
392 if diff < Rational (0):
393 print 'Negative skip', diff
396 if diff > Rational (0):
397 skip = musicexp.SkipEvent()
398 skip.duration.duration_log = 0
399 skip.duration.factor = diff
401 evc = musicexp.EventChord ()
402 evc.elements.append (skip)
403 self.add_music (evc, diff)
405 def last_event_chord (self, starting_at):
409 and isinstance (self.elements[-1], musicexp.EventChord)
410 and self.begin_moment == starting_at):
411 value = self.elements[-1]
413 self.jumpto (starting_at)
418 def correct_negative_skip (self, goto):
419 self.end_moment = goto
420 self.begin_moment = goto
421 evc = musicexp.EventChord ()
422 self.elements.append (evc)
424 def musicxml_voice_to_lily_voice (voice):
428 voice_builder = LilyPondVoiceBuilder()
430 for n in voice._elements:
431 if n.get_name () == 'forward':
434 if isinstance (n, musicxml.Direction):
435 for a in musicxml_direction_to_lily (n):
436 voice_builder.add_dynamics (a)
439 if not n.get_maybe_exist_named_child ('chord'):
441 voice_builder.jumpto (n._when)
442 except NegativeSkip, neg:
443 voice_builder.correct_negative_skip (n._when)
444 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
446 if isinstance (n, musicxml.Attributes):
447 if n.is_first () and n._measure_position == Rational (0):
449 number = int (n.get_parent ().number)
453 voice_builder.add_bar_check (number)
454 for a in musicxml_attributes_to_lily (n):
455 voice_builder.add_music (a, Rational (0))
458 if not n.__class__.__name__ == 'Note':
459 print 'not a Note or Attributes?', n
462 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
464 and rest.is_whole_measure ()):
466 voice_builder.add_multibar_rest (n._duration)
469 if n.is_first () and n._measure_position == Rational (0):
471 num = int (n.get_parent ().number)
474 voice_builder.add_bar_check (num)
476 main_event = musicxml_note_to_lily_main_event (n)
479 if main_event.drum_type:
480 modes_found['drummode'] = True
481 except AttributeError:
485 ev_chord = voice_builder.last_event_chord (n._when)
487 ev_chord = musicexp.EventChord()
488 voice_builder.add_music (ev_chord, n._duration)
490 ev_chord.append (main_event)
492 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
496 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
497 # +tied | +slur | +tuplet | glissando | slide |
498 # ornaments | technical | articulations | dynamics |
499 # +fermata | arpeggiate | non-arpeggiate |
500 # accidental-mark | other-notation
502 if notations.get_tuplet():
503 tuplet_event = notations.get_tuplet()
504 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
507 frac = mod.get_fraction ()
509 tuplet_events.append ((ev_chord, tuplet_event, frac))
511 slurs = [s for s in notations.get_named_children ('slur')
512 if s.get_type () in ('start','stop')]
515 print 'more than 1 slur?'
517 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
518 ev_chord.append (lily_ev)
520 mxl_tie = notations.get_tie ()
521 if mxl_tie and mxl_tie.type == 'start':
522 ev_chord.append (musicexp.TieEvent ())
524 fermatas = notations.get_named_children ('fermata')
526 ev = musicxml_fermata_to_lily_event (a);
530 # Articulations can contain the following child elements:
531 # accent | strong-accent | staccato | tenuto |
532 # detached-legato | staccatissimo | spiccato |
533 # scoop | plop | doit | falloff | breath-mark |
534 # caesura | stress | unstress
535 # Technical can contain the following child elements:
536 # up-bow | down-bow | harmonic | open-string |
537 # thumb-position | fingering | pluck | double-tongue |
538 # triple-tongue | stopped | snap-pizzicato | fret |
539 # string | hammer-on | pull-off | bend | tap | heel |
540 # toe | fingernails | other-technical
541 # Ornaments can contain the following child elements:
542 # trill-mark | turn | delayed-turn | inverted-turn |
543 # shake | wavy-line | mordent | inverted-mordent |
544 # schleifer | tremolo | other-ornament, accidental-mark
545 ornaments = notations.get_named_children ('ornaments')
547 for ch in a.get_named_children ('tremolo'):
548 ev = musicxml_tremolo_to_lily_event (ch)
552 ornaments += notations.get_named_children ('articulations')
553 ornaments += notations.get_named_children ('technical')
556 for ch in a.get_all_children ():
557 ev = musicxml_articulation_to_lily_event (ch)
561 dynamics = notations.get_named_children ('dynamics')
563 for ch in a.get_all_children ():
564 ev = musicxml_dynamics_to_lily_event (ch)
568 mxl_beams = [b for b in n.get_named_children ('beam')
569 if (b.get_type () in ('begin', 'end')
570 and b.is_primary ())]
572 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
574 ev_chord.append (beam_ev)
577 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
580 frac = mod.get_fraction ()
582 tuplet_events.append ((ev_chord, tuplet_event, frac))
584 ## force trailing mm rests to be written out.
585 voice_builder.add_music (musicexp.EventChord (), Rational (0))
587 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
589 seq_music = musicexp.SequentialMusic()
591 if 'drummode' in modes_found.keys ():
592 ## \key <pitch> barfs in drummode.
593 ly_voice = [e for e in ly_voice
594 if not isinstance(e, musicexp.KeySignatureChange)]
596 seq_music.elements = ly_voice
600 if len (modes_found) > 1:
601 print 'Too many modes found', modes_found.keys ()
603 return_value = seq_music
604 for mode in modes_found.keys ():
605 v = musicexp.ModeChangingMusicWrapper()
606 v.element = return_value
613 def musicxml_id_to_lily (id):
614 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
618 d = digits.index (dig)
619 id = re.sub ('%d' % d, dig, id)
621 id = re.sub ('[^a-zA-Z]', 'X', id)
625 def musicxml_pitch_to_lily (mxl_pitch):
627 p.alteration = mxl_pitch.get_alteration ()
628 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
629 p.octave = mxl_pitch.get_octave () - 4
632 def voices_in_part (part):
633 """Return a Name -> Voice dictionary for PART"""
635 part.extract_voices ()
636 voice_dict = part.get_voices ()
640 def voices_in_part_in_parts (parts):
641 """return a Part -> Name -> Voice dictionary"""
642 return dict([(p, voices_in_part (p)) for p in parts])
645 def get_all_voices (parts):
646 all_voices = voices_in_part_in_parts (parts)
649 for p, name_voice in all_voices.items ():
652 for n, v in name_voice.items ():
653 progress ("Converting to LilyPond expressions...")
654 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
656 all_ly_voices[p] = part_ly_voices
661 def option_parser ():
662 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
663 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
665 _ ("""This program is free software. It is covered by the GNU General Public
666 License and you are welcome to change it and/or distribute copies of it
667 under certain conditions. Invoke as `%s --warranty' for more
668 information.""") % 'lilypond'
670 Copyright (c) 2005--2007 by
671 Han-Wen Nienhuys <hanwen@xs4all.nl> and
672 Jan Nieuwenhuizen <janneke@gnu.org>
674 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
675 p.add_option ('-v', '--verbose',
678 help=_ ("be verbose"))
680 p.add_option ('', '--lxml',
684 help=_ ("Use lxml.etree; uses less memory and cpu time."))
686 p.add_option ('-o', '--output',
692 help=_ ("set output filename to FILE"))
693 p.add_option_group ('bugs',
694 description=(_ ("Report bugs via")
695 + ''' http://post.gmane.org/post.php'''
696 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
699 def music_xml_voice_name_to_lily_name (part, name):
700 str = "Part%sVoice%s" % (part.id, name)
701 return musicxml_id_to_lily (str)
703 def print_voice_definitions (printer, part_list, voices):
705 for (part, nv_dict) in voices.items():
706 part_dict[part.id] = (part, nv_dict)
708 for part in part_list:
709 (part, nv_dict) = part_dict[part.id]
710 for (name, (voice, mxlvoice)) in nv_dict.items ():
711 k = music_xml_voice_name_to_lily_name (part, name)
712 printer.dump ('%s = ' % k)
713 voice.print_ly (printer)
718 return dict ([(elt,1) for elt in l]).keys ()
720 def print_score_setup (printer, part_list, voices):
721 part_dict = dict ([(p.id, p) for p in voices.keys ()])
725 for part_definition in part_list:
726 part_name = part_definition.id
728 part = part_dict[part_name]
730 print 'unknown part in part-list:', part_name
733 nv_dict = voices[part]
734 staves = reduce (lambda x,y: x+ y,
735 [mxlvoice._staves.keys ()
736 for (v, mxlvoice) in nv_dict.values ()],
740 staves = uniq_list (staves)
742 printer ('\\context PianoStaff << ')
746 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
747 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
748 if mxlvoice._start_staff == s]
750 printer ('\\context Staff = "%s" << ' % s)
752 for v in staff_voices:
753 printer ('\\context Voice = "%s" \\%s' % (v,v))
762 printer ('\\new Staff <<')
764 for (n,v) in nv_dict.items ():
766 n = music_xml_voice_name_to_lily_name (part, n)
767 printer ('\\context Voice = "%s" \\%s' % (n,n))
774 def print_ly_preamble (printer, filename):
775 printer.dump_version ()
776 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
778 def read_musicxml (filename, use_lxml):
782 tree = lxml.etree.parse (filename)
783 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
786 from xml.dom import minidom, Node
788 doc = minidom.parse(filename)
789 node = doc.documentElement
790 return musicxml.minidom_demarshal_node (node)
795 def convert (filename, options):
796 progress ("Reading MusicXML from %s ..." % filename)
798 tree = read_musicxml (filename, options.use_lxml)
801 id_instrument_map = {}
802 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
803 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
804 part_list = mxl_pl.get_named_children ("score-part")
806 parts = tree.get_typed_children (musicxml.Part)
807 voices = get_all_voices (parts)
809 if not options.output_name:
810 options.output_name = os.path.basename (filename)
811 options.output_name = os.path.splitext (options.output_name)[0]
814 defs_ly_name = options.output_name + '-defs.ly'
815 driver_ly_name = options.output_name + '.ly'
817 printer = musicexp.Output_printer()
818 progress ("Output to `%s'" % defs_ly_name)
819 printer.set_file (open (defs_ly_name, 'w'))
821 print_ly_preamble (printer, filename)
822 print_voice_definitions (printer, part_list, voices)
827 progress ("Output to `%s'" % driver_ly_name)
828 printer = musicexp.Output_printer()
829 printer.set_file (open (driver_ly_name, 'w'))
830 print_ly_preamble (printer, filename)
831 printer.dump (r'\include "%s"' % defs_ly_name)
832 print_score_setup (printer, part_list, voices)
839 opt_parser = option_parser()
841 (options, args) = opt_parser.parse_args ()
843 opt_parser.print_usage()
846 voices = convert (args[0], options)
848 if __name__ == '__main__':