8 from gettext import gettext as _
10 datadir = '@local_lilypond_datadir@'
11 if not os.path.isdir (datadir):
12 datadir = '@lilypond_datadir@'
13 if os.environ.has_key ('LILYPONDPREFIX'):
14 datadir = os.environ['LILYPONDPREFIX']
15 while datadir[-1] == os.sep:
16 datadir = datadir[:-1]
18 if os.path.exists (os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')):
19 datadir = os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')
20 elif os.path.exists (os.path.join (datadir, 'share/lilypond/current/')):
21 datadir = os.path.join (datadir, 'share/lilypond/current/')
23 sys.path.insert (0, os.path.join (datadir, 'python'))
28 from rational import Rational
32 sys.stderr.write (str + '\n')
36 def musicxml_duration_to_lily (mxl_note):
37 d = musicexp.Duration ()
38 if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
39 d.duration_log = mxl_note.get_duration_log ()
43 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
44 d.factor = mxl_note._duration / d.get_length ()
48 def group_tuplets (music_list, events):
51 """Collect Musics from
52 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
59 for (ev_chord, tuplet_elt, fraction) in events:
60 while (j < len (music_list)):
61 if music_list[j]== ev_chord:
64 if tuplet_elt.type == 'start':
65 indices.append ((j, None, fraction))
66 elif tuplet_elt.type == 'stop':
67 indices[-1] = (indices[-1][0], j, indices[-1][2])
71 for (i1, i2, frac) in indices:
75 new_list.extend (music_list[last:i1])
76 seq = musicexp.SequentialMusic ()
78 seq.elements = music_list[i1:last]
80 tsm = musicexp.TimeScaledMusic ()
83 tsm.numerator = frac[0]
84 tsm.denominator = frac[1]
88 new_list.extend (music_list[last:])
92 def musicxml_clef_to_lily (mxl):
93 sign = mxl.get_maybe_exist_named_child ('sign')
94 change = musicexp.ClefChange ()
96 change.type = sign.get_text ()
100 def musicxml_time_to_lily (mxl):
101 beats = mxl.get_maybe_exist_named_child ('beats')
102 type = mxl.get_maybe_exist_named_child ('beat-type')
103 change = musicexp.TimeSignatureChange()
104 change.fraction = (string.atoi(beats.get_text ()),
105 string.atoi(type.get_text ()))
109 def musicxml_key_to_lily (mxl):
110 start_pitch = musicexp.Pitch ()
112 mode = mxl.get_maybe_exist_named_child ('mode')
114 mode = mode.get_text ()
118 (n,a) = { 'major' : (0,0),
122 start_pitch.alteration = a
124 print 'unknown mode', mode
126 fifths = string.atoi (mxl.get_maybe_exist_named_child ('fifths').get_text ())
128 fifth = musicexp.Pitch()
135 start_pitch = musicexp.Pitch()
136 for x in range (fifths):
137 start_pitch = start_pitch.transposed (fifth)
139 start_pitch.octave = 0
141 change = musicexp.KeySignatureChange()
143 change.tonic = start_pitch
146 def musicxml_attributes_to_lily (attrs):
149 'clef': musicxml_clef_to_lily,
150 'time': musicxml_time_to_lily,
151 'key': musicxml_key_to_lily
153 for (k, func) in attr_dispatch.items ():
154 childs = attrs.get_named_children (k)
156 ## ugh: you get clefs spread over staves for piano
158 elts.append (func (childs[0]))
162 def create_skip_music (duration):
163 skip = musicexp.SkipEvent()
164 skip.duration.duration_log = 0
165 skip.duration.factor = duration
167 evc = musicexp.EventChord ()
171 spanner_event_dict = {
172 'slur' : musicexp.SlurEvent,
173 'beam' : musicexp.BeamEvent,
175 spanner_type_dict = {
182 def musicxml_spanner_to_lily_event (mxl_event):
185 name = mxl_event.get_name()
187 func = spanner_event_dict[name]
190 print 'unknown span event ', mxl_event
193 key = mxl_event.get_type ()
194 ev.span_direction = spanner_type_dict[key]
196 print 'unknown span type', key, 'for', name
200 def musicxml_note_to_lily_main_event (n):
204 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
207 pitch = musicxml_pitch_to_lily (mxl_pitch)
208 event = musicexp.NoteEvent()
211 acc = n.get_maybe_exist_named_child ('accidental')
213 # let's not force accs everywhere.
214 event.cautionary = acc.editorial
216 elif n.get_maybe_exist_typed_child (musicxml.Rest):
217 event = musicexp.RestEvent()
219 event.duration = musicxml_duration_to_lily (n)
222 def musicxml_voice_to_lily_voice (voice):
225 ly_now = Rational (0)
226 pending_skip = Rational (0)
231 if n.get_name () == 'forward':
234 if isinstance (n, musicxml.Attributes):
235 ly_now += pending_skip
236 pending_skip = Rational (0)
238 ly_voice.extend (musicxml_attributes_to_lily (n))
241 if not n.__class__.__name__ == 'Note':
242 print 'not a Note or Attributes?', n
245 if n.is_first () and ly_voice:
246 ly_voice[-1].comment += '\n'
249 main_event = musicxml_note_to_lily_main_event (n)
252 if None == n.get_maybe_exist_typed_child (musicxml.Chord):
253 ly_now += pending_skip
254 pending_skip = main_event.get_length ()
256 if ly_now <> n._when:
257 diff = n._when - ly_now
259 if diff < Rational (0):
260 print 'huh: negative skip', n._when, ly_now, n._duration
261 diff = Rational (1,314159265)
263 ly_voice.append (create_skip_music (diff))
266 ly_voice.append (musicexp.EventChord())
270 ev_chord = ly_voice[-1]
271 ev_chord.append (main_event)
273 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
277 if notations.get_tuplet():
278 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
281 frac = mod.get_fraction ()
283 tuplet_events.append ((ev_chord, tuplet_event, frac))
285 slurs = [s for s in notations.get_named_children ('slur')
286 if s.get_type () in ('start','stop')]
289 print 'more than 1 slur?'
291 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
292 ev_chord.append (lily_ev)
294 mxl_tie = notations.get_tie ()
295 if mxl_tie and mxl_tie.type == 'start':
296 ev_chord.append (musicexp.TieEvent ())
298 mxl_beams = [b for b in n.get_named_children ('beam')
299 if b.get_type () in ('begin', 'end')]
301 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
303 ev_chord.append (beam_ev)
306 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
309 frac = mod.get_fraction ()
311 tuplet_events.append ((ev_chord, tuplet_event, frac))
313 ly_voice = group_tuplets (ly_voice, tuplet_events)
315 seq_music = musicexp.SequentialMusic()
317 seq_music.elements = ly_voice
321 def musicxml_id_to_lily (id):
322 digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
326 d = digits.index (dig) + 1
327 dig = dig[0].upper() + dig[1:]
328 id = re.sub ('%d' % d, dig, id)
330 id = re.sub ('[^a-zA-Z]', 'X', id)
334 def musicxml_pitch_to_lily (mxl_pitch):
336 p.alteration = mxl_pitch.get_alteration ()
337 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
338 p.octave = mxl_pitch.get_octave () - 4
341 def synchronize_musicxml (parts):
342 progress ("Synchronizing MusicXML...")
348 voice_dict = p.get_voices ()
350 for (id, voice) in voice_dict.items ():
351 m_name = 'Part' + p.id + 'Voice' + id
352 m_name = musicxml_id_to_lily (m_name)
353 all_voices[m_name] = voice
356 def get_all_voices (parts):
358 all_voices = synchronize_musicxml (parts)
360 progress ("Converting to LilyPond expressions...")
362 for (k, v) in all_voices.items():
363 all_ly_voices[k] = musicxml_voice_to_lily_voice (v)
367 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
368 def format_heading(self, heading):
370 return heading[0].upper() + heading[1:] + ':\n'
372 def format_option_strings(self, option):
374 if option._short_opts and option._long_opts:
378 if option.takes_value():
379 metavar = '=' + option.metavar or option.dest.upper()
381 return "%3s%s %s%s" % (" ".join (option._short_opts),
383 " ".join (option._long_opts),
386 def format_usage(self, usage):
387 return _("Usage: %s\n") % usage
389 def format_description(self, description):
393 def option_parser ():
394 p = optparse.OptionParser(usage='musicxml2ly FILE.xml',
395 version = """%prog (LilyPond) @TOPLEVEL_VERSION@
397 This program is free software. It is covered by the GNU General Public
398 License and you are welcome to change it and/or distribute copies of it
399 under certain conditions. Invoke as `lilypond --warranty' for more
402 Copyright (c) 2005 by
403 Han-Wen Nienhuys <hanwen@xs4all.nl> and
404 Jan Nieuwenhuizen <janneke@gnu.org>
408 """Convert MusicXML file to LilyPond input.
411 p.add_option ('-v', '--verbose',
412 action = "store_true",
415 p.add_option ('-o', '--output',
421 help = 'set output file')
423 p.add_option_group ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
425 p.formatter = NonDentedHeadingFormatter ()
429 def convert (filename, output_name):
430 printer = musicexp.Output_printer()
431 progress ("Reading MusicXML...")
433 tree = musicxml.read_musicxml (filename)
434 parts = tree.get_typed_children (musicxml.Part)
436 voices = get_all_voices (parts)
439 printer.file = open (output_name,'w')
441 progress ("Printing as .ly...")
442 for (k,v) in voices.items():
443 printer.print_verbatim ('%% converted from %s\n' % filename)
444 printer.dump_version ()
445 printer.dump ('%s = ' % k)
453 opt_parser = option_parser()
455 (options, args) = opt_parser.parse_args ()
457 opt_parser.print_usage()
460 voices = convert (args[0], options.output)
462 if __name__ == '__main__':