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