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 work = tree.get_maybe_exist_named_child ('work')
33 if work.get_work_title ():
34 score_information['title'] = work.get_work_title ()
35 if work.get_work_number ():
36 score_information['worknumber'] = work.get_work_number ()
38 score_information['opus'] = work.get_opus ()
40 movement_title = tree.get_maybe_exist_named_child ('movement-title')
42 score_information['title'] = movement_title.get_text ()
44 identifications = tree.get_named_children ('identification')
45 for ids in identifications:
47 score_information['copyright'] = ids.get_rights ()
48 if ids.get_composer ():
49 score_information['composer'] = ids.get_composer ()
50 if ids.get_arranger ():
51 score_information['arranger'] = ids.get_arranger ()
53 score_information['editor'] = ids.get_editor ()
55 score_information['poet'] = ids.get_poet ()
57 if ids.get_encoding_software ():
58 score_information['tagline'] = ids.get_encoding_software ()
59 score_information['encodingsoftware'] = ids.get_encoding_software ()
60 if ids.get_encoding_date ():
61 score_information['encodingdate'] = ids.get_encoding_date ()
62 if ids.get_encoding_person ():
63 score_information['encoder'] = ids.get_encoding_person ()
64 if ids.get_encoding_description ():
65 score_information['encodingdescription'] = ids.get_encoding_description ()
67 return score_information
69 def print_ly_information (printer, score_information):
70 printer.dump ('\header {')
72 for k in score_information.keys ():
73 printer.dump ('%s = "%s"' % (k, score_information[k]))
80 def musicxml_duration_to_lily (mxl_note):
81 d = musicexp.Duration ()
82 if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
83 d.duration_log = mxl_note.get_duration_log ()
87 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
88 d.factor = mxl_note._duration / d.get_length ()
92 def group_tuplets (music_list, events):
95 """Collect Musics from
96 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
103 for (ev_chord, tuplet_elt, fraction) in events:
104 while (j < len (music_list)):
105 if music_list[j] == ev_chord:
108 if tuplet_elt.type == 'start':
109 indices.append ((j, None, fraction))
110 elif tuplet_elt.type == 'stop':
111 indices[-1] = (indices[-1][0], j, indices[-1][2])
115 for (i1, i2, frac) in indices:
119 new_list.extend (music_list[last:i1])
120 seq = musicexp.SequentialMusic ()
122 seq.elements = music_list[i1:last]
124 tsm = musicexp.TimeScaledMusic ()
127 tsm.numerator = frac[0]
128 tsm.denominator = frac[1]
130 new_list.append (tsm)
132 new_list.extend (music_list[last:])
136 def musicxml_clef_to_lily (attributes):
137 change = musicexp.ClefChange ()
138 change.type = attributes.get_clef_sign ()
141 def musicxml_time_to_lily (attributes):
142 (beats, type) = attributes.get_time_signature ()
144 change = musicexp.TimeSignatureChange()
145 change.fraction = (beats, type)
149 def musicxml_key_to_lily (attributes):
150 start_pitch = musicexp.Pitch ()
151 (fifths, mode) = attributes.get_key_signature ()
158 start_pitch.alteration = a
160 print 'unknown mode', mode
162 fifth = musicexp.Pitch()
169 for x in range (fifths):
170 start_pitch = start_pitch.transposed (fifth)
172 start_pitch.octave = 0
174 change = musicexp.KeySignatureChange()
176 change.tonic = start_pitch
179 def musicxml_attributes_to_lily (attrs):
182 'clef': musicxml_clef_to_lily,
183 'time': musicxml_time_to_lily,
184 'key': musicxml_key_to_lily
186 for (k, func) in attr_dispatch.items ():
187 children = attrs.get_named_children (k)
189 ## ugh: you get clefs spread over staves for piano
191 elts.append (func (attrs))
195 spanner_event_dict = {
196 'slur' : musicexp.SlurEvent,
197 'beam' : musicexp.BeamEvent,
199 spanner_type_dict = {
206 def musicxml_spanner_to_lily_event (mxl_event):
209 name = mxl_event.get_name()
210 func = spanner_event_dict.get (name)
214 print 'unknown span event ', mxl_event
216 key = mxl_event.get_type ()
217 span_direction = spanner_type_dict.get (key)
219 ev.span_direction = span_direction
221 print 'unknown span type', key, 'for', name
225 def musicxml_direction_to_indicator (direction):
226 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
228 def musicxml_fermata_to_lily_event (mxl_event):
229 ev = musicexp.ArticulationEvent ()
231 if hasattr (mxl_event, 'type'):
232 dir = musicxml_direction_to_indicator (mxl_event.type)
234 ev.force_direction = dir
237 def musicxml_tremolo_to_lily_event(mxl_event):
238 if mxl_event.get_name () != "tremolo":
240 ev = musicexp.TremoloEvent ()
241 ev.bars = mxl_event.get_text ()
244 # TODO: Some translations are missing!
245 articulations_dict = {
247 "trill-mark": "trill",
249 #"delayed-turn": "?",
250 "inverted-turn": "reverseturn",
253 "mordent": "mordent",
254 "inverted-mordent": "downmordent",
258 "down-bow": "downbow",
259 "harmonic": "flageolet",
261 #"thumb-position": "",
264 #"double-tongue": "",
265 #"triple-tongue": "",
267 #"snap-pizzicato": "",
279 "strong-accent": "marcato",
280 "staccato": "staccato",
282 #"detached-legato": "",
283 "staccatissimo": "staccatissimo",
289 "breath-mark": "breathe",
290 #"caesura": "caesura",
295 def musicxml_articulation_to_lily_event(mxl_event):
296 ev = musicexp.ArticulationEvent ()
297 tp = articulations_dict.get (mxl_event.get_name ())
303 # Some articulations use the type attribute, other the placement...
305 if hasattr (mxl_event, 'type'):
306 dir = musicxml_direction_to_indicator (mxl_event.type)
307 if hasattr (mxl_event, 'placement'):
308 dir = musicxml_direction_to_indicator (mxl_event.placement)
309 # \breathe cannot have any direction modifyer (^, _, -)!
310 if dir and tp != "breathe":
311 ev.force_direction = dir
315 def musicxml_direction_to_lily( n ):
316 # TODO: Handle the <staff> element!
318 dirtype = n.get_maybe_exist_typed_child (musicxml.DirType)
322 for entry in dirtype.get_all_children ():
323 if entry.get_name () == "dynamics":
324 for dynentry in entry.get_all_children ():
325 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
326 "f", "ff", "fff", "ffff", "fffff", "ffffff",
327 "mp", "mf", "sf", "sfp", "sfpp", "fp",
328 "rf", "rfz", "sfz", "sffz", "fz" )
329 if not dynentry.get_name() in dynamics_available:
331 event = musicexp.DynamicsEvent ()
332 event.type = dynentry.get_name ()
335 if entry.get_name() == "wedge":
336 if hasattr (entry, 'type'):
337 wedgetype = entry.type;
338 wedgetypeval = {"crescendo" : 1, "decrescendo" : -1,
339 "diminuendo" : -1, "stop" : 0 }.get (wedgetype)
340 # Really check for != None, becaus otherwise 0 will also cause
341 # the code to be executed!
342 if wedgetypeval != None:
343 event = musicexp.HairpinEvent (wedgetypeval)
348 instrument_drumtype_dict = {
349 'Acoustic Snare Drum': 'acousticsnare',
350 'Side Stick': 'sidestick',
351 'Open Triangle': 'opentriangle',
352 'Mute Triangle': 'mutetriangle',
353 'Tambourine': 'tambourine'
356 def musicxml_note_to_lily_main_event (n):
360 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
363 pitch = musicxml_pitch_to_lily (mxl_pitch)
364 event = musicexp.NoteEvent()
367 acc = n.get_maybe_exist_named_child ('accidental')
369 # let's not force accs everywhere.
370 event.cautionary = acc.editorial
372 elif n.get_maybe_exist_typed_child (musicxml.Rest):
373 event = musicexp.RestEvent()
374 elif n.instrument_name:
375 event = musicexp.NoteEvent ()
376 drum_type = instrument_drumtype_dict.get (n.instrument_name)
378 event.drum_type = drum_type
380 n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
381 event.drum_type = 'acousticsnare'
384 n.message ("cannot find suitable event")
386 event.duration = musicxml_duration_to_lily (n)
392 def __init__ (self, here, dest):
396 class LilyPondVoiceBuilder:
399 self.pending_dynamics = []
400 self.end_moment = Rational (0)
401 self.begin_moment = Rational (0)
402 self.pending_multibar = Rational (0)
404 def _insert_multibar (self):
405 r = musicexp.MultiMeasureRest ()
406 r.duration = musicexp.Duration()
407 r.duration.duration_log = 0
408 r.duration.factor = self.pending_multibar
409 self.elements.append (r)
410 self.begin_moment = self.end_moment
411 self.end_moment = self.begin_moment + self.pending_multibar
412 self.pending_multibar = Rational (0)
414 def add_multibar_rest (self, duration):
415 self.pending_multibar += duration
418 def add_music (self, music, duration):
419 assert isinstance (music, musicexp.Music)
420 if self.pending_multibar > Rational (0):
421 self._insert_multibar ()
423 self.elements.append (music)
424 self.begin_moment = self.end_moment
425 self.end_moment = self.begin_moment + duration
427 # Insert all pending dynamics right after the note/rest:
428 if duration > Rational (0):
429 for d in self.pending_dynamics:
430 self.elements.append (d)
431 self.pending_dynamics = []
433 def add_dynamics (self, dynamic):
434 # store the dynamic item(s) until we encounter the next note/rest:
435 self.pending_dynamics.append (dynamic)
437 def add_bar_check (self, number):
438 b = musicexp.BarCheck ()
439 b.bar_number = number
440 self.add_music (b, Rational (0))
442 def jumpto (self, moment):
443 current_end = self.end_moment + self.pending_multibar
444 diff = moment - current_end
446 if diff < Rational (0):
447 print 'Negative skip', diff
450 if diff > Rational (0):
451 skip = musicexp.SkipEvent()
452 skip.duration.duration_log = 0
453 skip.duration.factor = diff
455 evc = musicexp.EventChord ()
456 evc.elements.append (skip)
457 self.add_music (evc, diff)
459 def last_event_chord (self, starting_at):
463 and isinstance (self.elements[-1], musicexp.EventChord)
464 and self.begin_moment == starting_at):
465 value = self.elements[-1]
467 self.jumpto (starting_at)
472 def correct_negative_skip (self, goto):
473 self.end_moment = goto
474 self.begin_moment = goto
475 evc = musicexp.EventChord ()
476 self.elements.append (evc)
478 def musicxml_voice_to_lily_voice (voice):
482 voice_builder = LilyPondVoiceBuilder()
484 for n in voice._elements:
485 if n.get_name () == 'forward':
488 if isinstance (n, musicxml.Direction):
489 for a in musicxml_direction_to_lily (n):
490 voice_builder.add_dynamics (a)
493 if not n.get_maybe_exist_named_child ('chord'):
495 voice_builder.jumpto (n._when)
496 except NegativeSkip, neg:
497 voice_builder.correct_negative_skip (n._when)
498 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
500 if isinstance (n, musicxml.Attributes):
501 if n.is_first () and n._measure_position == Rational (0):
503 number = int (n.get_parent ().number)
507 voice_builder.add_bar_check (number)
508 for a in musicxml_attributes_to_lily (n):
509 voice_builder.add_music (a, Rational (0))
512 if not n.__class__.__name__ == 'Note':
513 print 'not a Note or Attributes?', n
516 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
518 and rest.is_whole_measure ()):
520 voice_builder.add_multibar_rest (n._duration)
523 if n.is_first () and n._measure_position == Rational (0):
525 num = int (n.get_parent ().number)
528 voice_builder.add_bar_check (num)
530 main_event = musicxml_note_to_lily_main_event (n)
532 if hasattr (main_event, 'drum_type') and main_event.drum_type:
533 modes_found['drummode'] = True
536 ev_chord = voice_builder.last_event_chord (n._when)
538 ev_chord = musicexp.EventChord()
539 voice_builder.add_music (ev_chord, n._duration)
541 ev_chord.append (main_event)
543 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
547 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
548 # +tied | +slur | +tuplet | glissando | slide |
549 # ornaments | technical | articulations | dynamics |
550 # +fermata | arpeggiate | non-arpeggiate |
551 # accidental-mark | other-notation
553 if notations.get_tuplet():
554 tuplet_event = notations.get_tuplet()
555 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
558 frac = mod.get_fraction ()
560 tuplet_events.append ((ev_chord, tuplet_event, frac))
562 slurs = [s for s in notations.get_named_children ('slur')
563 if s.get_type () in ('start','stop')]
566 print 'more than 1 slur?'
568 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
569 ev_chord.append (lily_ev)
571 mxl_tie = notations.get_tie ()
572 if mxl_tie and mxl_tie.type == 'start':
573 ev_chord.append (musicexp.TieEvent ())
575 fermatas = notations.get_named_children ('fermata')
577 ev = musicxml_fermata_to_lily_event (a);
581 # Articulations can contain the following child elements:
582 # accent | strong-accent | staccato | tenuto |
583 # detached-legato | staccatissimo | spiccato |
584 # scoop | plop | doit | falloff | breath-mark |
585 # caesura | stress | unstress
586 # Technical can contain the following child elements:
587 # up-bow | down-bow | harmonic | open-string |
588 # thumb-position | fingering | pluck | double-tongue |
589 # triple-tongue | stopped | snap-pizzicato | fret |
590 # string | hammer-on | pull-off | bend | tap | heel |
591 # toe | fingernails | other-technical
592 # Ornaments can contain the following child elements:
593 # trill-mark | turn | delayed-turn | inverted-turn |
594 # shake | wavy-line | mordent | inverted-mordent |
595 # schleifer | tremolo | other-ornament, accidental-mark
596 ornaments = notations.get_named_children ('ornaments')
598 for ch in a.get_named_children ('tremolo'):
599 ev = musicxml_tremolo_to_lily_event (ch)
603 ornaments += notations.get_named_children ('articulations')
604 ornaments += notations.get_named_children ('technical')
607 for ch in a.get_all_children ():
608 ev = musicxml_articulation_to_lily_event (ch)
612 dynamics = notations.get_named_children ('dynamics')
614 for ch in a.get_all_children ():
615 ev = musicxml_dynamics_to_lily_event (ch)
619 mxl_beams = [b for b in n.get_named_children ('beam')
620 if (b.get_type () in ('begin', 'end')
621 and b.is_primary ())]
623 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
625 ev_chord.append (beam_ev)
628 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
631 frac = mod.get_fraction ()
633 tuplet_events.append ((ev_chord, tuplet_event, frac))
635 ## force trailing mm rests to be written out.
636 voice_builder.add_music (musicexp.EventChord (), Rational (0))
638 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
640 seq_music = musicexp.SequentialMusic()
642 if 'drummode' in modes_found.keys ():
643 ## \key <pitch> barfs in drummode.
644 ly_voice = [e for e in ly_voice
645 if not isinstance(e, musicexp.KeySignatureChange)]
647 seq_music.elements = ly_voice
651 if len (modes_found) > 1:
652 print 'Too many modes found', modes_found.keys ()
654 return_value = seq_music
655 for mode in modes_found.keys ():
656 v = musicexp.ModeChangingMusicWrapper()
657 v.element = return_value
664 def musicxml_id_to_lily (id):
665 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
666 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
669 d = digits.index (digit)
670 id = re.sub ('%d' % d, digit, id)
672 id = re.sub ('[^a-zA-Z]', 'X', id)
676 def musicxml_pitch_to_lily (mxl_pitch):
678 p.alteration = mxl_pitch.get_alteration ()
679 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
680 p.octave = mxl_pitch.get_octave () - 4
683 def voices_in_part (part):
684 """Return a Name -> Voice dictionary for PART"""
686 part.extract_voices ()
687 voice_dict = part.get_voices ()
691 def voices_in_part_in_parts (parts):
692 """return a Part -> Name -> Voice dictionary"""
693 return dict([(p, voices_in_part (p)) for p in parts])
696 def get_all_voices (parts):
697 all_voices = voices_in_part_in_parts (parts)
700 for p, name_voice in all_voices.items ():
703 for n, v in name_voice.items ():
704 progress ("Converting to LilyPond expressions...")
705 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
707 all_ly_voices[p] = part_ly_voices
712 def option_parser ():
713 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
714 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
716 _ ("""This program is free software. It is covered by the GNU General Public
717 License and you are welcome to change it and/or distribute copies of it
718 under certain conditions. Invoke as `%s --warranty' for more
719 information.""") % 'lilypond'
721 Copyright (c) 2005--2007 by
722 Han-Wen Nienhuys <hanwen@xs4all.nl> and
723 Jan Nieuwenhuizen <janneke@gnu.org>
725 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
726 p.add_option ('-v', '--verbose',
729 help=_ ("be verbose"))
731 p.add_option ('', '--lxml',
735 help=_ ("Use lxml.etree; uses less memory and cpu time."))
737 p.add_option ('-o', '--output',
743 help=_ ("set output filename to FILE"))
744 p.add_option_group ('bugs',
745 description=(_ ("Report bugs via")
746 + ''' http://post.gmane.org/post.php'''
747 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
750 def music_xml_voice_name_to_lily_name (part, name):
751 str = "Part%sVoice%s" % (part.id, name)
752 return musicxml_id_to_lily (str)
754 def print_voice_definitions (printer, part_list, voices):
756 for (part, nv_dict) in voices.items():
757 part_dict[part.id] = (part, nv_dict)
759 for part in part_list:
760 (part, nv_dict) = part_dict.get (part.id, (None, {}))
761 for (name, (voice, mxlvoice)) in nv_dict.items ():
762 k = music_xml_voice_name_to_lily_name (part, name)
763 printer.dump ('%s = ' % k)
764 voice.print_ly (printer)
769 return dict ([(elt,1) for elt in l]).keys ()
771 def print_score_setup (printer, part_list, voices):
772 part_dict = dict ([(p.id, p) for p in voices.keys ()])
776 for part_definition in part_list:
777 part_name = part_definition.id
778 part = part_dict.get (part_name)
780 print 'unknown part in part-list:', part_name
783 nv_dict = voices.get (part)
784 staves = reduce (lambda x,y: x+ y,
785 [mxlvoice._staves.keys ()
786 for (v, mxlvoice) in nv_dict.values ()],
790 staves = uniq_list (staves)
792 printer ('\\context PianoStaff << ')
796 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
797 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
798 if mxlvoice._start_staff == s]
800 printer ('\\context Staff = "%s" << ' % s)
802 for v in staff_voices:
803 printer ('\\context Voice = "%s" \\%s' % (v,v))
812 printer ('\\new Staff <<')
814 for (n,v) in nv_dict.items ():
816 n = music_xml_voice_name_to_lily_name (part, n)
817 printer ('\\context Voice = "%s" \\%s' % (n,n))
824 def print_ly_preamble (printer, filename):
825 printer.dump_version ()
826 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
828 def read_musicxml (filename, use_lxml):
832 tree = lxml.etree.parse (filename)
833 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
836 from xml.dom import minidom, Node
838 doc = minidom.parse(filename)
839 node = doc.documentElement
840 return musicxml.minidom_demarshal_node (node)
845 def convert (filename, options):
846 progress ("Reading MusicXML from %s ..." % filename)
848 tree = read_musicxml (filename, options.use_lxml)
851 id_instrument_map = {}
852 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
853 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
854 part_list = mxl_pl.get_named_children ("score-part")
856 # score information is contained in the <work>, <identification> or <movement-title> tags
857 score_information = extract_score_information (tree)
858 parts = tree.get_typed_children (musicxml.Part)
859 voices = get_all_voices (parts)
861 if not options.output_name:
862 options.output_name = os.path.basename (filename)
863 options.output_name = os.path.splitext (options.output_name)[0]
866 defs_ly_name = options.output_name + '-defs.ly'
867 driver_ly_name = options.output_name + '.ly'
869 printer = musicexp.Output_printer()
870 progress ("Output to `%s'" % defs_ly_name)
871 printer.set_file (open (defs_ly_name, 'w'))
873 print_ly_preamble (printer, filename)
874 print_ly_information (printer, score_information)
875 print_voice_definitions (printer, part_list, voices)
880 progress ("Output to `%s'" % driver_ly_name)
881 printer = musicexp.Output_printer()
882 printer.set_file (open (driver_ly_name, 'w'))
883 print_ly_preamble (printer, filename)
884 printer.dump (r'\include "%s"' % defs_ly_name)
885 print_score_setup (printer, part_list, voices)
892 opt_parser = option_parser()
894 (options, args) = opt_parser.parse_args ()
896 opt_parser.print_usage()
899 voices = convert (args[0], options)
901 if __name__ == '__main__':