]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
(ps-page-count): prevent null characters
[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
11 datadir = '@local_lilypond_datadir@'
12 if not os.path.isdir (datadir):
13         datadir = '@lilypond_datadir@'
14 if os.environ.has_key ('LILYPONDPREFIX'):
15         datadir = os.environ['LILYPONDPREFIX']
16         while datadir[-1] == os.sep:
17                 datadir = datadir[:-1]
18
19 if os.path.exists (os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')):
20         datadir = os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')
21 elif os.path.exists (os.path.join (datadir, 'share/lilypond/current/')):
22         datadir = os.path.join (datadir, 'share/lilypond/current/')
23
24 sys.path.insert (0, os.path.join (datadir, 'python'))
25
26
27 import musicxml
28 import musicexp
29 import lilylib as ly
30
31 from rational import Rational
32
33
34 def progress (str):
35         sys.stderr.write (str + '\n')
36         sys.stderr.flush ()
37         
38
39 def musicxml_duration_to_lily (mxl_note):
40         d = musicexp.Duration ()
41         if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
42                 d.duration_log = mxl_note.get_duration_log ()
43         else:
44                 d.duration_log = 0
45
46         d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
47         d.factor = mxl_note._duration / d.get_length ()
48
49         return d        
50
51 def group_tuplets (music_list, events):
52
53
54         """Collect Musics from
55         MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
56         """
57
58         
59         indices = []
60
61         j = 0
62         for (ev_chord, tuplet_elt, fraction) in events:
63                 while (j < len (music_list)):
64                         if music_list[j]== ev_chord:
65                                 break
66                         j += 1
67                 if tuplet_elt.type == 'start':
68                         indices.append ((j, None, fraction))
69                 elif tuplet_elt.type == 'stop':
70                         indices[-1] = (indices[-1][0], j, indices[-1][2])
71
72         new_list = []
73         last = 0
74         for (i1, i2, frac) in indices:
75                 if i1 >= i2:
76                         continue
77
78                 new_list.extend (music_list[last:i1])
79                 seq = musicexp.SequentialMusic ()
80                 last = i2 + 1
81                 seq.elements = music_list[i1:last]
82
83                 tsm = musicexp.TimeScaledMusic ()
84                 tsm.element = seq
85
86                 tsm.numerator = frac[0]
87                 tsm.denominator  = frac[1]
88
89                 new_list.append (tsm)
90
91         new_list.extend (music_list[last:])
92         return new_list
93
94
95 def musicxml_clef_to_lily (mxl):
96         sign = mxl.get_maybe_exist_named_child ('sign')
97         change = musicexp.ClefChange ()
98         if sign:
99                 change.type = sign.get_text ()
100         return change
101
102         
103 def musicxml_time_to_lily (mxl):
104         beats = mxl.get_maybe_exist_named_child ('beats')
105         type = mxl.get_maybe_exist_named_child ('beat-type')
106         change = musicexp.TimeSignatureChange()
107         change.fraction = (string.atoi(beats.get_text ()),
108                            string.atoi(type.get_text ()))
109         
110         return change
111
112 def musicxml_key_to_lily (mxl):
113         start_pitch  = musicexp.Pitch ()
114         try:
115                 mode = mxl.get_maybe_exist_named_child ('mode')
116                 if mode:
117                         mode = mode.get_text ()
118                 else:
119                         mode = 'major'
120                         
121                 (n,a) = { 'major' : (0,0),
122                           'minor' : (6,0),
123                         }[mode]
124                 start_pitch.step = n
125                 start_pitch.alteration = a
126         except  KeyError:
127                 print 'unknown mode', mode
128                 
129         fifths = string.atoi (mxl.get_maybe_exist_named_child ('fifths').get_text ())
130
131         fifth = musicexp.Pitch()
132         fifth.step = 4
133         if fifths < 0:
134                 fifths *= -1
135                 fifth.step *= -1
136                 fifth.normalize ()
137         
138         start_pitch = musicexp.Pitch()
139         for x in range (fifths):
140                 start_pitch = start_pitch.transposed (fifth)
141
142         start_pitch.octave = 0
143
144         change = musicexp.KeySignatureChange()
145         change.mode = mode
146         change.tonic = start_pitch
147         return change
148         
149 def musicxml_attributes_to_lily (attrs):
150         elts = []
151         attr_dispatch =  {
152                 'clef': musicxml_clef_to_lily,
153                 'time': musicxml_time_to_lily,
154                 'key': musicxml_key_to_lily
155         }
156         for (k, func) in attr_dispatch.items ():
157                 childs = attrs.get_named_children (k)
158
159                 ## ugh: you get clefs spread over staves for piano
160                 if childs:
161                         elts.append (func (childs[0]))
162         
163         return elts
164
165 def create_skip_music (duration):
166         skip = musicexp.SkipEvent()
167         skip.duration.duration_log = 0
168         skip.duration.factor = duration
169
170         evc = musicexp.EventChord ()
171         evc.append (skip)
172         return evc
173
174 spanner_event_dict = {
175         'slur' : musicexp.SlurEvent,
176         'beam' : musicexp.BeamEvent,
177 }       
178 spanner_type_dict = {
179         'start': -1,
180         'begin': -1,
181         'stop': 1,
182         'end' : 1
183 }
184
185 def musicxml_spanner_to_lily_event (mxl_event):
186         ev = None
187         
188         name = mxl_event.get_name()
189         try:
190                 func = spanner_event_dict[name]
191                 ev = func()
192         except KeyError:
193                 print 'unknown span event ', mxl_event
194
195         try:
196                 key = mxl_event.get_type ()
197                 ev.span_direction = spanner_type_dict[key]
198         except KeyError:
199                 print 'unknown span type', key, 'for', name
200
201         return ev
202
203 def musicxml_note_to_lily_main_event (n):
204         pitch  = None
205         duration = None
206                 
207         mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
208         event = None
209         if mxl_pitch:
210                 pitch = musicxml_pitch_to_lily (mxl_pitch)
211                 event = musicexp.NoteEvent()
212                 event.pitch = pitch
213
214                 acc = n.get_maybe_exist_named_child ('accidental')
215                 if acc:
216                         # let's not force accs everywhere. 
217                         event.cautionary = acc.editorial
218                 
219         elif n.get_maybe_exist_typed_child (musicxml.Rest):
220                 event = musicexp.RestEvent()
221
222         event.duration = musicxml_duration_to_lily (n)
223         return event
224
225 def musicxml_voice_to_lily_voice (voice):
226         ly_voice = []
227         ly_now = Rational (0)
228         pending_skip = Rational (0) 
229
230         tuplet_events = []
231
232         for n in voice._elements:
233                 if n.get_name () == 'forward':
234                         continue
235                 
236                 if isinstance (n, musicxml.Attributes):
237                         ly_now += pending_skip
238                         pending_skip = Rational (0)
239                         
240                         ly_voice.extend (musicxml_attributes_to_lily (n))
241                         continue
242                 
243                 if not n.__class__.__name__ == 'Note':
244                         print 'not a Note or Attributes?', n
245                         continue
246
247                 if n.is_first () and ly_voice:
248                         ly_voice[-1].comment += '\n'
249                 
250
251                 main_event = musicxml_note_to_lily_main_event (n)
252
253                 ev_chord = None
254                 if None ==  n.get_maybe_exist_typed_child (musicxml.Chord):
255                         ly_now += pending_skip
256                         pending_skip = main_event.get_length ()
257
258                         if ly_now <> n._when:
259                                 diff = n._when - ly_now
260
261                                 if diff < Rational (0):
262                                         print 'huh: negative skip', n._when, ly_now, n._duration
263                                         diff = Rational (1,314159265)
264
265                                 ly_voice.append (create_skip_music (diff))
266                                 ly_now = n._when
267                                 
268                         ly_voice.append (musicexp.EventChord())
269                 else:
270                         pass
271                 
272                 ev_chord = ly_voice[-1]
273                 ev_chord.append (main_event)
274                 
275                 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
276                 tuplet_event = None
277                 span_events = []
278                 if notations:
279                         if notations.get_tuplet():
280                                 tuplet_event = notations.get_tuplet()
281                                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
282                                 frac = (1,1)
283                                 if mod:
284                                         frac = mod.get_fraction ()
285                                 
286                                 tuplet_events.append ((ev_chord, tuplet_event, frac))
287
288                         slurs = [s for s in notations.get_named_children ('slur')
289                                  if s.get_type () in ('start','stop')]
290                         if slurs:
291                                 if len (slurs) > 1:
292                                         print 'more than 1 slur?'
293
294                                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
295                                 ev_chord.append (lily_ev)
296
297                         mxl_tie = notations.get_tie ()
298                         if mxl_tie and mxl_tie.type == 'start':
299                                 ev_chord.append (musicexp.TieEvent ())
300
301                 mxl_beams = [b for b in n.get_named_children ('beam')
302                              if b.get_type () in ('begin', 'end')] 
303                 if mxl_beams:
304                         beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
305                         if beam_ev:
306                                 ev_chord.append (beam_ev)
307                         
308                 if tuplet_event:
309                         mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
310                         frac = (1,1)
311                         if mod:
312                                 frac = mod.get_fraction ()
313                                 
314                         tuplet_events.append ((ev_chord, tuplet_event, frac))
315
316         ly_voice = group_tuplets (ly_voice, tuplet_events)
317
318         seq_music = musicexp.SequentialMusic()
319         
320         seq_music.elements = ly_voice
321         return seq_music
322
323
324 def musicxml_id_to_lily (id):
325         digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
326                   'nine', 'ten']
327         
328         for dig in digits:
329                 d = digits.index (dig) + 1
330                 dig = dig[0].upper() + dig[1:]
331                 id = re.sub ('%d' % d, dig, id)
332
333         id = re.sub  ('[^a-zA-Z]', 'X', id)
334         return id
335
336
337 def musicxml_pitch_to_lily (mxl_pitch):
338         p = musicexp.Pitch()
339         p.alteration = mxl_pitch.get_alteration ()
340         p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
341         p.octave = mxl_pitch.get_octave () - 4
342         return p
343
344
345
346 def voices_in_part (part):
347         """Return a Name -> Voice dictionary for PART"""
348         part.interpret ()
349         part.extract_voices ()          
350         voice_dict = part.get_voices ()
351
352         return voice_dict
353
354 def voices_in_part_in_parts (parts):
355         """return a Part -> Name -> Voice dictionary"""
356         return dict([(p, voices_in_part (p)) for p in parts])
357
358
359 def get_all_voices (parts):
360         all_voices = voices_in_part_in_parts (parts)
361
362         all_ly_voices = {}
363         for p, name_voice in all_voices.items ():
364
365                 part_ly_voices = {}
366                 for n, v in name_voice.items ():
367                         progress ("Converting to LilyPond expressions...")
368                         part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
369
370                 all_ly_voices[p] = part_ly_voices
371                 
372         return all_ly_voices
373
374
375 def option_parser ():
376         p = ly.get_option_parser(usage='musicxml2ly FILE.xml',
377                                   version = """%prog (LilyPond) @TOPLEVEL_VERSION@
378
379 This program is free software.  It is covered by the GNU General Public
380 License and you are welcome to change it and/or distribute copies of it
381 under certain conditions.  Invoke as `lilypond --warranty' for more
382 information.
383
384 Copyright (c) 2005--2006 by
385   Han-Wen Nienhuys <hanwen@xs4all.nl> and
386   Jan Nieuwenhuizen <janneke@gnu.org>
387 """,
388
389                                   description  =
390                                   """Convert MusicXML file to LilyPond input.
391 """
392                                   )
393         p.add_option ('-v', '--verbose',
394                       action = "store_true",
395                       dest = 'verbose',
396                       help = 'be verbose')
397         p.add_option ('-o', '--output',
398                       metavar = 'FILE',
399                       action = "store",
400                       default = None,
401                       type = 'string',
402                       dest = 'output',
403                       help = 'set output file')
404
405         p.add_option_group  ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
406 ''')
407         return p
408
409 def music_xml_voice_name_to_lily_name (part, name):
410         str = "Part%sVoice%s" % (part.id, name)
411         return musicxml_id_to_lily (str) 
412
413 def print_voice_definitions (printer, voices):
414         for (part, nv_dict) in voices.items():
415                 for (name, (voice, mxlvoice)) in nv_dict.items ():
416                         k = music_xml_voice_name_to_lily_name (part, name)
417                         printer.dump ('%s = ' % k)
418                         voice.print_ly (printer)
419                         printer.newline()
420 def uniq_list (l):
421         return dict ([(elt,1) for elt in l]).keys ()
422         
423 def print_score_setup (printer, part_list, voices):
424         part_dict = dict ([(p.id, p) for p in voices.keys ()]) 
425
426         printer ('<<')
427         printer.newline ()
428         for part_definition in part_list:
429                 part_name = part_definition.id
430                 try:
431                         part = part_dict[part_name]
432                 except KeyError:
433                         print 'unknown part in part-list:', part_name
434                         continue
435
436                 nv_dict = voices[part]
437                 staves = reduce (lambda x,y: x+ y,
438                                  [mxlvoice._staves.keys ()
439                                   for (v, mxlvoice) in nv_dict.values ()],
440                                  [])
441
442                 if len (staves) > 1:
443                         staves = uniq_list (staves)
444                         staves.sort ()
445                         printer ('\\context PianoStaff << ')
446                         printer.newline ()
447                         
448                         for s in staves:
449                                 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
450                                                 for (voice_name, (v, mxlvoice)) in nv_dict.items ()
451                                                 if mxlvoice._start_staff == s]
452                                 
453                                 printer ('\\context Staff = "%s" << ' % s)
454                                 printer.newline ()
455                                 for v in staff_voices:
456                                         printer ('\\context Voice = "%s"  \\%s' % (v,v))
457                                         printer.newline ()
458                                 printer ('>>')
459                                 printer.newline ()
460                                 
461                         printer ('>>')
462                         printer.newline ()
463                         
464                 else:
465                         printer ('\\new Staff <<')
466                         printer.newline ()
467                         for (n,v) in nv_dict.items ():
468
469                                 n = music_xml_voice_name_to_lily_name (part, n) 
470                                 printer ('\\context Voice = "%s"  \\%s' % (n,n))
471                         printer ('>>')
472                         printer.newline ()
473                         
474
475         printer ('>>')
476         printer.newline ()
477
478                                 
479
480 def print_ly_preamble (printer, filename):
481         printer.dump_version ()
482         printer.print_verbatim ('%% converted from %s\n' % filename)
483
484 def convert (filename, output_name):
485         printer = musicexp.Output_printer()
486         progress ("Reading MusicXML...")
487         
488         tree = musicxml.read_musicxml (filename)
489         parts = tree.get_typed_children (musicxml.Part)
490         voices = get_all_voices (parts)
491
492         part_list = []
493         if tree.get_maybe_exist_typed_child (musicxml.Part_list):
494                 pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
495                 part_list = pl.get_named_children ("score-part")
496                 
497         if not output_name:
498                 output_name = os.path.basename (filename)
499                 output_name = os.path.splitext (output_name)[0] + '.ly'
500
501                 
502         if output_name:
503                 progress ("Output to `%s'" % output_name)
504                 printer.set_file (open (output_name, 'w'))
505         
506         progress ("Printing as .ly...")
507
508         print_ly_preamble (printer, filename)
509         print_voice_definitions (printer,  voices)
510         print_score_setup (printer, part_list, voices)
511         printer.newline ()
512         return voices
513
514
515 def main ():
516         opt_parser = option_parser()
517
518         (options, args) = opt_parser.parse_args ()
519         if not args:
520                 opt_parser.print_usage()
521                 sys.exit (2)
522
523         voices = convert (args[0], options.output)
524
525 if __name__ == '__main__':
526         main()