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