8 from gettext import gettext as _
13 datadir = '@local_lilypond_datadir@'
14 if not os.path.isdir (datadir):
15 datadir = '@lilypond_datadir@'
16 if os.environ.has_key ('LILYPONDPREFIX'):
17 datadir = os.environ['LILYPONDPREFIX']
18 while datadir[-1] == os.sep:
19 datadir = datadir[:-1]
21 if os.path.exists (os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')):
22 datadir = os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')
23 elif os.path.exists (os.path.join (datadir, 'share/lilypond/current/')):
24 datadir = os.path.join (datadir, 'share/lilypond/current/')
26 sys.path.insert (0, os.path.join (datadir, 'python'))
28 # dynamic relocation, for GUB binaries.
29 bindir = os.path.split (sys.argv[0])[0]
31 for prefix_component in ['share', 'lib']:
32 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
33 sys.path.insert (0, datadir)
41 from rational import Rational
45 sys.stderr.write (str + '\n')
49 def musicxml_duration_to_lily (mxl_note):
50 d = musicexp.Duration ()
51 if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
52 d.duration_log = mxl_note.get_duration_log ()
56 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
57 d.factor = mxl_note._duration / d.get_length ()
61 def group_tuplets (music_list, events):
64 """Collect Musics from
65 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
72 for (ev_chord, tuplet_elt, fraction) in events:
73 while (j < len (music_list)):
74 if music_list[j]== ev_chord:
77 if tuplet_elt.type == 'start':
78 indices.append ((j, None, fraction))
79 elif tuplet_elt.type == 'stop':
80 indices[-1] = (indices[-1][0], j, indices[-1][2])
84 for (i1, i2, frac) in indices:
88 new_list.extend (music_list[last:i1])
89 seq = musicexp.SequentialMusic ()
91 seq.elements = music_list[i1:last]
93 tsm = musicexp.TimeScaledMusic ()
96 tsm.numerator = frac[0]
97 tsm.denominator = frac[1]
101 new_list.extend (music_list[last:])
105 def musicxml_clef_to_lily (attributes):
106 change = musicexp.ClefChange ()
107 change.type = attributes.get_clef_sign ()
110 def musicxml_time_to_lily (attributes):
111 (beats, type) = attributes.get_time_signature ()
113 change = musicexp.TimeSignatureChange()
114 change.fraction = (beats, type)
118 def musicxml_key_to_lily (attributes):
119 start_pitch = musicexp.Pitch ()
120 (fifths, mode) = attributes.get_key_signature ()
127 start_pitch.alteration = a
129 print 'unknown mode', mode
131 fifth = musicexp.Pitch()
138 start_pitch = musicexp.Pitch()
139 for x in range (fifths):
140 start_pitch = start_pitch.transposed (fifth)
142 start_pitch.octave = 0
144 change = musicexp.KeySignatureChange()
146 change.tonic = start_pitch
149 def musicxml_attributes_to_lily (attrs):
152 'clef': musicxml_clef_to_lily,
153 'time': musicxml_time_to_lily,
154 'key': musicxml_key_to_lily
156 for (k, func) in attr_dispatch.items ():
157 childs = attrs.get_named_children (k)
159 ## ugh: you get clefs spread over staves for piano
161 elts.append (func (attrs))
165 spanner_event_dict = {
166 'slur' : musicexp.SlurEvent,
167 'beam' : musicexp.BeamEvent,
169 spanner_type_dict = {
176 def musicxml_spanner_to_lily_event (mxl_event):
179 name = mxl_event.get_name()
181 func = spanner_event_dict[name]
184 print 'unknown span event ', mxl_event
187 key = mxl_event.get_type ()
188 ev.span_direction = spanner_type_dict[key]
190 print 'unknown span type', key, 'for', name
194 instrument_drumtype_dict = {
195 'Acoustic Snare Drum': 'acousticsnare',
196 'Side Stick': 'sidestick',
197 'Open Triangle': 'opentriangle',
198 'Mute Triangle': 'mutetriangle',
199 'Tambourine': 'tambourine',
203 def musicxml_note_to_lily_main_event (n):
207 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
210 pitch = musicxml_pitch_to_lily (mxl_pitch)
211 event = musicexp.NoteEvent()
214 acc = n.get_maybe_exist_named_child ('accidental')
216 # let's not force accs everywhere.
217 event.cautionary = acc.editorial
219 elif n.get_maybe_exist_typed_child (musicxml.Rest):
220 event = musicexp.RestEvent()
221 elif n.instrument_name:
222 event = musicexp.NoteEvent ()
223 event.drum_type = instrument_drumtype_dict[n.instrument_name]
227 n.message ("could not find suitable event")
229 event.duration = musicxml_duration_to_lily (n)
235 def __init__ (self, here, dest):
239 class LilyPondVoiceBuilder:
242 self.end_moment = Rational (0)
243 self.begin_moment = Rational (0)
244 self.pending_multibar = Rational (0)
246 def _insert_multibar (self):
247 r = musicexp.MultiMeasureRest ()
248 r.duration = musicexp.Duration()
249 r.duration.duration_log = 0
250 r.duration.factor = self.pending_multibar
251 self.elements.append (r)
252 self.begin_moment = self.end_moment
253 self.end_moment = self.begin_moment + self.pending_multibar
254 self.pending_multibar = Rational (0)
256 def add_multibar_rest (self, duration):
257 self.pending_multibar += duration
260 def add_music (self, music, duration):
261 assert isinstance (music, musicexp.Music)
262 if self.pending_multibar > Rational (0):
263 self._insert_multibar ()
265 self.elements.append (music)
266 self.begin_moment = self.end_moment
267 self.end_moment = self.begin_moment + duration
269 def add_bar_check (self, number):
270 b = musicexp.BarCheck ()
271 b.bar_number = number
272 self.add_music (b, Rational (0))
274 def jumpto (self, moment):
275 current_end = self.end_moment + self.pending_multibar
276 diff = moment - current_end
278 if diff < Rational (0):
279 raise NegativeSkip(current_end, moment)
281 if diff > Rational (0):
282 skip = musicexp.SkipEvent()
283 skip.duration.duration_log = 0
284 skip.duration.factor = diff
286 evc = musicexp.EventChord ()
287 evc.elements.append (skip)
288 self.add_music (evc, diff)
290 def last_event_chord (self, starting_at):
294 and isinstance (self.elements[-1], musicexp.EventChord)
295 and self.begin_moment == starting_at):
296 value = self.elements[-1]
298 self.jumpto (starting_at)
303 def correct_negative_skip (self, goto):
304 self.end_moment = goto
305 self.begin_moment = goto
306 evc = musicexp.EventChord ()
307 self.elements.append (evc)
309 def musicxml_voice_to_lily_voice (voice):
313 voice_builder = LilyPondVoiceBuilder()
315 for n in voice._elements:
316 if n.get_name () == 'forward':
319 if not n.get_maybe_exist_named_child ('chord'):
321 voice_builder.jumpto (n._when)
322 except NegativeSkip, neg:
323 voice_builder.correct_negative_skip (n._when)
324 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
326 if isinstance (n, musicxml.Attributes):
327 if n.is_first () and n._measure_position == Rational (0):
328 voice_builder.add_bar_check (int (n.get_parent ().number))
329 for a in musicxml_attributes_to_lily (n):
330 voice_builder.add_music (a, Rational (0))
333 if not n.__class__.__name__ == 'Note':
334 print 'not a Note or Attributes?', n
337 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
339 and rest.is_whole_measure ()):
341 voice_builder.add_multibar_rest (n._duration)
344 if n.is_first () and n._measure_position == Rational (0):
345 num = int (n.get_parent ().number)
346 voice_builder.add_bar_check (num)
348 main_event = musicxml_note_to_lily_main_event (n)
351 if main_event.drum_type:
352 modes_found['drummode'] = True
353 except AttributeError:
357 ev_chord = voice_builder.last_event_chord (n._when)
359 ev_chord = musicexp.EventChord()
360 voice_builder.add_music (ev_chord, n._duration)
362 ev_chord.append (main_event)
364 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
368 if notations.get_tuplet():
369 tuplet_event = notations.get_tuplet()
370 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
373 frac = mod.get_fraction ()
375 tuplet_events.append ((ev_chord, tuplet_event, frac))
377 slurs = [s for s in notations.get_named_children ('slur')
378 if s.get_type () in ('start','stop')]
381 print 'more than 1 slur?'
383 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
384 ev_chord.append (lily_ev)
386 mxl_tie = notations.get_tie ()
387 if mxl_tie and mxl_tie.type == 'start':
388 ev_chord.append (musicexp.TieEvent ())
390 mxl_beams = [b for b in n.get_named_children ('beam')
391 if (b.get_type () in ('begin', 'end')
392 and b.is_primary ())]
394 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
396 ev_chord.append (beam_ev)
399 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
402 frac = mod.get_fraction ()
404 tuplet_events.append ((ev_chord, tuplet_event, frac))
406 ## force trailing mm rests to be written out.
407 voice_builder.add_music (musicexp.EventChord (), Rational (0))
409 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
411 seq_music = musicexp.SequentialMusic()
413 if 'drummode' in modes_found.keys ():
414 ## \key <pitch> barfs in drummode.
415 ly_voice = [e for e in ly_voice
416 if not isinstance(e, musicexp.KeySignatureChange)]
418 seq_music.elements = ly_voice
422 if len (modes_found) > 1:
423 print 'Too many modes found', modes_found.keys ()
425 return_value = seq_music
426 for mode in modes_found.keys ():
427 v = musicexp.ModeChangingMusicWrapper()
428 v.element = return_value
435 def musicxml_id_to_lily (id):
436 digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
440 d = digits.index (dig) + 1
441 dig = dig[0].upper() + dig[1:]
442 id = re.sub ('%d' % d, dig, id)
444 id = re.sub ('[^a-zA-Z]', 'X', id)
448 def musicxml_pitch_to_lily (mxl_pitch):
450 p.alteration = mxl_pitch.get_alteration ()
451 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
452 p.octave = mxl_pitch.get_octave () - 4
455 def voices_in_part (part):
456 """Return a Name -> Voice dictionary for PART"""
458 part.extract_voices ()
459 voice_dict = part.get_voices ()
463 def voices_in_part_in_parts (parts):
464 """return a Part -> Name -> Voice dictionary"""
465 return dict([(p, voices_in_part (p)) for p in parts])
468 def get_all_voices (parts):
469 all_voices = voices_in_part_in_parts (parts)
472 for p, name_voice in all_voices.items ():
475 for n, v in name_voice.items ():
476 progress ("Converting to LilyPond expressions...")
477 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
479 all_ly_voices[p] = part_ly_voices
484 def option_parser ():
485 p = ly.get_option_parser(usage='musicxml2ly FILE.xml',
486 version = """%prog (LilyPond) @TOPLEVEL_VERSION@
488 This program is free software. It is covered by the GNU General Public
489 License and you are welcome to change it and/or distribute copies of it
490 under certain conditions. Invoke as `lilypond --warranty' for more
493 Copyright (c) 2005--2006 by
494 Han-Wen Nienhuys <hanwen@xs4all.nl> and
495 Jan Nieuwenhuizen <janneke@gnu.org>
499 """Convert MusicXML file to LilyPond input.
502 p.add_option ('-v', '--verbose',
503 action = "store_true",
507 p.add_option ('', '--lxml',
511 help="Use lxml.etree; uses less memory and cpu time.")
513 p.add_option ('-o', '--output',
519 help='set output file')
521 p.add_option_group ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
525 def music_xml_voice_name_to_lily_name (part, name):
526 str = "Part%sVoice%s" % (part.id, name)
527 return musicxml_id_to_lily (str)
529 def print_voice_definitions (printer, voices):
530 for (part, nv_dict) in voices.items():
532 for (name, (voice, mxlvoice)) in nv_dict.items ():
533 k = music_xml_voice_name_to_lily_name (part, name)
534 printer.dump ('%s = ' % k)
535 voice.print_ly (printer)
540 return dict ([(elt,1) for elt in l]).keys ()
542 def print_score_setup (printer, part_list, voices):
543 part_dict = dict ([(p.id, p) for p in voices.keys ()])
547 for part_definition in part_list:
548 part_name = part_definition.id
550 part = part_dict[part_name]
552 print 'unknown part in part-list:', part_name
555 nv_dict = voices[part]
556 staves = reduce (lambda x,y: x+ y,
557 [mxlvoice._staves.keys ()
558 for (v, mxlvoice) in nv_dict.values ()],
562 staves = uniq_list (staves)
564 printer ('\\context PianoStaff << ')
568 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
569 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
570 if mxlvoice._start_staff == s]
572 printer ('\\context Staff = "%s" << ' % s)
574 for v in staff_voices:
575 printer ('\\context Voice = "%s" \\%s' % (v,v))
584 printer ('\\new Staff <<')
586 for (n,v) in nv_dict.items ():
588 n = music_xml_voice_name_to_lily_name (part, n)
589 printer ('\\context Voice = "%s" \\%s' % (n,n))
596 def print_ly_preamble (printer, filename):
597 printer.dump_version ()
598 printer.print_verbatim ('%% converted from %s\n' % filename)
600 def read_musicxml (filename, use_lxml):
604 tree = lxml.etree.parse (filename)
605 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
608 from xml.dom import minidom, Node
610 doc = minidom.parse(filename)
611 node = doc.documentElement
612 return musicxml.minidom_demarshal_node (node)
617 def convert (filename, options):
618 progress ("Reading MusicXML from %s ..." % filename)
620 tree = read_musicxml (filename, options.use_lxml)
623 id_instrument_map = {}
624 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
625 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
626 part_list = mxl_pl.get_named_children ("score-part")
628 parts = tree.get_typed_children (musicxml.Part)
629 voices = get_all_voices (parts)
631 if not options.output_name:
632 options.output_name = os.path.basename (filename)
633 options.output_name = os.path.splitext (options.output_name)[0]
636 defs_ly_name = options.output_name + '-defs.ly'
637 driver_ly_name = options.output_name + '.ly'
639 printer = musicexp.Output_printer()
640 progress ("Output to `%s'" % defs_ly_name)
641 printer.set_file (open (defs_ly_name, 'w'))
643 print_ly_preamble (printer, filename)
644 print_voice_definitions (printer, voices)
649 progress ("Output to `%s'" % driver_ly_name)
650 printer = musicexp.Output_printer()
651 printer.set_file (open (driver_ly_name, 'w'))
652 print_ly_preamble (printer, filename)
653 printer.dump (r'\include "%s"' % defs_ly_name)
654 print_score_setup (printer, part_list, voices)
661 opt_parser = option_parser()
663 (options, args) = opt_parser.parse_args ()
665 opt_parser.print_usage()
668 voices = convert (args[0], options)
670 if __name__ == '__main__':