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
30 def musicxml_duration_to_lily (mxl_note):
31 d = musicexp.Duration ()
32 if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
33 d.duration_log = mxl_note.get_duration_log ()
37 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
38 d.factor = mxl_note._duration / d.get_length ()
47 def group_tuplets (music_list, events):
51 for (ev_chord, tuplet_elt, fraction) in events:
52 while (j < len (music_list)):
53 if music_list[j]== ev_chord:
56 if tuplet_elt.type == 'start':
57 indices.append ((j, None, fraction))
58 elif tuplet_elt.type == 'stop':
59 indices[-1] = (indices[-1][0], j, indices[-1][2])
63 for (i1, i2, frac) in indices:
67 new_list.extend (music_list[last:i1])
68 seq = musicexp.SequentialMusic ()
70 seq.elements = music_list[i1:last]
72 tsm = musicexp.TimeScaledMusic ()
75 tsm.numerator = frac[0]
76 tsm.denominator = frac[1]
80 new_list.extend (music_list[last:])
83 def musicxml_clef_to_lily (mxl):
84 sign = mxl.get_maybe_exist_named_child ('sign')
85 change = musicexp.ClefChange ()
87 change.type = sign.get_text ()
91 def musicxml_time_to_lily (mxl):
92 beats = mxl.get_maybe_exist_named_child ('beats')
93 type = mxl.get_maybe_exist_named_child ('beat-type')
94 change = musicexp.TimeSignatureChange()
95 change.fraction = (string.atoi(beats.get_text ()),
96 string.atoi(type.get_text ()))
100 def musicxml_key_to_lily (mxl):
101 mode = mxl.get_maybe_exist_named_child ('mode').get_text ()
102 fifths = string.atoi (mxl.get_maybe_exist_named_child ('fifths').get_text ())
104 fifth = musicexp.Pitch()
112 for x in range (fifths):
113 c = c.transposed (fifth)
117 change = musicexp.KeySignatureChange()
122 def musicxml_attributes_to_lily (attrs):
125 'clef': musicxml_clef_to_lily,
126 'time': musicxml_time_to_lily,
127 'key': musicxml_key_to_lily
129 for (k, func) in attr_dispatch.items ():
130 childs = attrs.get_named_children (k)
132 ## ugh: you get clefs spread over staves for piano
134 elts.append (func (childs[0]))
138 def insert_measure_start_comments (ly_voice, indices):
142 c = musicexp.Comment()
144 ly_voice.insert (i, c)
148 def musicxml_voice_to_lily_voice (voice):
151 ly_now = Rational (0)
155 measure_start_indices = []
158 measure_start_indices.append (len (ly_voice))
160 if isinstance (n, musicxml.Attributes):
161 ly_voice.extend (musicxml_attributes_to_lily (n))
164 if not n.__class__.__name__ == 'Note':
165 print 'not a Note or Attributes?'
172 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
175 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
179 tuplet_event = notations.get_tuplet ()
180 slur_event = notations.get_slur ()
183 pitch = musicxml_pitch_to_lily (mxl_pitch)
184 event = musicexp.NoteEvent()
186 elif n.get_maybe_exist_typed_child (musicxml.Rest):
187 event = musicexp.RestEvent()
189 event.duration = musicxml_duration_to_lily (n)
191 if None == n.get_maybe_exist_typed_child (musicxml.Chord):
193 ly_now += ly_voice[-1].get_length ()
195 if ly_now <> n._when:
196 diff = n._when - ly_now
197 if diff < Rational (0):
198 print 'huh: negative skip', n._when, ly_now, n._duration
199 diff = Rational (1,314159265)
201 skip = musicexp.SkipEvent()
202 skip.duration.duration_log = 0
203 skip.duration.factor = diff
205 evc = musicexp.EventChord ()
206 evc.elements.append (skip)
207 ly_voice.append (evc)
210 ly_voice.append (musicexp.EventChord())
214 ev_chord = ly_voice[-1]
215 ev_chord.elements.append (event)
218 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
221 frac = mod.get_fraction ()
223 tuplet_events.append ((ev_chord, tuplet_event, frac))
226 sp = musicexp.SlurEvent()
228 sp.span_direction = span_event_dict[slur_event.type]
229 ev_chord.elements.append (sp)
233 ly_voice = insert_measure_start_comments (ly_voice, measure_start_indices)
234 ly_voice = group_tuplets (ly_voice, tuplet_events)
236 seq_music = musicexp.SequentialMusic()
238 seq_music.elements = ly_voice
242 def musicxml_id_to_lily (id):
243 digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
247 d = digits.index (dig) + 1
248 dig = dig[0].upper() + dig[1:]
249 id = re.sub ('%d' % d, dig, id)
251 id = re.sub ('[^a-zA-Z]', 'X', id)
255 def musicxml_pitch_to_lily (mxl_pitch):
257 p.alteration = mxl_pitch.get_alteration ()
258 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
259 p.octave = mxl_pitch.get_octave () -4
262 def get_all_voices (parts):
267 voice_dict = p.get_voices ()
269 for (id, voice) in voice_dict.items ():
270 m = musicxml_voice_to_lily_voice (voice)
271 m_name = 'Part' + p.id + 'Voice' + id
272 m_name = musicxml_id_to_lily (m_name)
273 all_voices[m_name] = m
277 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
278 def format_heading(self, heading):
280 return heading[0].upper() + heading[1:] + ':\n'
282 def format_option_strings(self, option):
284 if option._short_opts and option._long_opts:
288 if option.takes_value():
289 metavar = '=' + option.metavar or option.dest.upper()
291 return "%3s%s %s%s" % (" ".join (option._short_opts),
293 " ".join (option._long_opts),
296 def format_usage(self, usage):
297 return _("Usage: %s\n") % usage
299 def format_description(self, description):
303 def option_parser ():
304 p = optparse.OptionParser(usage='musicxml2ly FILE.xml',
305 version = """%prog (LilyPond) @TOPLEVEL_VERSION@
307 This program is free software. It is covered by the GNU General Public
308 License and you are welcome to change it and/or distribute copies of it
309 under certain conditions. Invoke as `lilypond --warranty' for more
312 Copyright (c) 2005 by
313 Han-Wen Nienhuys <hanwen@xs4all.nl> and
314 Jan Nieuwenhuizen <janneke@gnu.org>
318 """Convert MusicXML file to LilyPond input.
321 p.add_option ('-v', '--verbose',
322 action = "store_true",
325 p.add_option ('-o', '--output',
331 help = 'set output file')
333 p.add_option_group ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
335 p.formatter = NonDentedHeadingFormatter ()
339 def convert (filename, output_name):
341 printer = musicexp.Output_printer()
342 tree = musicxml.read_musicxml (filename)
343 parts = tree.get_typed_children (musicxml.Part)
345 voices = get_all_voices (parts)
349 printer.file = open (output_name,'w')
351 for (k,v) in voices.items():
352 printer.dump ('%s = ' % k)
359 opt_parser = option_parser()
361 (options, args) = opt_parser.parse_args ()
363 opt_parser.print_version()
366 opt_parser.print_usage()
369 voices = convert (args[0], options.output)