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