8 from gettext import gettext as _
14 datadir = '@local_lilypond_datadir@'
15 if not os.path.isdir (datadir):
16 datadir = '@lilypond_datadir@'
17 if os.environ.has_key ('LILYPONDPREFIX'):
18 datadir = os.environ['LILYPONDPREFIX']
19 while datadir[-1] == os.sep:
20 datadir = datadir[:-1]
22 if os.path.exists (os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')):
23 datadir = os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')
24 elif os.path.exists (os.path.join (datadir, 'share/lilypond/current/')):
25 datadir = os.path.join (datadir, 'share/lilypond/current/')
27 sys.path.insert (0, os.path.join (datadir, 'python'))
29 # dynamic relocation, for GUB binaries.
30 bindir = os.path.split (sys.argv[0])[0]
32 for prefix_component in ['share', 'lib']:
33 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
34 sys.path.insert (0, datadir)
42 from rational import Rational
46 sys.stderr.write (str + '\n')
50 def musicxml_duration_to_lily (mxl_note):
51 d = musicexp.Duration ()
52 if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
53 d.duration_log = mxl_note.get_duration_log ()
57 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
58 d.factor = mxl_note._duration / d.get_length ()
62 def group_tuplets (music_list, events):
65 """Collect Musics from
66 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
73 for (ev_chord, tuplet_elt, fraction) in events:
74 while (j < len (music_list)):
75 if music_list[j]== ev_chord:
78 if tuplet_elt.type == 'start':
79 indices.append ((j, None, fraction))
80 elif tuplet_elt.type == 'stop':
81 indices[-1] = (indices[-1][0], j, indices[-1][2])
85 for (i1, i2, frac) in indices:
89 new_list.extend (music_list[last:i1])
90 seq = musicexp.SequentialMusic ()
92 seq.elements = music_list[i1:last]
94 tsm = musicexp.TimeScaledMusic ()
97 tsm.numerator = frac[0]
98 tsm.denominator = frac[1]
100 new_list.append (tsm)
102 new_list.extend (music_list[last:])
106 def musicxml_clef_to_lily (attributes):
107 change = musicexp.ClefChange ()
108 change.type = attributes.get_clef_sign ()
111 def musicxml_time_to_lily (attributes):
112 (beats, type) = attributes.get_time_signature ()
114 change = musicexp.TimeSignatureChange()
115 change.fraction = (beats, type)
119 def musicxml_key_to_lily (attributes):
120 start_pitch = musicexp.Pitch ()
121 (fifths, mode) = attributes.get_key_signature ()
128 start_pitch.alteration = a
130 print 'unknown mode', mode
132 fifth = musicexp.Pitch()
139 start_pitch = musicexp.Pitch()
140 for x in range (fifths):
141 start_pitch = start_pitch.transposed (fifth)
143 start_pitch.octave = 0
145 change = musicexp.KeySignatureChange()
147 change.tonic = start_pitch
150 def musicxml_attributes_to_lily (attrs):
153 'clef': musicxml_clef_to_lily,
154 'time': musicxml_time_to_lily,
155 'key': musicxml_key_to_lily
157 for (k, func) in attr_dispatch.items ():
158 childs = attrs.get_named_children (k)
160 ## ugh: you get clefs spread over staves for piano
162 elts.append (func (attrs))
166 spanner_event_dict = {
167 'slur' : musicexp.SlurEvent,
168 'beam' : musicexp.BeamEvent,
170 spanner_type_dict = {
177 def musicxml_spanner_to_lily_event (mxl_event):
180 name = mxl_event.get_name()
182 func = spanner_event_dict[name]
185 print 'unknown span event ', mxl_event
188 key = mxl_event.get_type ()
189 ev.span_direction = spanner_type_dict[key]
191 print 'unknown span type', key, 'for', name
195 instrument_drumtype_dict = {
196 'Acoustic Snare Drum': 'acousticsnare',
197 'Side Stick': 'sidestick',
198 'Open Triangle': 'opentriangle',
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):
292 and isinstance (self.elements[-1], musicexp.EventChord)
293 and self.begin_moment == starting_at):
294 return self.elements[-1]
296 self.jumpto (starting_at)
298 def correct_negative_skip (self, goto):
299 self.end_moment = goto
300 self.begin_moment = goto
301 evc = musicexp.EventChord ()
302 self.elements.append (evc)
304 def musicxml_voice_to_lily_voice (voice):
308 voice_builder = LilyPondVoiceBuilder()
309 for n in voice._elements:
310 if n.get_name () == 'forward':
314 voice_builder.jumpto (n._when)
315 except NegativeSkip, neg:
316 voice_builder.correct_negative_skip (n._when)
317 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
319 if isinstance (n, musicxml.Attributes):
320 if n.is_first () and n._measure_position == Rational (0):
321 voice_builder.add_bar_check (int (n.get_parent ().number))
322 for a in musicxml_attributes_to_lily (n):
323 voice_builder.add_music (a, Rational (0))
326 if not n.__class__.__name__ == 'Note':
327 print 'not a Note or Attributes?', n
330 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
332 and rest.is_whole_measure ()):
334 voice_builder.add_multibar_rest (n._duration)
337 if n.is_first () and n._measure_position == Rational (0):
338 num = int (n.get_parent ().number)
339 voice_builder.add_bar_check (num)
341 main_event = musicxml_note_to_lily_main_event (n)
344 if main_event.drum_type:
345 modes_found['drummode'] = True
346 except AttributeError:
350 ev_chord = voice_builder.last_event_chord (n._when)
352 ev_chord = musicexp.EventChord()
355 ev_chord.append (main_event)
356 voice_builder.add_music (ev_chord, n._duration)
358 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
362 if notations.get_tuplet():
363 tuplet_event = notations.get_tuplet()
364 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
367 frac = mod.get_fraction ()
369 tuplet_events.append ((ev_chord, tuplet_event, frac))
371 slurs = [s for s in notations.get_named_children ('slur')
372 if s.get_type () in ('start','stop')]
375 print 'more than 1 slur?'
377 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
378 ev_chord.append (lily_ev)
380 mxl_tie = notations.get_tie ()
381 if mxl_tie and mxl_tie.type == 'start':
382 ev_chord.append (musicexp.TieEvent ())
384 mxl_beams = [b for b in n.get_named_children ('beam')
385 if (b.get_type () in ('begin', 'end')
386 and b.is_primary ())]
388 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
390 ev_chord.append (beam_ev)
393 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
396 frac = mod.get_fraction ()
398 tuplet_events.append ((ev_chord, tuplet_event, frac))
400 ## force trailing mm rests to be written out.
401 voice_builder.add_music (musicexp.EventChord ())
403 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
405 seq_music = musicexp.SequentialMusic()
407 if 'drummode' in modes_found.keys ():
408 ## \key <pitch> barfs in drummode.
409 ly_voice = [e for e in ly_voice
410 if not isinstance(e, musicexp.KeySignatureChange)]
412 seq_music.elements = ly_voice
416 if len (modes_found) > 1:
417 print 'Too many modes found', modes_found.keys ()
419 return_value = seq_music
420 for mode in modes_found.keys ():
421 v = musicexp.ModeChangingMusicWrapper()
422 v.element = return_value
429 def musicxml_id_to_lily (id):
430 digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
434 d = digits.index (dig) + 1
435 dig = dig[0].upper() + dig[1:]
436 id = re.sub ('%d' % d, dig, id)
438 id = re.sub ('[^a-zA-Z]', 'X', id)
442 def musicxml_pitch_to_lily (mxl_pitch):
444 p.alteration = mxl_pitch.get_alteration ()
445 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
446 p.octave = mxl_pitch.get_octave () - 4
449 def voices_in_part (part):
450 """Return a Name -> Voice dictionary for PART"""
452 part.extract_voices ()
453 voice_dict = part.get_voices ()
457 def voices_in_part_in_parts (parts):
458 """return a Part -> Name -> Voice dictionary"""
459 return dict([(p, voices_in_part (p)) for p in parts])
462 def get_all_voices (parts):
463 all_voices = voices_in_part_in_parts (parts)
466 for p, name_voice in all_voices.items ():
469 for n, v in name_voice.items ():
470 progress ("Converting to LilyPond expressions...")
471 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
473 all_ly_voices[p] = part_ly_voices
478 def option_parser ():
479 p = ly.get_option_parser(usage='musicxml2ly FILE.xml',
480 version = """%prog (LilyPond) @TOPLEVEL_VERSION@
482 This program is free software. It is covered by the GNU General Public
483 License and you are welcome to change it and/or distribute copies of it
484 under certain conditions. Invoke as `lilypond --warranty' for more
487 Copyright (c) 2005--2006 by
488 Han-Wen Nienhuys <hanwen@xs4all.nl> and
489 Jan Nieuwenhuizen <janneke@gnu.org>
493 """Convert MusicXML file to LilyPond input.
496 p.add_option ('-v', '--verbose',
497 action = "store_true",
501 p.add_option ('', '--lxml',
505 help="Use lxml.etree; uses less memory and cpu time.")
507 p.add_option ('-o', '--output',
513 help='set output file')
515 p.add_option_group ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
519 def music_xml_voice_name_to_lily_name (part, name):
520 str = "Part%sVoice%s" % (part.id, name)
521 return musicxml_id_to_lily (str)
523 def print_voice_definitions (printer, voices):
524 for (part, nv_dict) in voices.items():
526 for (name, (voice, mxlvoice)) in nv_dict.items ():
527 k = music_xml_voice_name_to_lily_name (part, name)
528 printer.dump ('%s = ' % k)
529 voice.print_ly (printer)
534 return dict ([(elt,1) for elt in l]).keys ()
536 def print_score_setup (printer, part_list, voices):
537 part_dict = dict ([(p.id, p) for p in voices.keys ()])
541 for part_definition in part_list:
542 part_name = part_definition.id
544 part = part_dict[part_name]
546 print 'unknown part in part-list:', part_name
549 nv_dict = voices[part]
550 staves = reduce (lambda x,y: x+ y,
551 [mxlvoice._staves.keys ()
552 for (v, mxlvoice) in nv_dict.values ()],
556 staves = uniq_list (staves)
558 printer ('\\context PianoStaff << ')
562 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
563 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
564 if mxlvoice._start_staff == s]
566 printer ('\\context Staff = "%s" << ' % s)
568 for v in staff_voices:
569 printer ('\\context Voice = "%s" \\%s' % (v,v))
578 printer ('\\new Staff <<')
580 for (n,v) in nv_dict.items ():
582 n = music_xml_voice_name_to_lily_name (part, n)
583 printer ('\\context Voice = "%s" \\%s' % (n,n))
590 def print_ly_preamble (printer, filename):
591 printer.dump_version ()
592 printer.print_verbatim ('%% converted from %s\n' % filename)
594 def read_musicxml (filename, use_lxml):
598 tree = lxml.etree.parse (filename)
599 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
602 from xml.dom import minidom, Node
604 doc = minidom.parse(filename)
605 node = doc.documentElement
606 return musicxml.minidom_demarshal_node (node)
611 def convert (filename, options):
612 progress ("Reading MusicXML from %s ..." % filename)
614 tree = read_musicxml (filename, options.use_lxml)
617 id_instrument_map = {}
618 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
619 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
620 part_list = mxl_pl.get_named_children ("score-part")
622 parts = tree.get_typed_children (musicxml.Part)
623 voices = get_all_voices (parts)
625 if not options.output_name:
626 options.output_name = os.path.basename (filename)
627 options.output_name = os.path.splitext (options.output_name)[0]
630 defs_ly_name = options.output_name + '-defs.ly'
631 driver_ly_name = options.output_name + '.ly'
633 printer = musicexp.Output_printer()
634 progress ("Output to `%s'" % defs_ly_name)
635 printer.set_file (open (defs_ly_name, 'w'))
637 print_ly_preamble (printer, filename)
638 print_voice_definitions (printer, voices)
643 progress ("Output to `%s'" % driver_ly_name)
644 printer = musicexp.Output_printer()
645 printer.set_file (open (driver_ly_name, 'w'))
646 print_ly_preamble (printer, filename)
647 printer.dump (r'\include "%s"' % defs_ly_name)
648 print_score_setup (printer, part_list, voices)
655 opt_parser = option_parser()
657 (options, args) = opt_parser.parse_args ()
659 opt_parser.print_usage()
662 voices = convert (args[0], options)
664 if __name__ == '__main__':