]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
* The grand 2005-2006 replace.
[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                 
216         elif n.get_maybe_exist_typed_child (musicxml.Rest):
217                 event = musicexp.RestEvent()
218
219         event.duration = musicxml_duration_to_lily (n)
220         return event
221
222 def musicxml_voice_to_lily_voice (voice):
223         ly_voice = []
224         ly_now = Rational (0)
225         pending_skip = Rational (0) 
226
227         tuplet_events = []
228
229         for n in voice._elements:
230                 if n.get_name () == 'forward':
231                         continue
232                 
233                 if isinstance (n, musicxml.Attributes):
234                         ly_now += pending_skip
235                         pending_skip = Rational (0)
236                         
237                         ly_voice.extend (musicxml_attributes_to_lily (n))
238                         continue
239                 
240                 if not n.__class__.__name__ == 'Note':
241                         print 'not a Note or Attributes?', n
242                         continue
243
244                 if n.is_first () and ly_voice:
245                         ly_voice[-1].comment += '\n'
246                 
247
248                 main_event = musicxml_note_to_lily_main_event (n)
249
250                 ev_chord = None
251                 if None ==  n.get_maybe_exist_typed_child (musicxml.Chord):
252                         ly_now += pending_skip
253                         pending_skip = main_event.get_length ()
254
255                         if ly_now <> n._when:
256                                 diff = n._when - ly_now
257
258                                 if diff < Rational (0):
259                                         print 'huh: negative skip', n._when, ly_now, n._duration
260                                         diff = Rational (1,314159265)
261
262                                 ly_voice.append (create_skip_music (diff))
263                                 ly_now = n._when
264                                 
265                         ly_voice.append (musicexp.EventChord())
266                 else:
267                         pass
268                 
269                 ev_chord = ly_voice[-1]
270                 ev_chord.append (main_event)
271                 
272                 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
273                 tuplet_event = None
274                 span_events = []
275                 if notations:
276                         if notations.get_tuplet():
277                                 tuplet_event = notations.get_tuplet()
278                                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
279                                 frac = (1,1)
280                                 if mod:
281                                         frac = mod.get_fraction ()
282                                 
283                                 tuplet_events.append ((ev_chord, tuplet_event, frac))
284
285                         slurs = [s for s in notations.get_named_children ('slur')
286                                  if s.get_type () in ('start','stop')]
287                         if slurs:
288                                 if len (slurs) > 1:
289                                         print 'more than 1 slur?'
290
291                                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
292                                 ev_chord.append (lily_ev)
293
294                         mxl_tie = notations.get_tie ()
295                         if mxl_tie and mxl_tie.type == 'start':
296                                 ev_chord.append (musicexp.TieEvent ())
297
298                 mxl_beams = [b for b in n.get_named_children ('beam')
299                              if b.get_type () in ('begin', 'end')] 
300                 if mxl_beams:
301                         beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
302                         if beam_ev:
303                                 ev_chord.append (beam_ev)
304                         
305                 if tuplet_event:
306                         mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
307                         frac = (1,1)
308                         if mod:
309                                 frac = mod.get_fraction ()
310                                 
311                         tuplet_events.append ((ev_chord, tuplet_event, frac))
312
313         ly_voice = group_tuplets (ly_voice, tuplet_events)
314
315         seq_music = musicexp.SequentialMusic()
316         
317         seq_music.elements = ly_voice
318         return seq_music
319
320
321 def musicxml_id_to_lily (id):
322         digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
323                   'nine', 'ten']
324         
325         for dig in digits:
326                 d = digits.index (dig) + 1
327                 dig = dig[0].upper() + dig[1:]
328                 id = re.sub ('%d' % d, dig, id)
329
330         id = re.sub  ('[^a-zA-Z]', 'X', id)
331         return id
332
333
334 def musicxml_pitch_to_lily (mxl_pitch):
335         p = musicexp.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
339         return p
340
341
342
343 def voices_in_part (part):
344         """Return a Name -> Voice dictionary for PART"""
345         part.interpret ()
346         part.extract_voices ()          
347         voice_dict = part.get_voices ()
348
349         return voice_dict
350
351 def voices_in_part_in_parts (parts):
352         """return a Part -> Name -> Voice dictionary"""
353         return dict([(p, voices_in_part (p)) for p in parts])
354
355
356 def get_all_voices (parts):
357         all_voices = voices_in_part_in_parts (parts)
358
359         all_ly_voices = {}
360         for p, name_voice in all_voices.items ():
361
362                 part_ly_voices = {}
363                 for n, v in name_voice.items ():
364                         progress ("Converting to LilyPond expressions...")
365                         part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
366
367                 all_ly_voices[p] = part_ly_voices
368                 
369         return all_ly_voices
370
371 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
372     def format_heading(self, heading):
373             if heading:
374                     return heading[0].upper() + heading[1:] + ':\n'
375             return ''
376     def format_option_strings(self, option):
377             sep = ' '
378             if option._short_opts and option._long_opts:
379                     sep = ','
380
381             metavar = ''
382             if option.takes_value():
383                     metavar = '=' + option.metavar or option.dest.upper()
384
385             return "%3s%s %s%s" % (" ".join (option._short_opts),
386                                    sep,
387                                    " ".join (option._long_opts),
388                                    metavar)
389
390     def format_usage(self, usage):
391         return _("Usage: %s\n") % usage
392     
393     def format_description(self, description):
394             return description
395   
396
397 def option_parser ():
398         p = optparse.OptionParser(usage='musicxml2ly FILE.xml',
399                                   version = """%prog (LilyPond) @TOPLEVEL_VERSION@
400
401 This program is free software.  It is covered by the GNU General Public
402 License and you are welcome to change it and/or distribute copies of it
403 under certain conditions.  Invoke as `lilypond --warranty' for more
404 information.
405
406 Copyright (c) 2005--2006 by
407   Han-Wen Nienhuys <hanwen@xs4all.nl> and
408   Jan Nieuwenhuizen <janneke@gnu.org>
409 """,
410
411                                   description  =
412                                   """Convert MusicXML file to LilyPond input.
413 """
414                                   )
415         p.add_option ('-v', '--verbose',
416                       action = "store_true",
417                       dest = 'verbose',
418                       help = 'be verbose')
419         p.add_option ('-o', '--output',
420                       metavar = 'FILE',
421                       action = "store",
422                       default = None,
423                       type = 'string',
424                       dest = 'output',
425                       help = 'set output file')
426
427         p.add_option_group  ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
428 ''')
429         p.formatter = NonDentedHeadingFormatter () 
430         return p
431
432 def music_xml_voice_name_to_lily_name (part, name):
433         str = "Part%sVoice%s" % (part.id, name)
434         return musicxml_id_to_lily (str) 
435
436 def print_voice_definitions (printer, voices):
437         for (part, nv_dict) in voices.items():
438                 for (name, (voice, mxlvoice)) in nv_dict.items ():
439                         k = music_xml_voice_name_to_lily_name (part, name)
440                         printer.dump ('%s = ' % k)
441                         voice.print_ly (printer)
442                         printer.newline()
443 def uniq_list (l):
444         return dict ([(elt,1) for elt in l]).keys ()
445         
446 def print_score_setup (printer, part_list, voices):
447         part_dict = dict ([(p.id, p) for p in voices.keys ()]) 
448
449         printer ('<<')
450         printer.newline ()
451         for part_definition in part_list:
452                 part_name = part_definition.id
453                 try:
454                         part = part_dict[part_name]
455                 except KeyError:
456                         print 'unknown part in part-list:', part_name
457                         continue
458
459                 nv_dict = voices[part]
460                 staves = reduce (lambda x,y: x+ y,
461                                  [mxlvoice._staves.keys ()
462                                   for (v, mxlvoice) in nv_dict.values ()],
463                                  [])
464
465                 if len (staves) > 1:
466                         staves = uniq_list (staves)
467                         staves.sort ()
468                         printer ('\\context PianoStaff << ')
469                         printer.newline ()
470                         
471                         for s in staves:
472                                 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
473                                                 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
474                                                 if mxlvoice._start_staff == s]
475                                 
476                                 printer ('\\context Staff = "%s" << ' % s)
477                                 printer.newline ()
478                                 for v in staff_voices:
479                                         printer ('\\context Voice = "%s"  \\%s' % (v,v))
480                                         printer.newline ()
481                                 printer ('>>')
482                                 printer.newline ()
483                                 
484                         printer ('>>')
485                         printer.newline ()
486                         
487                 else:
488                         printer ('\\new Staff <<')
489                         printer.newline ()
490                         for (n,v) in nv_dict.items ():
491
492                                 n = music_xml_voice_name_to_lily_name (part, n) 
493                                 printer ('\\context Voice = "%s"  \\%s' % (n,n))
494                         printer ('>>')
495                         printer.newline ()
496                         
497
498         printer ('>>')
499         printer.newline ()
500
501                                 
502
503 def print_ly_preamble (printer, filename):
504         printer.dump_version ()
505         printer.print_verbatim ('%% converted from %s\n' % filename)
506
507 def convert (filename, output_name):
508         printer = musicexp.Output_printer()
509         progress ("Reading MusicXML...")
510         
511         tree = musicxml.read_musicxml (filename)
512         parts = tree.get_typed_children (musicxml.Part)
513         voices = get_all_voices (parts)
514
515         part_list = []
516         if tree.get_maybe_exist_typed_child (musicxml.Part_list):
517                 pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
518                 part_list = pl.get_named_children ("score-part")
519                 
520         if not output_name:
521                 output_name = os.path.basename (filename)
522                 output_name = os.path.splitext (output_name)[0] + '.ly'
523
524                 
525         if output_name:
526                 progress ("Output to `%s'" % output_name)
527                 printer.set_file (open (output_name, 'w'))
528         
529         progress ("Printing as .ly...")
530
531         print_ly_preamble (printer, filename)
532         print_voice_definitions (printer,  voices)
533         print_score_setup (printer, part_list, voices)
534         printer.newline ()
535         return voices
536
537
538 def main ():
539         opt_parser = option_parser()
540
541         (options, args) = opt_parser.parse_args ()
542         if not args:
543                 opt_parser.print_usage()
544                 sys.exit (2)
545
546         voices = convert (args[0], options.output)
547
548 if __name__ == '__main__':
549         main()