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'))
31 from rational import Rational
35 sys.stderr.write (str + '\n')
39 def musicxml_duration_to_lily (mxl_note):
40 d = musicexp.Duration ()
41 if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
42 d.duration_log = mxl_note.get_duration_log ()
46 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
47 d.factor = mxl_note._duration / d.get_length ()
51 def group_tuplets (music_list, events):
54 """Collect Musics from
55 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
62 for (ev_chord, tuplet_elt, fraction) in events:
63 while (j < len (music_list)):
64 if music_list[j]== ev_chord:
67 if tuplet_elt.type == 'start':
68 indices.append ((j, None, fraction))
69 elif tuplet_elt.type == 'stop':
70 indices[-1] = (indices[-1][0], j, indices[-1][2])
74 for (i1, i2, frac) in indices:
78 new_list.extend (music_list[last:i1])
79 seq = musicexp.SequentialMusic ()
81 seq.elements = music_list[i1:last]
83 tsm = musicexp.TimeScaledMusic ()
86 tsm.numerator = frac[0]
87 tsm.denominator = frac[1]
91 new_list.extend (music_list[last:])
95 def musicxml_clef_to_lily (mxl):
96 sign = mxl.get_maybe_exist_named_child ('sign')
97 change = musicexp.ClefChange ()
99 change.type = sign.get_text ()
103 def musicxml_time_to_lily (mxl):
104 beats = mxl.get_maybe_exist_named_child ('beats')
105 type = mxl.get_maybe_exist_named_child ('beat-type')
106 change = musicexp.TimeSignatureChange()
107 change.fraction = (string.atoi(beats.get_text ()),
108 string.atoi(type.get_text ()))
112 def musicxml_key_to_lily (mxl):
113 start_pitch = musicexp.Pitch ()
115 mode = mxl.get_maybe_exist_named_child ('mode')
117 mode = mode.get_text ()
121 (n,a) = { 'major' : (0,0),
125 start_pitch.alteration = a
127 print 'unknown mode', mode
129 fifths = string.atoi (mxl.get_maybe_exist_named_child ('fifths').get_text ())
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 (childs[0]))
165 def create_skip_music (duration):
166 skip = musicexp.SkipEvent()
167 skip.duration.duration_log = 0
168 skip.duration.factor = duration
170 evc = musicexp.EventChord ()
174 spanner_event_dict = {
175 'slur' : musicexp.SlurEvent,
176 'beam' : musicexp.BeamEvent,
178 spanner_type_dict = {
185 def musicxml_spanner_to_lily_event (mxl_event):
188 name = mxl_event.get_name()
190 func = spanner_event_dict[name]
193 print 'unknown span event ', mxl_event
196 key = mxl_event.get_type ()
197 ev.span_direction = spanner_type_dict[key]
199 print 'unknown span type', key, 'for', name
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()
222 event.duration = musicxml_duration_to_lily (n)
225 def musicxml_voice_to_lily_voice (voice):
227 ly_now = Rational (0)
228 pending_skip = Rational (0)
232 for n in voice._elements:
233 if n.get_name () == 'forward':
236 if isinstance (n, musicxml.Attributes):
237 ly_now += pending_skip
238 pending_skip = Rational (0)
240 ly_voice.extend (musicxml_attributes_to_lily (n))
243 if not n.__class__.__name__ == 'Note':
244 print 'not a Note or Attributes?', n
247 if n.is_first () and ly_voice:
248 ly_voice[-1].comment += '\n'
251 main_event = musicxml_note_to_lily_main_event (n)
254 if None == n.get_maybe_exist_typed_child (musicxml.Chord):
255 ly_now += pending_skip
256 pending_skip = main_event.get_length ()
258 if ly_now <> n._when:
259 diff = n._when - ly_now
261 if diff < Rational (0):
262 print 'huh: negative skip', n._when, ly_now, n._duration
263 diff = Rational (1,314159265)
265 ly_voice.append (create_skip_music (diff))
268 ly_voice.append (musicexp.EventChord())
272 ev_chord = ly_voice[-1]
273 ev_chord.append (main_event)
275 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
279 if notations.get_tuplet():
280 tuplet_event = notations.get_tuplet()
281 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
284 frac = mod.get_fraction ()
286 tuplet_events.append ((ev_chord, tuplet_event, frac))
288 slurs = [s for s in notations.get_named_children ('slur')
289 if s.get_type () in ('start','stop')]
292 print 'more than 1 slur?'
294 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
295 ev_chord.append (lily_ev)
297 mxl_tie = notations.get_tie ()
298 if mxl_tie and mxl_tie.type == 'start':
299 ev_chord.append (musicexp.TieEvent ())
301 mxl_beams = [b for b in n.get_named_children ('beam')
302 if b.get_type () in ('begin', 'end')]
304 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
306 ev_chord.append (beam_ev)
309 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
312 frac = mod.get_fraction ()
314 tuplet_events.append ((ev_chord, tuplet_event, frac))
316 ly_voice = group_tuplets (ly_voice, tuplet_events)
318 seq_music = musicexp.SequentialMusic()
320 seq_music.elements = ly_voice
324 def musicxml_id_to_lily (id):
325 digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
329 d = digits.index (dig) + 1
330 dig = dig[0].upper() + dig[1:]
331 id = re.sub ('%d' % d, dig, id)
333 id = re.sub ('[^a-zA-Z]', 'X', id)
337 def musicxml_pitch_to_lily (mxl_pitch):
339 p.alteration = mxl_pitch.get_alteration ()
340 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
341 p.octave = mxl_pitch.get_octave () - 4
346 def voices_in_part (part):
347 """Return a Name -> Voice dictionary for PART"""
349 part.extract_voices ()
350 voice_dict = part.get_voices ()
354 def voices_in_part_in_parts (parts):
355 """return a Part -> Name -> Voice dictionary"""
356 return dict([(p, voices_in_part (p)) for p in parts])
359 def get_all_voices (parts):
360 all_voices = voices_in_part_in_parts (parts)
363 for p, name_voice in all_voices.items ():
366 for n, v in name_voice.items ():
367 progress ("Converting to LilyPond expressions...")
368 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
370 all_ly_voices[p] = part_ly_voices
375 def option_parser ():
376 p = ly.get_option_parser(usage='musicxml2ly FILE.xml',
377 version = """%prog (LilyPond) @TOPLEVEL_VERSION@
379 This program is free software. It is covered by the GNU General Public
380 License and you are welcome to change it and/or distribute copies of it
381 under certain conditions. Invoke as `lilypond --warranty' for more
384 Copyright (c) 2005--2006 by
385 Han-Wen Nienhuys <hanwen@xs4all.nl> and
386 Jan Nieuwenhuizen <janneke@gnu.org>
390 """Convert MusicXML file to LilyPond input.
393 p.add_option ('-v', '--verbose',
394 action = "store_true",
397 p.add_option ('-o', '--output',
403 help = 'set output file')
405 p.add_option_group ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
409 def music_xml_voice_name_to_lily_name (part, name):
410 str = "Part%sVoice%s" % (part.id, name)
411 return musicxml_id_to_lily (str)
413 def print_voice_definitions (printer, voices):
414 for (part, nv_dict) in voices.items():
415 for (name, (voice, mxlvoice)) in nv_dict.items ():
416 k = music_xml_voice_name_to_lily_name (part, name)
417 printer.dump ('%s = ' % k)
418 voice.print_ly (printer)
421 return dict ([(elt,1) for elt in l]).keys ()
423 def print_score_setup (printer, part_list, voices):
424 part_dict = dict ([(p.id, p) for p in voices.keys ()])
428 for part_definition in part_list:
429 part_name = part_definition.id
431 part = part_dict[part_name]
433 print 'unknown part in part-list:', part_name
436 nv_dict = voices[part]
437 staves = reduce (lambda x,y: x+ y,
438 [mxlvoice._staves.keys ()
439 for (v, mxlvoice) in nv_dict.values ()],
443 staves = uniq_list (staves)
445 printer ('\\context PianoStaff << ')
449 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
450 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
451 if mxlvoice._start_staff == s]
453 printer ('\\context Staff = "%s" << ' % s)
455 for v in staff_voices:
456 printer ('\\context Voice = "%s" \\%s' % (v,v))
465 printer ('\\new Staff <<')
467 for (n,v) in nv_dict.items ():
469 n = music_xml_voice_name_to_lily_name (part, n)
470 printer ('\\context Voice = "%s" \\%s' % (n,n))
480 def print_ly_preamble (printer, filename):
481 printer.dump_version ()
482 printer.print_verbatim ('%% converted from %s\n' % filename)
484 def convert (filename, output_name):
485 printer = musicexp.Output_printer()
486 progress ("Reading MusicXML...")
488 tree = musicxml.read_musicxml (filename)
489 parts = tree.get_typed_children (musicxml.Part)
490 voices = get_all_voices (parts)
493 if tree.get_maybe_exist_typed_child (musicxml.Part_list):
494 pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
495 part_list = pl.get_named_children ("score-part")
498 output_name = os.path.basename (filename)
499 output_name = os.path.splitext (output_name)[0] + '.ly'
503 progress ("Output to `%s'" % output_name)
504 printer.set_file (open (output_name, 'w'))
506 progress ("Printing as .ly...")
508 print_ly_preamble (printer, filename)
509 print_voice_definitions (printer, voices)
510 print_score_setup (printer, part_list, voices)
516 opt_parser = option_parser()
518 (options, args) = opt_parser.parse_args ()
520 opt_parser.print_usage()
523 voices = convert (args[0], options.output)
525 if __name__ == '__main__':