]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
* scripts/musicxml2ly.py (progress): new function
[lilypond.git] / scripts / musicxml2ly.py
1 #!@PYTHON@
2
3 import optparse
4 import sys
5 import re
6 import os
7 import string
8 from gettext import gettext as _
9
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]
17
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/')
22
23 sys.path.insert (0, os.path.join (datadir, 'python'))
24
25
26 import musicxml
27 import musicexp
28 from rational import Rational
29
30
31 def progress (str):
32         sys.stderr.write (str + '\n')
33         sys.stderr.flush ()
34         
35
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 ()
40         else:
41                 d.duration_log = 0
42
43         d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
44         d.factor = mxl_note._duration / d.get_length ()
45
46         return d        
47
48 def group_tuplets (music_list, events):
49
50
51         """Collect Musics from
52         MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
53         """
54
55         
56         indices = []
57
58         j = 0
59         for (ev_chord, tuplet_elt, fraction) in events:
60                 while (j < len (music_list)):
61                         if music_list[j]== ev_chord:
62                                 break
63                         j += 1
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])
68
69         new_list = []
70         last = 0
71         for (i1, i2, frac) in indices:
72                 if i1 >= i2:
73                         continue
74
75                 new_list.extend (music_list[last:i1])
76                 seq = musicexp.SequentialMusic ()
77                 last = i2 + 1
78                 seq.elements = music_list[i1:last]
79
80                 tsm = musicexp.TimeScaledMusic ()
81                 tsm.element = seq
82
83                 tsm.numerator = frac[0]
84                 tsm.denominator  = frac[1]
85
86                 new_list.append (tsm)
87
88         new_list.extend (music_list[last:])
89         return new_list
90
91
92 def musicxml_clef_to_lily (mxl):
93         sign = mxl.get_maybe_exist_named_child ('sign')
94         change = musicexp.ClefChange ()
95         if sign:
96                 change.type = sign.get_text ()
97         return change
98
99         
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 ()))
106         
107         return change
108
109 def musicxml_key_to_lily (mxl):
110         start_pitch  = musicexp.Pitch ()
111         try:
112                 mode = mxl.get_maybe_exist_named_child ('mode')
113                 if mode:
114                         mode = mode.get_text ()
115                 else:
116                         mode = 'major'
117                         
118                 (n,a) = { 'major' : (0,0),
119                           'minor' : (6,0),
120                         }[mode]
121                 start_pitch.step = n
122                 start_pitch.alteration = a
123         except  KeyError:
124                 print 'unknown mode', mode
125                 
126         fifths = string.atoi (mxl.get_maybe_exist_named_child ('fifths').get_text ())
127
128         fifth = musicexp.Pitch()
129         fifth.step = 4
130         if fifths < 0:
131                 fifths *= -1
132                 fifth.step *= -1
133                 fifth.normalize ()
134         
135         start_pitch = musicexp.Pitch()
136         for x in range (fifths):
137                 start_pitch = start_pitch.transposed (fifth)
138
139         start_pitch.octave = 0
140
141         change = musicexp.KeySignatureChange()
142         change.mode = mode
143         change.tonic = start_pitch
144         return change
145         
146 def musicxml_attributes_to_lily (attrs):
147         elts = []
148         attr_dispatch =  {
149                 'clef': musicxml_clef_to_lily,
150                 'time': musicxml_time_to_lily,
151                 'key': musicxml_key_to_lily
152         }
153         for (k, func) in attr_dispatch.items ():
154                 childs = attrs.get_named_children (k)
155
156                 ## ugh: you get clefs spread over staves for piano
157                 if childs:
158                         elts.append (func (childs[0]))
159         
160         return elts
161
162 def create_skip_music (duration):
163         skip = musicexp.SkipEvent()
164         skip.duration.duration_log = 0
165         skip.duration.factor = duration
166
167         evc = musicexp.EventChord ()
168         evc.append (skip)
169         return evc
170
171 spanner_event_dict = {
172         'slur' : musicexp.SlurEvent,
173         'beam' : musicexp.BeamEvent,
174 }       
175 spanner_type_dict = {
176         'start': -1,
177         'begin': -1,
178         'stop': 1,
179         'end' : 1
180 }
181
182 def musicxml_spanner_to_lily_event (mxl_event):
183         ev = None
184         
185         name = mxl_event.get_name()
186         try:
187                 func = spanner_event_dict[name]
188                 ev = func()
189         except KeyError:
190                 print 'unknown span event ', mxl_event
191
192         try:
193                 key = mxl_event.get_type ()
194                 ev.span_direction = spanner_type_dict[key]
195         except KeyError:
196                 print 'unknown span type', key, 'for', name
197
198         return ev
199
200 def musicxml_note_to_lily_main_event (n):
201         pitch  = None
202         duration = None
203                 
204         mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
205         event = None
206         if mxl_pitch:
207                 pitch = musicxml_pitch_to_lily (mxl_pitch)
208                 event = musicexp.NoteEvent()
209                 event.pitch = pitch
210
211                 acc = n.get_maybe_exist_named_child ('accidental')
212                 if acc:
213                         # let's not force accs everywhere. 
214                         event.cautionary = acc.editorial
215                         print event, event.cautionary, event.ly_expression()
216                 
217         elif n.get_maybe_exist_typed_child (musicxml.Rest):
218                 event = musicexp.RestEvent()
219
220         event.duration = musicxml_duration_to_lily (n)
221         return event
222
223 def musicxml_voice_to_lily_voice (voice):
224         
225         ly_voice = []
226         ly_now = Rational (0)
227
228         tuplet_events = []
229
230         for n in voice:
231                 if n.get_name () == 'forward':
232                         continue
233                 
234                 if isinstance (n, musicxml.Attributes):
235                         ly_voice.extend (musicxml_attributes_to_lily (n))
236                         continue
237                 
238                 if not n.__class__.__name__ == 'Note':
239                         print 'not a Note or Attributes?', n
240                         continue
241
242                 if n.is_first () and ly_voice:
243                         ly_voice[-1].comment += '\n'
244                 
245                 ev_chord = None
246                 if None ==  n.get_maybe_exist_typed_child (musicxml.Chord):
247                         if ly_voice:
248                                 ly_now += ly_voice[-1].get_length ()
249
250                         if ly_now <> n._when:
251                                 diff = n._when - ly_now
252                                 if diff < Rational (0):
253                                         print 'huh: negative skip', n._when, ly_now, n._duration
254                                         diff = Rational (1,314159265)
255
256                                 ly_voice.append (create_skip_music (diff))
257                                 ly_now = n._when
258                                 
259                         ly_voice.append (musicexp.EventChord())
260                 else:
261                         pass
262                 
263                 ev_chord = ly_voice[-1]
264
265                 main_event = musicxml_note_to_lily_main_event (n)
266                 ev_chord.append (main_event)
267                         
268                 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
269                 tuplet_event = None
270                 span_events = []
271                 if notations:
272                         if notations.get_tuplet():
273                                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
274                                 frac = (1,1)
275                                 if mod:
276                                         frac = mod.get_fraction ()
277                                 
278                                 tuplet_events.append ((ev_chord, tuplet_event, frac))
279
280                         slurs = [s for s in notations.get_named_children ('slur')
281                                  if s.get_type () in ('start','stop')]
282                         if slurs:
283                                 if len (slurs) > 1:
284                                         print 'more than 1 slur?'
285
286                                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
287                                 ev_chord.append (lily_ev)
288
289                         mxl_tie = notations.get_tie ()
290                         if mxl_tie and mxl_tie.type == 'start':
291                                 ev_chord.append (musicexp.TieEvent ())
292
293                 mxl_beams = [b for b in n.get_named_children ('beam')
294                              if b.get_type () in ('begin', 'end')] 
295                 if mxl_beams:
296                         beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
297                         if beam_ev:
298                                 ev_chord.append (beam_ev)
299                         
300                 if tuplet_event:
301                         mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
302                         frac = (1,1)
303                         if mod:
304                                 frac = mod.get_fraction ()
305                                 
306                         tuplet_events.append ((ev_chord, tuplet_event, frac))
307
308         ly_voice = group_tuplets (ly_voice, tuplet_events)
309
310         seq_music = musicexp.SequentialMusic()
311         
312         seq_music.elements = ly_voice
313         return seq_music
314
315
316 def musicxml_id_to_lily (id):
317         digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
318                   'nine', 'ten']
319         
320         for dig in digits:
321                 d = digits.index (dig) + 1
322                 dig = dig[0].upper() + dig[1:]
323                 id = re.sub ('%d' % d, dig, id)
324
325         id = re.sub  ('[^a-zA-Z]', 'X', id)
326         return id
327
328
329 def musicxml_pitch_to_lily (mxl_pitch):
330         p = musicexp.Pitch()
331         p.alteration = mxl_pitch.get_alteration ()
332         p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
333         p.octave = mxl_pitch.get_octave () - 4
334         return p
335
336 def get_all_voices (parts):
337         progress ("Synchronizing MusicXML...")
338         
339         all_voices = {} 
340         for p in parts:
341                 p.interpret ()
342                 p.extract_voices ()             
343                 voice_dict = p.get_voices ()
344                 
345                 for (id, voice) in voice_dict.items ():
346                         m_name = 'Part' + p.id + 'Voice' + id
347                         m_name = musicxml_id_to_lily (m_name)
348                         all_voices[m_name] = voice
349
350
351         progress ("Converting to LilyPond expressions...")
352         all_ly_voices = {}
353         for (k, v) in all_voices.items():
354                 all_ly_voices[k] = musicxml_voice_to_lily_voice (v)
355
356         return all_ly_voices
357
358 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
359     def format_heading(self, heading):
360             if heading:
361                     return heading[0].upper() + heading[1:] + ':\n'
362             return ''
363     def format_option_strings(self, option):
364             sep = ' '
365             if option._short_opts and option._long_opts:
366                     sep = ','
367
368             metavar = ''
369             if option.takes_value():
370                     metavar = '=' + option.metavar or option.dest.upper()
371
372             return "%3s%s %s%s" % (" ".join (option._short_opts),
373                                    sep,
374                                    " ".join (option._long_opts),
375                                    metavar)
376
377     def format_usage(self, usage):
378         return _("Usage: %s\n") % usage
379     
380     def format_description(self, description):
381             return description
382   
383
384 def option_parser ():
385         p = optparse.OptionParser(usage='musicxml2ly FILE.xml',
386                                   version = """%prog (LilyPond) @TOPLEVEL_VERSION@
387
388 This program is free software.  It is covered by the GNU General Public
389 License and you are welcome to change it and/or distribute copies of it
390 under certain conditions.  Invoke as `lilypond --warranty' for more
391 information.
392
393 Copyright (c) 2005 by
394   Han-Wen Nienhuys <hanwen@xs4all.nl> and
395   Jan Nieuwenhuizen <janneke@gnu.org>
396 """,
397
398                                   description  =
399                                   """Convert MusicXML file to LilyPond input.
400 """
401                                   )
402         p.add_option ('-v', '--verbose',
403                       action = "store_true",
404                       dest = 'verbose',
405                       help = 'be verbose')
406         p.add_option ('-o', '--output',
407                       metavar = 'FILE',
408                       action = "store",
409                       default = None,
410                       type = 'string',
411                       dest = 'output',
412                       help = 'set output file')
413
414         p.add_option_group  ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
415 ''')
416         p.formatter = NonDentedHeadingFormatter () 
417         return p
418
419
420 def convert (filename, output_name):
421         
422         printer = musicexp.Output_printer()
423
424         progress ("Reading MusicXML...")
425         
426         tree = musicxml.read_musicxml (filename)
427         parts = tree.get_typed_children (musicxml.Part)
428
429         voices = get_all_voices (parts)
430
431         if output_name:
432                 printer.file = open (output_name,'w')
433                 
434         progress ("Printing as .ly...")
435         for  (k,v) in voices.items():
436                 printer.dump ('%s = ' % k)
437                 v.print_ly (printer)
438                 printer.newline()
439
440         return voices
441
442
443 opt_parser = option_parser()
444
445 (options, args) = opt_parser.parse_args ()
446 if not args:
447         opt_parser.print_usage()
448         sys.exit (2)
449
450 voices = convert (args[0], options.output)