]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
* scripts/musicxml2ly.py (NonDentedHeadingFormatter.format_headi):
[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 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 ()
34         else:
35                 d.duration_log = 0
36
37         d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
38         d.factor = mxl_note._duration / d.get_length ()
39
40         return d        
41
42 span_event_dict = {
43         'start': -1,
44         'stop': 1
45 }
46
47 def group_tuplets (music_list, events):
48         indices = []
49
50         j = 0
51         for (ev_chord, tuplet_elt, fraction) in events:
52                 while (j < len (music_list)):
53                         if music_list[j]== ev_chord:
54                                 break
55                         j += 1
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])
60
61         new_list = []
62         last = 0
63         for (i1, i2, frac) in indices:
64                 if i1 >= i2:
65                         continue
66
67                 new_list.extend (music_list[last:i1])
68                 seq = musicexp.SequentialMusic ()
69                 last = i2 + 1
70                 seq.elements = music_list[i1:last]
71
72                 tsm = musicexp.TimeScaledMusic ()
73                 tsm.element = seq
74
75                 tsm.numerator = frac[0]
76                 tsm.denominator  = frac[1]
77
78                 new_list.append (tsm)
79
80         new_list.extend (music_list[last:])
81         return new_list
82
83 def musicxml_clef_to_lily (mxl):
84         sign = mxl.get_maybe_exist_named_child ('sign')
85         change = musicexp.ClefChange ()
86         if sign:
87                 change.type = sign.get_text ()
88         return change
89
90         
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 ()))
97         
98         return change
99
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 ())
103
104         fifth = musicexp.Pitch()
105         fifth.step = 4
106         if fifths < 0:
107                 fifths *= -1
108                 fifth.step *= -1
109                 fifth.normalize ()
110         
111         c = musicexp.Pitch()
112         for x in range (fifths):
113                 c = c.transposed (fifth)
114
115         c.octave = 0
116
117         change = musicexp.KeySignatureChange()
118         change.mode = mode
119         change.tonic = c
120         return change
121         
122 def musicxml_attributes_to_lily (attrs):
123         elts = []
124         attr_dispatch =  {
125                 'clef': musicxml_clef_to_lily,
126                 'time': musicxml_time_to_lily,
127                 'key': musicxml_key_to_lily
128         }
129         for (k, func) in attr_dispatch.items ():
130                 childs = attrs.get_named_children (k)
131
132                 ## ugh: you get clefs spread over staves for piano
133                 if childs:
134                         elts.append (func (childs[0]))
135         
136         return elts
137
138 def insert_measure_start_comments (ly_voice, indices):
139         idxs = indices[:]
140         idxs.reverse ()
141         for i in idxs:
142                 c = musicexp.Comment()
143                 c.text = '' 
144                 ly_voice.insert (i, c)
145
146         return ly_voice
147         
148 def musicxml_voice_to_lily_voice (voice):
149         
150         ly_voice = []
151         ly_now = Rational (0)
152
153         tuplet_events = []
154
155         measure_start_indices = []
156         for n in voice:
157                 if n.is_first ():
158                         measure_start_indices.append (len (ly_voice))
159                         
160                 if isinstance (n, musicxml.Attributes):
161                         ly_voice.extend (musicxml_attributes_to_lily (n))
162                         continue
163                 
164                 if not n.__class__.__name__ == 'Note':
165                         print 'not a Note or Attributes?'
166                         continue
167                 
168                 
169                 pitch  = None
170                 duration = None
171                 
172                 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
173                 event = None
174
175                 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
176                 tuplet_event = None
177                 slur_event = None
178                 if notations:
179                         tuplet_event = notations.get_tuplet ()
180                         slur_event = notations.get_slur ()
181                         
182                 if mxl_pitch:
183                         pitch = musicxml_pitch_to_lily (mxl_pitch)
184                         event = musicexp.NoteEvent()
185                         event.pitch = pitch
186                 elif n.get_maybe_exist_typed_child (musicxml.Rest):
187                         event = musicexp.RestEvent()
188
189                 event.duration = musicxml_duration_to_lily (n)
190                 ev_chord = None
191                 if None ==  n.get_maybe_exist_typed_child (musicxml.Chord):
192                         if ly_voice:
193                                 ly_now += ly_voice[-1].get_length ()
194
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)
200                                 
201                                 skip = musicexp.SkipEvent()
202                                 skip.duration.duration_log = 0
203                                 skip.duration.factor = diff
204
205                                 evc = musicexp.EventChord ()
206                                 evc.elements.append (skip)
207                                 ly_voice.append (evc)
208                                 ly_now = n._when
209                                 
210                         ly_voice.append (musicexp.EventChord())
211                 else:
212                         pass
213
214                 ev_chord = ly_voice[-1]
215                 ev_chord.elements.append (event)
216
217                 if tuplet_event:
218                         mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
219                         frac = (1,1)
220                         if mod:
221                                 frac = mod.get_fraction ()
222                                 
223                         tuplet_events.append ((ev_chord, tuplet_event, frac))
224                         
225                 if slur_event:
226                         sp = musicexp.SlurEvent()
227                         try:
228                                 sp.span_direction = span_event_dict[slur_event.type]
229                                 ev_chord.elements.append (sp)
230                         except KeyError:
231                                 pass
232
233         ly_voice = insert_measure_start_comments (ly_voice, measure_start_indices)
234         ly_voice = group_tuplets (ly_voice, tuplet_events)
235
236         seq_music = musicexp.SequentialMusic()
237         
238         seq_music.elements = ly_voice
239         return seq_music
240
241
242 def musicxml_id_to_lily (id):
243         digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
244                   'nine', 'ten']
245         
246         for dig in digits:
247                 d = digits.index (dig) + 1
248                 dig = dig[0].upper() + dig[1:]
249                 id = re.sub ('%d' % d, dig, id)
250
251         id = re.sub  ('[^a-zA-Z]', 'X', id)
252         return id
253
254
255 def musicxml_pitch_to_lily (mxl_pitch):
256         p = musicexp.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
260         return p
261
262 def get_all_voices (parts):
263         all_voices = {} 
264         for p in parts:
265                 p.interpret ()
266                 p.extract_voices ()             
267                 voice_dict = p.get_voices ()
268                 
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
274
275         return all_voices
276
277 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
278     def format_heading(self, heading):
279             if heading:
280                     return heading[0].upper() + heading[1:] + ':\n'
281             return ''
282     def format_option_strings(self, option):
283             sep = ' '
284             if option._short_opts and option._long_opts:
285                     sep = ','
286
287             metavar = ''
288             if option.takes_value():
289                     metavar = '=' + option.metavar or option.dest.upper()
290
291             return "%3s%s %s%s" % (" ".join (option._short_opts),
292                                    sep,
293                                    " ".join (option._long_opts),
294                                    metavar)
295
296     def format_usage(self, usage):
297         return _("Usage: %s\n") % usage
298     
299     def format_description(self, description):
300             return description
301   
302
303 def option_parser ():
304         p = optparse.OptionParser(usage='musicxml2ly FILE.xml',
305                                   version = """%prog (LilyPond) @TOPLEVEL_VERSION@
306
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
310 information.
311
312 Copyright (c) 2005 by
313   Han-Wen Nienhuys <hanwen@xs4all.nl> and
314   Jan Nieuwenhuizen <janneke@gnu.org>
315 """,
316
317                                   description  =
318                                   """Convert MusicXML file to LilyPond input.
319 """
320                                   )
321         p.add_option ('-v', '--verbose',
322                       action = "store_true",
323                       dest = 'verbose',
324                       help = 'be verbose')
325         p.add_option ('-o', '--output',
326                       metavar = 'FILE',
327                       action = "store",
328                       default = None,
329                       type = 'string',
330                       dest = 'output',
331                       help = 'set output file')
332
333         p.add_option_group  ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
334 ''')
335         p.formatter = NonDentedHeadingFormatter () 
336         return p
337
338
339 def convert (filename, output_name):
340         
341         printer = musicexp.Output_printer()
342         tree = musicxml.read_musicxml (filename)
343         parts = tree.get_typed_children (musicxml.Part)
344
345         voices = get_all_voices (parts)
346
347
348         if output_name:
349                 printer.file = open (output_name,'w')
350                 
351         for  (k,v) in voices.items():
352                 printer.dump ('%s = ' % k)
353                 v.print_ly (printer)
354                 printer.newline()
355
356         return voices
357
358
359 opt_parser = option_parser()
360
361 (options, args) = opt_parser.parse_args ()
362 if options.version:
363         opt_parser.print_version()
364         sys.exit (0)
365 if not args:
366         opt_parser.print_usage()
367         sys.exit (2)
368
369 voices = convert (args[0], options.output)