8 from gettext import gettext as _
11 datadir = '@local_lilypond_datadir@'
12 if not os.path.isdir (datadir):
13 datadir = '@lilypond_datadir@'
14 if os.environ.has_key ('LILYPONDPREFIX'):
15 datadir = os.environ['LILYPONDPREFIX']
16 while datadir[-1] == os.sep:
17 datadir = datadir[:-1]
19 if os.path.exists (os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')):
20 datadir = os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')
21 elif os.path.exists (os.path.join (datadir, 'share/lilypond/current/')):
22 datadir = os.path.join (datadir, 'share/lilypond/current/')
24 sys.path.insert (0, os.path.join (datadir, 'python'))
26 # dynamic relocation, for GUB binaries.
27 bindir = os.path.split (sys.argv[0])[0]
29 for prefix_component in ['share', 'lib']:
30 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
31 sys.path.insert (0, datadir)
39 from rational import Rational
43 sys.stderr.write (str + '\n')
47 def musicxml_duration_to_lily (mxl_note):
48 d = musicexp.Duration ()
49 if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
50 d.duration_log = mxl_note.get_duration_log ()
54 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
55 d.factor = mxl_note._duration / d.get_length ()
59 def group_tuplets (music_list, events):
62 """Collect Musics from
63 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
70 for (ev_chord, tuplet_elt, fraction) in events:
71 while (j < len (music_list)):
72 if music_list[j]== ev_chord:
75 if tuplet_elt.type == 'start':
76 indices.append ((j, None, fraction))
77 elif tuplet_elt.type == 'stop':
78 indices[-1] = (indices[-1][0], j, indices[-1][2])
82 for (i1, i2, frac) in indices:
86 new_list.extend (music_list[last:i1])
87 seq = musicexp.SequentialMusic ()
89 seq.elements = music_list[i1:last]
91 tsm = musicexp.TimeScaledMusic ()
94 tsm.numerator = frac[0]
95 tsm.denominator = frac[1]
99 new_list.extend (music_list[last:])
103 def musicxml_clef_to_lily (mxl):
104 sign = mxl.get_maybe_exist_named_child ('sign')
105 change = musicexp.ClefChange ()
107 change.type = sign.get_text ()
111 def musicxml_time_to_lily (mxl):
112 beats = mxl.get_maybe_exist_named_child ('beats')
113 type = mxl.get_maybe_exist_named_child ('beat-type')
114 change = musicexp.TimeSignatureChange()
115 change.fraction = (string.atoi(beats.get_text ()),
116 string.atoi(type.get_text ()))
120 def musicxml_key_to_lily (mxl):
121 start_pitch = musicexp.Pitch ()
123 mode = mxl.get_maybe_exist_named_child ('mode')
125 mode = mode.get_text ()
129 (n,a) = { 'major' : (0,0),
133 start_pitch.alteration = a
135 print 'unknown mode', mode
137 fifths = string.atoi (mxl.get_maybe_exist_named_child ('fifths').get_text ())
139 fifth = musicexp.Pitch()
146 start_pitch = musicexp.Pitch()
147 for x in range (fifths):
148 start_pitch = start_pitch.transposed (fifth)
150 start_pitch.octave = 0
152 change = musicexp.KeySignatureChange()
154 change.tonic = start_pitch
157 def musicxml_attributes_to_lily (attrs):
160 'clef': musicxml_clef_to_lily,
161 'time': musicxml_time_to_lily,
162 'key': musicxml_key_to_lily
164 for (k, func) in attr_dispatch.items ():
165 childs = attrs.get_named_children (k)
167 ## ugh: you get clefs spread over staves for piano
169 elts.append (func (childs[0]))
173 def create_skip_music (duration):
174 skip = musicexp.SkipEvent()
175 skip.duration.duration_log = 0
176 skip.duration.factor = duration
178 evc = musicexp.EventChord ()
182 spanner_event_dict = {
183 'slur' : musicexp.SlurEvent,
184 'beam' : musicexp.BeamEvent,
186 spanner_type_dict = {
193 def musicxml_spanner_to_lily_event (mxl_event):
196 name = mxl_event.get_name()
198 func = spanner_event_dict[name]
201 print 'unknown span event ', mxl_event
204 key = mxl_event.get_type ()
205 ev.span_direction = spanner_type_dict[key]
207 print 'unknown span type', key, 'for', name
211 def musicxml_note_to_lily_main_event (n):
215 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
218 pitch = musicxml_pitch_to_lily (mxl_pitch)
219 event = musicexp.NoteEvent()
222 acc = n.get_maybe_exist_named_child ('accidental')
224 # let's not force accs everywhere.
225 event.cautionary = acc.editorial
227 elif n.get_maybe_exist_typed_child (musicxml.Rest):
228 event = musicexp.RestEvent()
230 event.duration = musicxml_duration_to_lily (n)
233 def musicxml_voice_to_lily_voice (voice):
235 ly_now = Rational (0)
236 pending_skip = Rational (0)
240 for n in voice._elements:
241 if n.get_name () == 'forward':
244 if isinstance (n, musicxml.Attributes):
245 ly_now += pending_skip
246 pending_skip = Rational (0)
248 ly_voice.extend (musicxml_attributes_to_lily (n))
251 if not n.__class__.__name__ == 'Note':
252 print 'not a Note or Attributes?', n
255 if n.is_first () and ly_voice:
256 ly_voice[-1].comment += '\n'
259 main_event = musicxml_note_to_lily_main_event (n)
262 if None == n.get_maybe_exist_typed_child (musicxml.Chord):
263 ly_now += pending_skip
264 pending_skip = main_event.get_length ()
266 if ly_now <> n._when:
267 diff = n._when - ly_now
269 if diff < Rational (0):
270 print 'huh: negative skip', n._when, ly_now, n._duration
271 diff = Rational (1,314159265)
273 ly_voice.append (create_skip_music (diff))
276 ly_voice.append (musicexp.EventChord())
280 ev_chord = ly_voice[-1]
281 ev_chord.append (main_event)
283 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
287 if notations.get_tuplet():
288 tuplet_event = notations.get_tuplet()
289 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
292 frac = mod.get_fraction ()
294 tuplet_events.append ((ev_chord, tuplet_event, frac))
296 slurs = [s for s in notations.get_named_children ('slur')
297 if s.get_type () in ('start','stop')]
300 print 'more than 1 slur?'
302 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
303 ev_chord.append (lily_ev)
305 mxl_tie = notations.get_tie ()
306 if mxl_tie and mxl_tie.type == 'start':
307 ev_chord.append (musicexp.TieEvent ())
309 mxl_beams = [b for b in n.get_named_children ('beam')
310 if b.get_type () in ('begin', 'end')]
312 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
314 ev_chord.append (beam_ev)
317 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
320 frac = mod.get_fraction ()
322 tuplet_events.append ((ev_chord, tuplet_event, frac))
324 ly_voice = group_tuplets (ly_voice, tuplet_events)
326 seq_music = musicexp.SequentialMusic()
328 seq_music.elements = ly_voice
332 def musicxml_id_to_lily (id):
333 digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
337 d = digits.index (dig) + 1
338 dig = dig[0].upper() + dig[1:]
339 id = re.sub ('%d' % d, dig, id)
341 id = re.sub ('[^a-zA-Z]', 'X', id)
345 def musicxml_pitch_to_lily (mxl_pitch):
347 p.alteration = mxl_pitch.get_alteration ()
348 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
349 p.octave = mxl_pitch.get_octave () - 4
354 def voices_in_part (part):
355 """Return a Name -> Voice dictionary for PART"""
357 part.extract_voices ()
358 voice_dict = part.get_voices ()
362 def voices_in_part_in_parts (parts):
363 """return a Part -> Name -> Voice dictionary"""
364 return dict([(p, voices_in_part (p)) for p in parts])
367 def get_all_voices (parts):
368 all_voices = voices_in_part_in_parts (parts)
371 for p, name_voice in all_voices.items ():
374 for n, v in name_voice.items ():
375 progress ("Converting to LilyPond expressions...")
376 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
378 all_ly_voices[p] = part_ly_voices
383 def option_parser ():
384 p = ly.get_option_parser(usage='musicxml2ly FILE.xml',
385 version = """%prog (LilyPond) @TOPLEVEL_VERSION@
387 This program is free software. It is covered by the GNU General Public
388 License and you are welcome to change it and/or distribute copies of it
389 under certain conditions. Invoke as `lilypond --warranty' for more
392 Copyright (c) 2005--2006 by
393 Han-Wen Nienhuys <hanwen@xs4all.nl> and
394 Jan Nieuwenhuizen <janneke@gnu.org>
398 """Convert MusicXML file to LilyPond input.
401 p.add_option ('-v', '--verbose',
402 action = "store_true",
405 p.add_option ('-o', '--output',
411 help = 'set output file')
413 p.add_option_group ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
417 def music_xml_voice_name_to_lily_name (part, name):
418 str = "Part%sVoice%s" % (part.id, name)
419 return musicxml_id_to_lily (str)
421 def print_voice_definitions (printer, voices):
422 for (part, nv_dict) in voices.items():
423 for (name, (voice, mxlvoice)) in nv_dict.items ():
424 k = music_xml_voice_name_to_lily_name (part, name)
425 printer.dump ('%s = ' % k)
426 voice.print_ly (printer)
429 return dict ([(elt,1) for elt in l]).keys ()
431 def print_score_setup (printer, part_list, voices):
432 part_dict = dict ([(p.id, p) for p in voices.keys ()])
436 for part_definition in part_list:
437 part_name = part_definition.id
439 part = part_dict[part_name]
441 print 'unknown part in part-list:', part_name
444 nv_dict = voices[part]
445 staves = reduce (lambda x,y: x+ y,
446 [mxlvoice._staves.keys ()
447 for (v, mxlvoice) in nv_dict.values ()],
451 staves = uniq_list (staves)
453 printer ('\\context PianoStaff << ')
457 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
458 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
459 if mxlvoice._start_staff == s]
461 printer ('\\context Staff = "%s" << ' % s)
463 for v in staff_voices:
464 printer ('\\context Voice = "%s" \\%s' % (v,v))
473 printer ('\\new Staff <<')
475 for (n,v) in nv_dict.items ():
477 n = music_xml_voice_name_to_lily_name (part, n)
478 printer ('\\context Voice = "%s" \\%s' % (n,n))
488 def print_ly_preamble (printer, filename):
489 printer.dump_version ()
490 printer.print_verbatim ('%% converted from %s\n' % filename)
492 def convert (filename, output_name):
493 printer = musicexp.Output_printer()
494 progress ("Reading MusicXML...")
496 tree = musicxml.read_musicxml (filename)
497 parts = tree.get_typed_children (musicxml.Part)
498 voices = get_all_voices (parts)
501 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
502 pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
503 part_list = pl.get_named_children ("score-part")
506 output_name = os.path.basename (filename)
507 output_name = os.path.splitext (output_name)[0] + '.ly'
511 progress ("Output to `%s'" % output_name)
512 printer.set_file (open (output_name, 'w'))
514 progress ("Printing as .ly...")
516 print_ly_preamble (printer, filename)
517 print_voice_definitions (printer, voices)
518 print_score_setup (printer, part_list, voices)
524 opt_parser = option_parser()
526 (options, args) = opt_parser.parse_args ()
528 opt_parser.print_usage()
531 voices = convert (args[0], options.output)
533 if __name__ == '__main__':