]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
*** empty log message ***
[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 import musicxml
10
11
12
13
14 datadir = '@local_lilypond_datadir@'
15 if not os.path.isdir (datadir):
16     datadir = '@lilypond_datadir@'
17 if os.environ.has_key ('LILYPONDPREFIX'):
18     datadir = os.environ['LILYPONDPREFIX']
19     while datadir[-1] == os.sep:
20         datadir = datadir[:-1]
21
22 if os.path.exists (os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')):
23     datadir = os.path.join (datadir, 'share/lilypond/@TOPLEVEL_VERSION@/')
24 elif os.path.exists (os.path.join (datadir, 'share/lilypond/current/')):
25     datadir = os.path.join (datadir, 'share/lilypond/current/')
26
27 sys.path.insert (0, os.path.join (datadir, 'python'))
28
29 # dynamic relocation, for GUB binaries.
30 bindir = os.path.split (sys.argv[0])[0]
31
32 for prefix_component in ['share', 'lib']:
33     datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
34     sys.path.insert (0, datadir)
35
36
37 import lilylib as ly
38
39 import musicxml
40 import musicexp
41
42 from rational import Rational
43
44
45 def progress (str):
46     sys.stderr.write (str + '\n')
47     sys.stderr.flush ()
48     
49
50 def musicxml_duration_to_lily (mxl_note):
51     d = musicexp.Duration ()
52     if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
53         d.duration_log = mxl_note.get_duration_log ()
54     else:
55         d.duration_log = 0
56
57     d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
58     d.factor = mxl_note._duration / d.get_length ()
59
60     return d         
61
62 def group_tuplets (music_list, events):
63
64
65     """Collect Musics from
66     MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
67     """
68
69     
70     indices = []
71
72     j = 0
73     for (ev_chord, tuplet_elt, fraction) in events:
74         while (j < len (music_list)):
75             if music_list[j]== ev_chord:
76                 break
77             j += 1
78         if tuplet_elt.type == 'start':
79             indices.append ((j, None, fraction))
80         elif tuplet_elt.type == 'stop':
81             indices[-1] = (indices[-1][0], j, indices[-1][2])
82
83     new_list = []
84     last = 0
85     for (i1, i2, frac) in indices:
86         if i1 >= i2:
87             continue
88
89         new_list.extend (music_list[last:i1])
90         seq = musicexp.SequentialMusic ()
91         last = i2 + 1
92         seq.elements = music_list[i1:last]
93
94         tsm = musicexp.TimeScaledMusic ()
95         tsm.element = seq
96
97         tsm.numerator = frac[0]
98         tsm.denominator  = frac[1]
99
100         new_list.append (tsm)
101
102     new_list.extend (music_list[last:])
103     return new_list
104
105
106 def musicxml_clef_to_lily (attributes):
107     change = musicexp.ClefChange ()
108     change.type = attributes.get_clef_sign ()
109     return change
110     
111 def musicxml_time_to_lily (attributes):
112     (beats, type) = attributes.get_time_signature ()
113
114     change = musicexp.TimeSignatureChange()
115     change.fraction = (beats, type)
116     
117     return change
118
119 def musicxml_key_to_lily (attributes):
120     start_pitch  = musicexp.Pitch ()
121     (fifths, mode) = attributes.get_key_signature () 
122     try:
123         (n,a) = {
124             'major' : (0,0),
125             'minor' : (6,0),
126             }[mode]
127         start_pitch.step = n
128         start_pitch.alteration = a
129     except  KeyError:
130         print 'unknown mode', mode
131
132     fifth = musicexp.Pitch()
133     fifth.step = 4
134     if fifths < 0:
135         fifths *= -1
136         fifth.step *= -1
137         fifth.normalize ()
138     
139     start_pitch = musicexp.Pitch()
140     for x in range (fifths):
141         start_pitch = start_pitch.transposed (fifth)
142
143     start_pitch.octave = 0
144
145     change = musicexp.KeySignatureChange()
146     change.mode = mode
147     change.tonic = start_pitch
148     return change
149     
150 def musicxml_attributes_to_lily (attrs):
151     elts = []
152     attr_dispatch =  {
153         'clef': musicxml_clef_to_lily,
154         'time': musicxml_time_to_lily,
155         'key': musicxml_key_to_lily
156     }
157     for (k, func) in attr_dispatch.items ():
158         childs = attrs.get_named_children (k)
159
160         ## ugh: you get clefs spread over staves for piano
161         if childs:
162             elts.append (func (attrs))
163     
164     return elts
165
166 spanner_event_dict = {
167     'slur' : musicexp.SlurEvent,
168     'beam' : musicexp.BeamEvent,
169 }        
170 spanner_type_dict = {
171     'start': -1,
172     'begin': -1,
173     'stop': 1,
174     'end' : 1
175 }
176
177 def musicxml_spanner_to_lily_event (mxl_event):
178     ev = None
179     
180     name = mxl_event.get_name()
181     try:
182         func = spanner_event_dict[name]
183         ev = func()
184     except KeyError:
185         print 'unknown span event ', mxl_event
186
187     try:
188         key = mxl_event.get_type ()
189         ev.span_direction = spanner_type_dict[key]
190     except KeyError:
191         print 'unknown span type', key, 'for', name
192
193     return ev
194
195 instrument_drumtype_dict = {
196     'Acoustic Snare Drum': 'acousticsnare',
197     'Side Stick': 'sidestick',
198     'Open Triangle': 'opentriangle',
199     'Tambourine': 'tambourine',
200     
201 }
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     elif n.instrument_name:
222         event = musicexp.NoteEvent ()
223         event.drum_type = instrument_drumtype_dict[n.instrument_name]
224         
225     
226     if not event:
227         n.message ("could not find suitable event")
228
229     event.duration = musicxml_duration_to_lily (n)
230     return event
231
232
233 ## todo
234 class NegativeSkip:
235     def __init__ (self, here, dest):
236         self.here = here
237         self.dest = dest
238
239 class LilyPondVoiceBuilder:
240     def __init__ (self):
241         self.elements = []
242         self.end_moment = Rational (0)
243         self.begin_moment = Rational (0)
244         self.pending_multibar = Rational (0)
245
246     def _insert_multibar (self):
247         r = musicexp.MultiMeasureRest ()
248         r.duration = musicexp.Duration()
249         r.duration.duration_log = 0
250         r.duration.factor = self.pending_multibar
251         self.elements.append (r)
252         self.begin_moment = self.end_moment
253         self.end_moment = self.begin_moment + self.pending_multibar
254         self.pending_multibar = Rational (0)
255         
256     def add_multibar_rest (self, duration):
257         self.pending_multibar += duration
258         
259         
260     def add_music (self, music, duration):
261         assert isinstance (music, musicexp.Music)
262         if self.pending_multibar > Rational (0):
263             self._insert_multibar ()
264
265         self.elements.append (music)
266         self.begin_moment = self.end_moment
267         self.end_moment = self.begin_moment + duration 
268
269     def add_bar_check (self, number):
270         b = musicexp.BarCheck ()
271         b.bar_number = number
272         self.add_music (b, Rational (0))
273
274     def jumpto (self, moment):
275         current_end = self.end_moment + self.pending_multibar
276         diff = moment - current_end
277         
278         if diff < Rational (0):
279             raise NegativeSkip(current_end, moment)
280
281         if diff > Rational (0):
282             skip = musicexp.SkipEvent()
283             skip.duration.duration_log = 0
284             skip.duration.factor = diff
285
286             evc = musicexp.EventChord ()
287             evc.elements.append (skip)
288             self.add_music (evc, diff)
289                 
290     def last_event_chord (self, starting_at):
291         if (self.elements
292             and isinstance (self.elements[-1], musicexp.EventChord)
293             and self.begin_moment == starting_at):
294             return self.elements[-1]
295         else:
296             self.jumpto (starting_at)
297             return None
298     def correct_negative_skip (self, goto):
299         self.end_moment = goto
300         self.begin_moment = goto
301         evc = musicexp.EventChord ()
302         self.elements.append (evc)
303         
304 def musicxml_voice_to_lily_voice (voice):
305     tuplet_events = []
306     modes_found = {}
307
308     voice_builder = LilyPondVoiceBuilder()
309     for n in voice._elements:
310         if n.get_name () == 'forward':
311             continue
312
313         try:
314             voice_builder.jumpto (n._when)
315         except NegativeSkip, neg:
316             voice_builder.correct_negative_skip (n._when)
317             n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
318             
319         if isinstance (n, musicxml.Attributes):
320             if n.is_first () and n._measure_position == Rational (0):
321                 voice_builder.add_bar_check (int (n.get_parent ().number))
322             for a in musicxml_attributes_to_lily (n):
323                 voice_builder.add_music (a, Rational (0))
324             continue
325
326         if not n.__class__.__name__ == 'Note':
327             print 'not a Note or Attributes?', n
328             continue
329
330         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
331         if (rest
332             and rest.is_whole_measure ()):
333
334             voice_builder.add_multibar_rest (n._duration)
335             continue
336
337         if n.is_first () and n._measure_position == Rational (0):
338             num = int (n.get_parent ().number)
339             voice_builder.add_bar_check (num)
340         
341         main_event = musicxml_note_to_lily_main_event (n)
342
343         try:
344             if main_event.drum_type:
345                 modes_found['drummode'] = True
346         except AttributeError:
347             pass
348
349
350         ev_chord = voice_builder.last_event_chord (n._when)
351         if not ev_chord: 
352             ev_chord = musicexp.EventChord()
353
354         
355         ev_chord.append (main_event)
356         voice_builder.add_music (ev_chord, n._duration)
357         
358         notations = n.get_maybe_exist_typed_child (musicxml.Notations)
359         tuplet_event = None
360         span_events = []
361         if notations:
362             if notations.get_tuplet():
363                 tuplet_event = notations.get_tuplet()
364                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
365                 frac = (1,1)
366                 if mod:
367                     frac = mod.get_fraction ()
368                 
369                 tuplet_events.append ((ev_chord, tuplet_event, frac))
370
371             slurs = [s for s in notations.get_named_children ('slur')
372                 if s.get_type () in ('start','stop')]
373             if slurs:
374                 if len (slurs) > 1:
375                     print 'more than 1 slur?'
376
377                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
378                 ev_chord.append (lily_ev)
379
380             mxl_tie = notations.get_tie ()
381             if mxl_tie and mxl_tie.type == 'start':
382                 ev_chord.append (musicexp.TieEvent ())
383
384         mxl_beams = [b for b in n.get_named_children ('beam')
385                      if (b.get_type () in ('begin', 'end')
386                          and b.is_primary ())] 
387         if mxl_beams:
388             beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
389             if beam_ev:
390                 ev_chord.append (beam_ev)
391             
392         if tuplet_event:
393             mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
394             frac = (1,1)
395             if mod:
396                 frac = mod.get_fraction ()
397                 
398             tuplet_events.append ((ev_chord, tuplet_event, frac))
399
400     ## force trailing mm rests to be written out.   
401     voice_builder.add_music (musicexp.EventChord ())
402     
403     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
404
405     seq_music = musicexp.SequentialMusic()
406
407     if 'drummode' in modes_found.keys ():
408         ## \key <pitch> barfs in drummode.
409         ly_voice = [e for e in ly_voice
410                     if not isinstance(e, musicexp.KeySignatureChange)]
411     
412     seq_music.elements = ly_voice
413
414     
415     
416     if len (modes_found) > 1:
417        print 'Too many modes found', modes_found.keys ()
418
419     return_value = seq_music
420     for mode in modes_found.keys ():
421         v = musicexp.ModeChangingMusicWrapper()
422         v.element = return_value
423         v.mode = mode
424         return_value = v
425     
426     return return_value
427
428
429 def musicxml_id_to_lily (id):
430     digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
431               'nine', 'ten']
432     
433     for dig in digits:
434         d = digits.index (dig) + 1
435         dig = dig[0].upper() + dig[1:]
436         id = re.sub ('%d' % d, dig, id)
437
438     id = re.sub  ('[^a-zA-Z]', 'X', id)
439     return id
440
441
442 def musicxml_pitch_to_lily (mxl_pitch):
443     p = musicexp.Pitch()
444     p.alteration = mxl_pitch.get_alteration ()
445     p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
446     p.octave = mxl_pitch.get_octave () - 4
447     return p
448
449 def voices_in_part (part):
450     """Return a Name -> Voice dictionary for PART"""
451     part.interpret ()
452     part.extract_voices ()
453     voice_dict = part.get_voices ()
454
455     return voice_dict
456
457 def voices_in_part_in_parts (parts):
458     """return a Part -> Name -> Voice dictionary"""
459     return dict([(p, voices_in_part (p)) for p in parts])
460
461
462 def get_all_voices (parts):
463     all_voices = voices_in_part_in_parts (parts)
464
465     all_ly_voices = {}
466     for p, name_voice in all_voices.items ():
467
468         part_ly_voices = {}
469         for n, v in name_voice.items ():
470             progress ("Converting to LilyPond expressions...")
471             part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
472
473         all_ly_voices[p] = part_ly_voices
474         
475     return all_ly_voices
476
477
478 def option_parser ():
479     p = ly.get_option_parser(usage='musicxml2ly FILE.xml',
480                  version = """%prog (LilyPond) @TOPLEVEL_VERSION@
481
482 This program is free software.  It is covered by the GNU General Public
483 License and you are welcome to change it and/or distribute copies of it
484 under certain conditions.  Invoke as `lilypond --warranty' for more
485 information.
486
487 Copyright (c) 2005--2006 by
488     Han-Wen Nienhuys <hanwen@xs4all.nl> and
489     Jan Nieuwenhuizen <janneke@gnu.org>
490 """,
491
492                  description  =
493                  """Convert MusicXML file to LilyPond input.
494 """
495                  )
496     p.add_option ('-v', '--verbose',
497                   action = "store_true",
498                   dest = 'verbose',
499                   help = 'be verbose')
500
501     p.add_option ('', '--lxml',
502                   action="store_true",
503                   default=False,
504                   dest="use_lxml",
505                   help="Use lxml.etree; uses less memory and cpu time.")
506     
507     p.add_option ('-o', '--output',
508                   metavar = 'FILE',
509                   action="store",
510                   default=None,
511                   type='string',
512                   dest='output_name',
513                   help='set output file')
514
515     p.add_option_group  ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
516 ''')
517     return p
518
519 def music_xml_voice_name_to_lily_name (part, name):
520     str = "Part%sVoice%s" % (part.id, name)
521     return musicxml_id_to_lily (str) 
522
523 def print_voice_definitions (printer, voices):
524     for (part, nv_dict) in voices.items():
525         
526         for (name, (voice, mxlvoice)) in nv_dict.items ():
527             k = music_xml_voice_name_to_lily_name (part, name)
528             printer.dump ('%s = ' % k)
529             voice.print_ly (printer)
530             printer.newline()
531
532             
533 def uniq_list (l):
534     return dict ([(elt,1) for elt in l]).keys ()
535     
536 def print_score_setup (printer, part_list, voices):
537     part_dict = dict ([(p.id, p) for p in voices.keys ()]) 
538
539     printer ('<<')
540     printer.newline ()
541     for part_definition in part_list:
542         part_name = part_definition.id
543         try:
544             part = part_dict[part_name]
545         except KeyError:
546             print 'unknown part in part-list:', part_name
547             continue
548
549         nv_dict = voices[part]
550         staves = reduce (lambda x,y: x+ y,
551                 [mxlvoice._staves.keys ()
552                  for (v, mxlvoice) in nv_dict.values ()],
553                 [])
554
555         if len (staves) > 1:
556             staves = uniq_list (staves)
557             staves.sort ()
558             printer ('\\context PianoStaff << ')
559             printer.newline ()
560             
561             for s in staves:
562                 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
563                         for (voice_name, (v, mxlvoice)) in nv_dict.items ()
564                         if mxlvoice._start_staff == s]
565                 
566                 printer ('\\context Staff = "%s" << ' % s)
567                 printer.newline ()
568                 for v in staff_voices:
569                     printer ('\\context Voice = "%s"  \\%s' % (v,v))
570                     printer.newline ()
571                 printer ('>>')
572                 printer.newline ()
573                 
574             printer ('>>')
575             printer.newline ()
576             
577         else:
578             printer ('\\new Staff <<')
579             printer.newline ()
580             for (n,v) in nv_dict.items ():
581
582                 n = music_xml_voice_name_to_lily_name (part, n) 
583                 printer ('\\context Voice = "%s"  \\%s' % (n,n))
584             printer ('>>')
585             printer.newline ()
586             
587     printer ('>>')
588     printer.newline ()
589
590 def print_ly_preamble (printer, filename):
591     printer.dump_version ()
592     printer.print_verbatim ('%% converted from %s\n' % filename)
593
594 def read_musicxml (filename, use_lxml):
595     if use_lxml:
596         import lxml.etree
597         
598         tree = lxml.etree.parse (filename)
599         mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
600         return mxl_tree
601     else:
602         from xml.dom import minidom, Node
603         
604         doc = minidom.parse(filename)
605         node = doc.documentElement
606         return musicxml.minidom_demarshal_node (node)
607
608     return None
609
610
611 def convert (filename, options):
612     progress ("Reading MusicXML from %s ..." % filename)
613     
614     tree = read_musicxml (filename, options.use_lxml)
615
616     part_list = []
617     id_instrument_map = {}
618     if tree.get_maybe_exist_typed_child (musicxml.Part_list):
619         mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
620         part_list = mxl_pl.get_named_children ("score-part")
621         
622     parts = tree.get_typed_children (musicxml.Part)
623     voices = get_all_voices (parts)
624
625     if not options.output_name:
626         options.output_name = os.path.basename (filename) 
627         options.output_name = os.path.splitext (options.output_name)[0]
628
629
630     defs_ly_name = options.output_name + '-defs.ly'
631     driver_ly_name = options.output_name + '.ly'
632
633     printer = musicexp.Output_printer()
634     progress ("Output to `%s'" % defs_ly_name)
635     printer.set_file (open (defs_ly_name, 'w'))
636
637     print_ly_preamble (printer, filename)
638     print_voice_definitions (printer, voices)
639     
640     printer.close ()
641     
642     
643     progress ("Output to `%s'" % driver_ly_name)
644     printer = musicexp.Output_printer()
645     printer.set_file (open (driver_ly_name, 'w'))
646     print_ly_preamble (printer, filename)
647     printer.dump (r'\include "%s"' % defs_ly_name)
648     print_score_setup (printer, part_list, voices)
649     printer.newline ()
650
651     return voices
652
653
654 def main ():
655     opt_parser = option_parser()
656
657     (options, args) = opt_parser.parse_args ()
658     if not args:
659         opt_parser.print_usage()
660         sys.exit (2)
661
662     voices = convert (args[0], options)
663
664 if __name__ == '__main__':
665     main()