]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
MusicXML: Support for upbeats and partial/implicit measures
[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 import codecs
9 from gettext import gettext as _
10
11 """
12 @relocate-preamble@
13 """
14
15 import lilylib as ly
16
17 import musicxml
18 import musicexp
19
20 from rational import Rational
21
22
23 def progress (str):
24     sys.stderr.write (str + '\n')
25     sys.stderr.flush ()
26
27 def error_message (str):
28     sys.stderr.write (str + '\n')
29     sys.stderr.flush ()
30
31 # score information is contained in the <work>, <identification> or <movement-title> tags
32 # extract those into a hash, indexed by proper lilypond header attributes
33 def extract_score_information (tree):
34     header = musicexp.Header ()
35     def set_if_exists (field, value):
36         if value:
37             header.set_field (field, musicxml.escape_ly_output_string (value))
38
39     work = tree.get_maybe_exist_named_child ('work')
40     if work:
41         set_if_exists ('title', work.get_work_title ())
42         set_if_exists ('worknumber', work.get_work_number ())
43         set_if_exists ('opus', work.get_opus ())
44     else:
45         movement_title = tree.get_maybe_exist_named_child ('movement-title')
46         if movement_title:
47             set_if_exists ('title', movement_title.get_text ())
48     
49     identifications = tree.get_named_children ('identification')
50     for ids in identifications:
51         set_if_exists ('copyright', ids.get_rights ())
52         set_if_exists ('composer', ids.get_composer ())
53         set_if_exists ('arranger', ids.get_arranger ())
54         set_if_exists ('editor', ids.get_editor ())
55         set_if_exists ('poet', ids.get_poet ())
56             
57         set_if_exists ('tagline', ids.get_encoding_software ())
58         set_if_exists ('encodingsoftware', ids.get_encoding_software ())
59         set_if_exists ('encodingdate', ids.get_encoding_date ())
60         set_if_exists ('encoder', ids.get_encoding_person ())
61         set_if_exists ('encodingdescription', ids.get_encoding_description ())
62
63     return header
64
65
66 def extract_score_layout (part_list):
67     layout = musicexp.StaffGroup (None)
68     currentgroups_dict = {}
69     currentgroups = []
70     if not part_list:
71         return layout
72
73     def insert_into_layout (object):
74             if len (currentgroups) > 0:
75                 group_to_insert = currentgroups_dict.get (currentgroups [-1], layout)
76             else:
77                 group_to_insert = layout
78             group_to_insert.appendStaff (object)
79             return group_to_insert
80
81     def read_score_part (el):
82         if not isinstance (el, musicxml.Score_part):
83             return
84         staff = musicexp.Staff ()
85         staff.id = el.id
86         partname = el.get_maybe_exist_named_child ('part-name')
87         # Finale gives unnamed parts the name "MusicXML Part" automatically!
88         if partname and partname.get_text() != "MusicXML Part":
89             staff.instrument_name = partname.get_text ()
90         if el.get_maybe_exist_named_child ('part-abbreviation'):
91             staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
92         # TODO: Read in the MIDI device / instrument
93         return staff
94
95
96     parts_groups = part_list.get_all_children ()
97     # the start/end group tags are not necessarily ordered correctly, so
98     # we can't go through the children sequentially!
99
100     if len (parts_groups) == 1 and isinstance (parts_group[1], musicxml.Score_part):
101         return read_score_part (parts_group[1])
102
103     for el in parts_groups:
104         if isinstance (el, musicxml.Score_part):
105             staff = read_score_part (el)
106             insert_into_layout (staff)
107         elif isinstance (el, musicxml.Part_group):
108             if el.type == "start":
109                 group = musicexp.StaffGroup ()
110                 staff_group = insert_into_layout (group)
111                 # If we're inserting a nested staffgroup, we need to use InnerStaffGroup
112                 if staff_group != layout:
113                     group.stafftype = "InnerStaffGroup"
114                 if hasattr (el, 'number'):
115                     id = el.number
116                     group.id = id
117                     currentgroups_dict[id] = group
118                     currentgroups.append (id)
119                 if el.get_maybe_exist_named_child ('group-name'):
120                     group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
121                 if el.get_maybe_exist_named_child ('group-abbreviation'):
122                     group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
123                 if el.get_maybe_exist_named_child ('group-symbol'):
124                     group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
125                 if el.get_maybe_exist_named_child ('group-barline'):
126                     group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
127
128             elif el.type == "stop":
129                 # end the part-group, i.e. simply remove it from the lists
130                 if hasattr (el, 'number'):
131                     pid = el.number
132                 elif len (currentgroups) > 0:
133                     pid = el[-1]
134                 if pid:
135                     del currentgroups_dict[pid]
136                     currentgroups.remove (pid)
137     return layout
138
139
140
141 def musicxml_duration_to_lily (mxl_note):
142     d = musicexp.Duration ()
143     # if the note has no Type child, then that method spits out a warning and 
144     # returns 0, i.e. a whole note
145     d.duration_log = mxl_note.get_duration_log ()
146
147     d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
148     # Grace notes by specification have duration 0, so no time modification 
149     # factor is possible. It even messes up the output with *0/1
150     if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
151         d.factor = mxl_note._duration / d.get_length ()
152
153     return d
154
155 def rational_to_lily_duration (rational_len):
156     d = musicexp.Duration ()
157     d.duration_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (rational_len.denominator (), -1)
158     d.factor = Rational (rational_len.numerator ())
159     return d
160
161 def musicxml_partial_to_lily (partial_len):
162     if partial_len > 0:
163         p = musicexp.Partial ()
164         p.partial = rational_to_lily_duration (partial_len)
165         return p
166     else:
167         return Null
168
169 def group_tuplets (music_list, events):
170
171
172     """Collect Musics from
173     MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
174     """
175
176     
177     indices = []
178
179     j = 0
180     for (ev_chord, tuplet_elt, fraction) in events:
181         while (j < len (music_list)):
182             if music_list[j] == ev_chord:
183                 break
184             j += 1
185         if tuplet_elt.type == 'start':
186             indices.append ((j, None, fraction))
187         elif tuplet_elt.type == 'stop':
188             indices[-1] = (indices[-1][0], j, indices[-1][2])
189
190     new_list = []
191     last = 0
192     for (i1, i2, frac) in indices:
193         if i1 >= i2:
194             continue
195
196         new_list.extend (music_list[last:i1])
197         seq = musicexp.SequentialMusic ()
198         last = i2 + 1
199         seq.elements = music_list[i1:last]
200
201         tsm = musicexp.TimeScaledMusic ()
202         tsm.element = seq
203
204         tsm.numerator = frac[0]
205         tsm.denominator  = frac[1]
206
207         new_list.append (tsm)
208
209     new_list.extend (music_list[last:])
210     return new_list
211
212
213 def musicxml_clef_to_lily (attributes):
214     change = musicexp.ClefChange ()
215     (change.type, change.position, change.octave) = attributes.get_clef_information ()
216     return change
217     
218 def musicxml_time_to_lily (attributes):
219     (beats, type) = attributes.get_time_signature ()
220
221     change = musicexp.TimeSignatureChange()
222     change.fraction = (beats, type)
223     
224     return change
225
226 def musicxml_key_to_lily (attributes):
227     start_pitch  = musicexp.Pitch ()
228     (fifths, mode) = attributes.get_key_signature () 
229     try:
230         (n,a) = {
231             'major' : (0,0),
232             'minor' : (5,0),
233             }[mode]
234         start_pitch.step = n
235         start_pitch.alteration = a
236     except  KeyError:
237         error_message ('unknown mode %s' % mode)
238
239     fifth = musicexp.Pitch()
240     fifth.step = 4
241     if fifths < 0:
242         fifths *= -1
243         fifth.step *= -1
244         fifth.normalize ()
245     
246     for x in range (fifths):
247         start_pitch = start_pitch.transposed (fifth)
248
249     start_pitch.octave = 0
250
251     change = musicexp.KeySignatureChange()
252     change.mode = mode
253     change.tonic = start_pitch
254     return change
255     
256 def musicxml_attributes_to_lily (attrs):
257     elts = []
258     attr_dispatch =  {
259         'clef': musicxml_clef_to_lily,
260         'time': musicxml_time_to_lily,
261         'key': musicxml_key_to_lily
262     }
263     for (k, func) in attr_dispatch.items ():
264         children = attrs.get_named_children (k)
265         if children:
266             elts.append (func (attrs))
267     
268     return elts
269
270 spanner_event_dict = {
271     'slur' : musicexp.SlurEvent,
272     'beam' : musicexp.BeamEvent,
273     'glissando' : musicexp.GlissandoEvent,
274     'pedal' : musicexp.PedalEvent,
275     'wavy-line' : musicexp.TrillSpanEvent,
276     'octave-shift' : musicexp.OctaveShiftEvent,
277     'wedge' : musicexp.HairpinEvent
278 }
279 spanner_type_dict = {
280     'start': -1,
281     'begin': -1,
282     'crescendo': -1,
283     'decreschendo': -1,
284     'diminuendo': -1,
285     'continue': 0,
286     'up': -1,
287     'down': -1,
288     'stop': 1,
289     'end' : 1
290 }
291
292 def musicxml_spanner_to_lily_event (mxl_event):
293     ev = None
294     
295     name = mxl_event.get_name()
296     func = spanner_event_dict.get (name)
297     if func:
298         ev = func()
299     else:
300         error_message ('unknown span event %s' % mxl_event)
301
302
303     type = mxl_event.get_type ()
304     span_direction = spanner_type_dict.get (type)
305     # really check for None, because some types will be translated to 0, which
306     # would otherwise also lead to the unknown span warning
307     if span_direction != None:
308         ev.span_direction = span_direction
309     else:
310         error_message ('unknown span type %s for %s' % (type, name))
311
312     ev.set_span_type (type)
313     ev.line_type = getattr (mxl_event, 'line-type', 'solid')
314
315     # assign the size, which is used for octave-shift, etc.
316     ev.size = mxl_event.get_size ()
317
318     return ev
319
320 def musicxml_direction_to_indicator (direction):
321     return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
322
323 def musicxml_fermata_to_lily_event (mxl_event):
324     ev = musicexp.ArticulationEvent ()
325     ev.type = "fermata"
326     if hasattr (mxl_event, 'type'):
327       dir = musicxml_direction_to_indicator (mxl_event.type)
328       if dir:
329         ev.force_direction = dir
330     return ev
331
332 def musicxml_tremolo_to_lily_event (mxl_event):
333     ev = musicexp.TremoloEvent ()
334     ev.bars = mxl_event.get_text ()
335     return ev
336
337 def musicxml_bend_to_lily_event (mxl_event):
338     ev = musicexp.BendEvent ()
339     ev.alter = mxl_event.bend_alter ()
340     return ev
341
342
343 def musicxml_fingering_event (mxl_event):
344     ev = musicexp.ShortArticulationEvent ()
345     ev.type = mxl_event.get_text ()
346     return ev
347
348 def musicxml_accidental_mark (mxl_event):
349     ev = musicexp.MarkupEvent ()
350     contents = { "sharp": "\\sharp",
351       "natural": "\\natural",
352       "flat": "\\flat",
353       "double-sharp": "\\doublesharp",
354       "sharp-sharp": "\\sharp\\sharp",
355       "flat-flat": "\\flat\\flat",
356       "flat-flat": "\\doubleflat",
357       "natural-sharp": "\\natural\\sharp",
358       "natural-flat": "\\natural\\flat",
359       "quarter-flat": "\\semiflat",
360       "quarter-sharp": "\\semisharp",
361       "three-quarters-flat": "\\sesquiflat",
362       "three-quarters-sharp": "\\sesquisharp",
363     }.get (mxl_event.get_text ())
364     if contents:
365         ev.contents = contents
366         return ev
367     else:
368         return None
369
370 # translate articulations, ornaments and other notations into ArticulationEvents
371 # possible values:
372 #   -) string  (ArticulationEvent with that name)
373 #   -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
374 #   -) (class, name)  (like string, only that a different class than ArticulationEvent is used)
375 # TODO: Some translations are missing!
376 articulations_dict = {
377     "accent": (musicexp.ShortArticulationEvent, ">"),
378     "accidental-mark": musicxml_accidental_mark,
379     "bend": musicxml_bend_to_lily_event,
380     "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
381     #"caesura": "caesura",
382     #"delayed-turn": "?",
383     #"detached-legato": "",
384     #"doit": "",
385     #"double-tongue": "",
386     "down-bow": "downbow",
387     #"falloff": "",
388     "fingering": musicxml_fingering_event,
389     #"fingernails": "",
390     #"fret": "",
391     #"hammer-on": "",
392     "harmonic": "flageolet",
393     #"heel": "",
394     "inverted-mordent": "prall",
395     "inverted-turn": "reverseturn",
396     "mordent": "mordent",
397     #"open-string": "",
398     #"plop": "",
399     #"pluck": "",
400     #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
401     #"pull-off": "",
402     #"schleifer": "?",
403     #"scoop": "",
404     #"shake": "?",
405     #"snap-pizzicato": "",
406     #"spiccato": "",
407     "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
408     "staccato": (musicexp.ShortArticulationEvent, "."),
409     "stopped": (musicexp.ShortArticulationEvent, "+"),
410     #"stress": "",
411     #"string": "",
412     "strong-accent": (musicexp.ShortArticulationEvent, "^"),
413     #"tap": "",
414     "tenuto": (musicexp.ShortArticulationEvent, "-"),
415     #"thumb-position": "",
416     #"toe": "",
417     "turn": "turn",
418     "tremolo": musicxml_tremolo_to_lily_event,
419     "trill-mark": "trill",
420     #"triple-tongue": "",
421     #"unstress": ""
422     "up-bow": "upbow",
423     #"wavy-line": "?",
424 }
425 articulation_spanners = [ "wavy-line" ]
426
427 def musicxml_articulation_to_lily_event (mxl_event):
428     # wavy-line elements are treated as trill spanners, not as articulation ornaments
429     if mxl_event.get_name () in articulation_spanners:
430         return musicxml_spanner_to_lily_event (mxl_event)
431
432     tmp_tp = articulations_dict.get (mxl_event.get_name ())
433     if not tmp_tp:
434         return
435
436     if isinstance (tmp_tp, str):
437         ev = musicexp.ArticulationEvent ()
438         ev.type = tmp_tp
439     elif isinstance (tmp_tp, tuple):
440         ev = tmp_tp[0] ()
441         ev.type = tmp_tp[1]
442     else:
443         ev = tmp_tp (mxl_event)
444
445     # Some articulations use the type attribute, other the placement...
446     dir = None
447     if hasattr (mxl_event, 'type'):
448         dir = musicxml_direction_to_indicator (mxl_event.type)
449     if hasattr (mxl_event, 'placement'):
450         dir = musicxml_direction_to_indicator (mxl_event.placement)
451     return ev
452
453
454 def musicxml_dynamics_to_lily_event (dynentry):
455     dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
456         "f", "ff", "fff", "ffff", "fffff", "ffffff",
457         "mp", "mf", "sf", "sfp", "sfpp", "fp",
458         "rf", "rfz", "sfz", "sffz", "fz" )
459     if not dynentry.get_name() in dynamics_available:
460         return
461     event = musicexp.DynamicsEvent ()
462     event.type = dynentry.get_name ()
463     return event
464
465
466 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
467
468 def musicxml_direction_to_lily (n):
469     # TODO: Handle the <staff> element!
470     res = []
471     dirtype_children = []
472     for dt in n.get_typed_children (musicxml.DirType):
473         dirtype_children += dt.get_all_children ()
474
475     for entry in dirtype_children:
476         if entry.get_name () == "dynamics":
477             for dynentry in entry.get_all_children ():
478                 ev = musicxml_dynamics_to_lily_event (dynentry)
479                 if ev:
480                     res.append (ev)
481
482         # octave shifts. pedal marks, hairpins etc. are spanners:
483         if entry.get_name() in direction_spanners:
484             event = musicxml_spanner_to_lily_event (entry)
485             if event:
486                 res.append (event)
487
488
489     return res
490
491 instrument_drumtype_dict = {
492     'Acoustic Snare Drum': 'acousticsnare',
493     'Side Stick': 'sidestick',
494     'Open Triangle': 'opentriangle',
495     'Mute Triangle': 'mutetriangle',
496     'Tambourine': 'tambourine',
497     'Bass Drum': 'bassdrum',
498 }
499
500 def musicxml_note_to_lily_main_event (n):
501     pitch  = None
502     duration = None
503         
504     mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
505     event = None
506     if mxl_pitch:
507         pitch = musicxml_pitch_to_lily (mxl_pitch)
508         event = musicexp.NoteEvent()
509         event.pitch = pitch
510
511         acc = n.get_maybe_exist_named_child ('accidental')
512         if acc:
513             # let's not force accs everywhere. 
514             event.cautionary = acc.editorial
515         
516     elif n.get_maybe_exist_typed_child (musicxml.Rest):
517         # rests can have display-octave and display-step, which are
518         # treated like an ordinary note pitch
519         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
520         event = musicexp.RestEvent()
521         pitch = musicxml_restdisplay_to_lily (rest)
522         event.pitch = pitch
523     elif n.instrument_name:
524         event = musicexp.NoteEvent ()
525         drum_type = instrument_drumtype_dict.get (n.instrument_name)
526         if drum_type:
527             event.drum_type = drum_type
528         else:
529             n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
530             event.drum_type = 'acousticsnare'
531     
532     if not event:
533         n.message ("cannot find suitable event")
534
535     event.duration = musicxml_duration_to_lily (n)
536     return event
537
538
539 ## TODO
540 class NegativeSkip:
541     def __init__ (self, here, dest):
542         self.here = here
543         self.dest = dest
544
545 class LilyPondVoiceBuilder:
546     def __init__ (self):
547         self.elements = []
548         self.pending_dynamics = []
549         self.end_moment = Rational (0)
550         self.begin_moment = Rational (0)
551         self.pending_multibar = Rational (0)
552         self.ignore_skips = False
553
554     def _insert_multibar (self):
555         r = musicexp.MultiMeasureRest ()
556         r.duration = musicexp.Duration()
557         r.duration.duration_log = 0
558         r.duration.factor = self.pending_multibar
559         self.elements.append (r)
560         self.begin_moment = self.end_moment
561         self.end_moment = self.begin_moment + self.pending_multibar
562         self.pending_multibar = Rational (0)
563         
564     def add_multibar_rest (self, duration):
565         self.pending_multibar += duration
566
567     def set_duration (self, duration):
568         self.end_moment = self.begin_moment + duration
569     def current_duration (self):
570         return self.end_moment - self.begin_moment
571         
572     def add_music (self, music, duration):
573         assert isinstance (music, musicexp.Music)
574         if self.pending_multibar > Rational (0):
575             self._insert_multibar ()
576
577         self.elements.append (music)
578         self.begin_moment = self.end_moment
579         self.set_duration (duration)
580         
581         # Insert all pending dynamics right after the note/rest:
582         if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
583             for d in self.pending_dynamics:
584                 music.append (d)
585             self.pending_dynamics = []
586
587     # Insert some music command that does not affect the position in the measure
588     def add_command (self, command):
589         assert isinstance (command, musicexp.Music)
590         if self.pending_multibar > Rational (0):
591             self._insert_multibar ()
592         self.elements.append (command)
593     def add_partial (self, command):
594         self.ignore_skips = True
595         self.add_command (command)
596
597     def add_dynamics (self, dynamic):
598         # store the dynamic item(s) until we encounter the next note/rest:
599         self.pending_dynamics.append (dynamic)
600
601     def add_bar_check (self, number):
602         b = musicexp.BarCheck ()
603         b.bar_number = number
604         self.add_music (b, Rational (0))
605
606     def jumpto (self, moment):
607         current_end = self.end_moment + self.pending_multibar
608         diff = moment - current_end
609         
610         if diff < Rational (0):
611             error_message ('Negative skip %s' % diff)
612             diff = Rational (0)
613
614         if diff > Rational (0) and not self.ignore_skips:
615             skip = musicexp.SkipEvent()
616             skip.duration.duration_log = 0
617             skip.duration.factor = diff
618
619             evc = musicexp.EventChord ()
620             evc.elements.append (skip)
621             self.add_music (evc, diff)
622
623         if diff > Rational (0) and moment == 0:
624             self.ignore_skips = False
625
626     def last_event_chord (self, starting_at):
627
628         value = None
629
630         # if the position matches, find the last EventChord, do not cross a bar line!
631         at = len( self.elements ) - 1
632         while (at >= 0 and
633                not isinstance (self.elements[at], musicexp.EventChord) and
634                not isinstance (self.elements[at], musicexp.BarCheck)):
635             at -= 1
636
637         if (self.elements
638             and at >= 0
639             and isinstance (self.elements[at], musicexp.EventChord)
640             and self.begin_moment == starting_at):
641             value = self.elements[at]
642         else:
643             self.jumpto (starting_at)
644             value = None
645         return value
646         
647     def correct_negative_skip (self, goto):
648         self.end_moment = goto
649         self.begin_moment = goto
650         evc = musicexp.EventChord ()
651         self.elements.append (evc)
652         
653 def musicxml_voice_to_lily_voice (voice):
654     tuplet_events = []
655     modes_found = {}
656     lyrics = {}
657         
658     # TODO: Make sure that the keys in the dict don't get reordered, since
659     #       we need the correct ordering of the lyrics stanzas! By default,
660     #       a dict will reorder its keys
661     for k in voice.get_lyrics_numbers ():
662         lyrics[k] = []
663
664     voice_builder = LilyPondVoiceBuilder()
665
666     for n in voice._elements:
667         if n.get_name () == 'forward':
668             continue
669
670         if isinstance (n, musicxml.Partial) and n.partial > 0:
671             a = musicxml_partial_to_lily (n.partial)
672             if a:
673                 voice_builder.add_partial (a)
674             continue
675
676         if isinstance (n, musicxml.Direction):
677             for a in musicxml_direction_to_lily (n):
678                 if a.wait_for_note ():
679                     voice_builder.add_dynamics (a)
680                 else:
681                     voice_builder.add_command (a)
682             continue
683         
684         if not n.get_maybe_exist_named_child ('chord'):
685             try:
686                 voice_builder.jumpto (n._when)
687             except NegativeSkip, neg:
688                 voice_builder.correct_negative_skip (n._when)
689                 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
690             
691         if isinstance (n, musicxml.Attributes):
692             if n.is_first () and n._measure_position == Rational (0):
693                 try:
694                     number = int (n.get_parent ().number)
695                 except ValueError:
696                     number = 0
697                 if number > 0:
698                     voice_builder.add_bar_check (number)
699                 
700             for a in musicxml_attributes_to_lily (n):
701                 voice_builder.add_music (a, Rational (0))
702             continue
703
704         if not n.__class__.__name__ == 'Note':
705             error_message ('not a Note or Attributes? %s' % n)
706             continue
707
708         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
709         if (rest
710             and rest.is_whole_measure ()):
711
712             voice_builder.add_multibar_rest (n._duration)
713             continue
714
715         if n.is_first () and n._measure_position == Rational (0):
716             try: 
717                 num = int (n.get_parent ().number)
718             except ValueError:
719                 num = 0
720             if num > 0:
721                 voice_builder.add_bar_check (num)
722         
723         main_event = musicxml_note_to_lily_main_event (n)
724
725         if hasattr (main_event, 'drum_type') and main_event.drum_type:
726             modes_found['drummode'] = True
727
728
729         ev_chord = voice_builder.last_event_chord (n._when)
730         if not ev_chord: 
731             ev_chord = musicexp.EventChord()
732             voice_builder.add_music (ev_chord, n._duration)
733
734         grace = n.get_maybe_exist_typed_child (musicxml.Grace)
735         if grace:
736             grace_chord = None
737             if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
738                 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
739             if not grace_chord:
740                 grace_chord = musicexp.EventChord ()
741                 ev_chord.append_grace (grace_chord)
742             if hasattr (grace, 'slash'):
743                 # TODO: use grace_type = "appoggiatura" for slurred grace notes
744                 if grace.slash == "yes":
745                     ev_chord.grace_type = "acciaccatura"
746                 elif grace.slash == "no":
747                     ev_chord.grace_type = "grace"
748             # now that we have inserted the chord into the grace music, insert
749             # everything into that chord instead of the ev_chord
750             ev_chord = grace_chord
751             ev_chord.append (main_event)
752         else:
753             ev_chord.append (main_event)
754             # When a note/chord has grace notes (duration==0), the duration of the
755             # event chord is not yet known, but the event chord was already added
756             # with duration 0. The following correct this when we hit the real note!
757             if voice_builder.current_duration () == 0 and n._duration > 0:
758                 voice_builder.set_duration (n._duration)
759         
760         notations = n.get_maybe_exist_typed_child (musicxml.Notations)
761         tuplet_event = None
762         span_events = []
763         
764         # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
765         # +tied | +slur | +tuplet | glissando | slide | 
766         #    ornaments | technical | articulations | dynamics |
767         #    +fermata | arpeggiate | non-arpeggiate | 
768         #    accidental-mark | other-notation
769         if notations:
770             if notations.get_tuplet():
771                 tuplet_event = notations.get_tuplet()
772                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
773                 frac = (1,1)
774                 if mod:
775                     frac = mod.get_fraction ()
776                 
777                 tuplet_events.append ((ev_chord, tuplet_event, frac))
778
779             slurs = [s for s in notations.get_named_children ('slur')
780                 if s.get_type () in ('start','stop')]
781             if slurs:
782                 if len (slurs) > 1:
783                     error_message ('more than 1 slur?')
784
785                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
786                 ev_chord.append (lily_ev)
787
788             mxl_tie = notations.get_tie ()
789             if mxl_tie and mxl_tie.type == 'start':
790                 ev_chord.append (musicexp.TieEvent ())
791                 
792             fermatas = notations.get_named_children ('fermata')
793             for a in fermatas:
794                 ev = musicxml_fermata_to_lily_event (a)
795                 if ev: 
796                     ev_chord.append (ev)
797
798             arpeggiate = notations.get_named_children ('arpeggiate')
799             for a in arpeggiate:
800                 ev_chord.append (musicexp.ArpeggioEvent ())
801
802             glissandos = notations.get_named_children ('glissando')
803             for a in glissandos:
804                 ev = musicxml_spanner_to_lily_event (a)
805                 if ev:
806                     ev_chord.append (ev)
807                 
808             # Articulations can contain the following child elements:
809             #         accent | strong-accent | staccato | tenuto |
810             #         detached-legato | staccatissimo | spiccato |
811             #         scoop | plop | doit | falloff | breath-mark | 
812             #         caesura | stress | unstress
813             # Technical can contain the following child elements:
814             #         up-bow | down-bow | harmonic | open-string |
815             #         thumb-position | fingering | pluck | double-tongue |
816             #         triple-tongue | stopped | snap-pizzicato | fret |
817             #         string | hammer-on | pull-off | bend | tap | heel |
818             #         toe | fingernails | other-technical
819             # Ornaments can contain the following child elements:
820             #         trill-mark | turn | delayed-turn | inverted-turn |
821             #         shake | wavy-line | mordent | inverted-mordent | 
822             #         schleifer | tremolo | other-ornament, accidental-mark
823             ornaments = notations.get_named_children ('ornaments')
824             for a in ornaments:
825                 for ch in a.get_named_children ('tremolo'):
826                     ev = musicxml_tremolo_to_lily_event (ch)
827                     if ev: 
828                         ev_chord.append (ev)
829
830             ornaments += notations.get_named_children ('articulations')
831             ornaments += notations.get_named_children ('technical')
832
833             for a in ornaments:
834                 for ch in a.get_all_children ():
835                     ev = musicxml_articulation_to_lily_event (ch)
836                     if ev: 
837                         ev_chord.append (ev)
838
839             dynamics = notations.get_named_children ('dynamics')
840             for a in dynamics:
841                 for ch in a.get_all_children ():
842                     ev = musicxml_dynamics_to_lily_event (ch)
843                     if ev:
844                         ev_chord.append (ev)
845
846         # Extract the lyrics
847         if not rest:
848             note_lyrics_processed = []
849             note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
850             for l in note_lyrics_elements:
851                 if l.get_number () < 0:
852                     for k in lyrics.keys ():
853                         lyrics[k].append (l.lyric_to_text ())
854                         note_lyrics_processed.append (k)
855                 else:
856                     lyrics[l.number].append(l.lyric_to_text ())
857                     note_lyrics_processed.append (l.number)
858             for lnr in lyrics.keys ():
859                 if not lnr in note_lyrics_processed:
860                     lyrics[lnr].append ("\skip4")
861
862
863         mxl_beams = [b for b in n.get_named_children ('beam')
864                      if (b.get_type () in ('begin', 'end')
865                          and b.is_primary ())] 
866         if mxl_beams:
867             beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
868             if beam_ev:
869                 ev_chord.append (beam_ev)
870             
871         if tuplet_event:
872             mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
873             frac = (1,1)
874             if mod:
875                 frac = mod.get_fraction ()
876                 
877             tuplet_events.append ((ev_chord, tuplet_event, frac))
878
879     ## force trailing mm rests to be written out.   
880     voice_builder.add_music (musicexp.EventChord (), Rational (0))
881     
882     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
883
884     seq_music = musicexp.SequentialMusic ()
885
886     if 'drummode' in modes_found.keys ():
887         ## \key <pitch> barfs in drummode.
888         ly_voice = [e for e in ly_voice
889                     if not isinstance(e, musicexp.KeySignatureChange)]
890     
891     seq_music.elements = ly_voice
892     lyrics_dict = {}
893     for k in lyrics.keys ():
894         lyrics_dict[k] = musicexp.Lyrics ()
895         lyrics_dict[k].lyrics_syllables = lyrics[k]
896     
897     
898     if len (modes_found) > 1:
899        error_message ('Too many modes found %s' % modes_found.keys ())
900
901     return_value = seq_music
902     for mode in modes_found.keys ():
903         v = musicexp.ModeChangingMusicWrapper()
904         v.element = return_value
905         v.mode = mode
906         return_value = v
907     
908     return (return_value, lyrics_dict)
909
910
911 def musicxml_id_to_lily (id):
912     digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
913               'Six', 'Seven', 'Eight', 'Nine', 'Ten']
914     
915     for digit in digits:
916         d = digits.index (digit)
917         id = re.sub ('%d' % d, digit, id)
918
919     id = re.sub  ('[^a-zA-Z]', 'X', id)
920     return id
921
922
923 def musicxml_pitch_to_lily (mxl_pitch):
924     p = musicexp.Pitch()
925     p.alteration = mxl_pitch.get_alteration ()
926     p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
927     p.octave = mxl_pitch.get_octave () - 4
928     return p
929
930 def musicxml_restdisplay_to_lily (mxl_rest):
931     p = None
932     step = mxl_rest.get_step ()
933     if step:
934         p = musicexp.Pitch()
935         p.step = (ord (step) - ord ('A') + 7 - 2) % 7
936     octave = mxl_rest.get_octave ()
937     if octave and p:
938         p.octave = octave - 4
939     return p
940
941 def voices_in_part (part):
942     """Return a Name -> Voice dictionary for PART"""
943     part.interpret ()
944     part.extract_voices ()
945     voice_dict = part.get_voices ()
946
947     return voice_dict
948
949 def voices_in_part_in_parts (parts):
950     """return a Part -> Name -> Voice dictionary"""
951     return dict([(p, voices_in_part (p)) for p in parts])
952
953
954 def get_all_voices (parts):
955     all_voices = voices_in_part_in_parts (parts)
956
957     all_ly_voices = {}
958     for p, name_voice in all_voices.items ():
959
960         part_ly_voices = {}
961         for n, v in name_voice.items ():
962             progress ("Converting to LilyPond expressions...")
963             # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
964             part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
965
966         all_ly_voices[p] = part_ly_voices
967         
968     return all_ly_voices
969
970
971 def option_parser ():
972     p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
973                              version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
974                                       +
975 _ ("""This program is free software.  It is covered by the GNU General Public
976 License and you are welcome to change it and/or distribute copies of it
977 under certain conditions.  Invoke as `%s --warranty' for more
978 information.""") % 'lilypond'
979 + """
980 Copyright (c) 2005--2007 by
981     Han-Wen Nienhuys <hanwen@xs4all.nl> and
982     Jan Nieuwenhuizen <janneke@gnu.org>
983 """),
984                              description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
985     p.add_option ('-v', '--verbose',
986                   action="store_true",
987                   dest='verbose',
988                   help=_ ("be verbose"))
989
990     p.add_option ('', '--lxml',
991                   action="store_true",
992                   default=False,
993                   dest="use_lxml",
994                   help=_ ("Use lxml.etree; uses less memory and cpu time."))
995     
996     p.add_option ('-o', '--output',
997                   metavar=_ ("FILE"),
998                   action="store",
999                   default=None,
1000                   type='string',
1001                   dest='output_name',
1002                   help=_ ("set output filename to FILE"))
1003     p.add_option_group ('bugs',
1004                         description=(_ ("Report bugs via")
1005                                      + ''' http://post.gmane.org/post.php'''
1006                                      '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1007     return p
1008
1009 def music_xml_voice_name_to_lily_name (part, name):
1010     str = "Part%sVoice%s" % (part.id, name)
1011     return musicxml_id_to_lily (str) 
1012
1013 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1014     str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1015     return musicxml_id_to_lily (str) 
1016
1017 def print_voice_definitions (printer, part_list, voices):
1018     part_dict={}
1019     for (part, nv_dict) in voices.items():
1020         part_dict[part.id] = (part, nv_dict)
1021
1022     for part in part_list:
1023         (p, nv_dict) = part_dict.get (part.id, (None, {}))
1024         for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1025             k = music_xml_voice_name_to_lily_name (p, name)
1026             printer.dump ('%s = ' % k)
1027             voice.print_ly (printer)
1028             printer.newline()
1029             
1030             for l in lyrics.keys ():
1031                 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1032                 printer.dump ('%s = ' %lname )
1033                 lyrics[l].print_ly (printer)
1034                 printer.newline()
1035
1036             
1037 def uniq_list (l):
1038     return dict ([(elt,1) for elt in l]).keys ()
1039
1040 # format the information about the staff in the form 
1041 #     [staffid,
1042 #         [
1043 #            [voiceid1, [lyricsid11, lyricsid12,...] ...],
1044 #            [voiceid2, [lyricsid21, lyricsid22,...] ...],
1045 #            ...
1046 #         ]
1047 #     ]
1048 # raw_voices is of the form [(voicename, lyrics)*]
1049 def format_staff_info (part, staff_id, raw_voices):
1050     voices = []
1051     for (v, lyrics) in raw_voices:
1052         voice_name = music_xml_voice_name_to_lily_name (part, v)
1053         voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1054                    for l in lyrics.keys ()]
1055         voices.append ([voice_name, voice_lyrics])
1056     return [staff_id, voices]
1057
1058 def update_score_setup (score_structure, part_list, voices):
1059     part_dict = dict ([(p.id, p) for p in voices.keys ()])
1060     final_part_dict = {}
1061
1062     for part_definition in part_list:
1063         part_name = part_definition.id
1064         part = part_dict.get (part_name)
1065         if not part:
1066             error_message ('unknown part in part-list: %s' % part_name)
1067             continue
1068
1069         nv_dict = voices.get (part)
1070         staves = reduce (lambda x,y: x+ y,
1071                 [mxlvoice._staves.keys ()
1072                  for (v, mxlvoice) in nv_dict.values ()],
1073                 [])
1074         staves_info = []
1075         if len (staves) > 1:
1076             staves_info = []
1077             staves = uniq_list (staves)
1078             staves.sort ()
1079             for s in staves:
1080                 thisstaff_raw_voices = [(voice_name, lyrics) 
1081                     for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1082                     if mxlvoice._start_staff == s]
1083                 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1084         else:
1085             thisstaff_raw_voices = [(voice_name, lyrics) 
1086                 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1087             staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1088         score_structure.setPartInformation (part_name, staves_info)
1089
1090 def print_ly_preamble (printer, filename):
1091     printer.dump_version ()
1092     printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1093
1094 def read_musicxml (filename, use_lxml):
1095     if use_lxml:
1096         import lxml.etree
1097         
1098         tree = lxml.etree.parse (filename)
1099         mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1100         return mxl_tree
1101     else:
1102         from xml.dom import minidom, Node
1103         
1104         doc = minidom.parse(filename)
1105         node = doc.documentElement
1106         return musicxml.minidom_demarshal_node (node)
1107
1108     return None
1109
1110
1111 def convert (filename, options):
1112     progress ("Reading MusicXML from %s ..." % filename)
1113     
1114     tree = read_musicxml (filename, options.use_lxml)
1115
1116     score_structure = None
1117     mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1118     if mxl_pl:
1119         score_structure = extract_score_layout (mxl_pl)
1120         part_list = mxl_pl.get_named_children ("score-part")
1121
1122     # score information is contained in the <work>, <identification> or <movement-title> tags
1123     score_information = extract_score_information (tree)
1124     parts = tree.get_typed_children (musicxml.Part)
1125     voices = get_all_voices (parts)
1126     update_score_setup (score_structure, part_list, voices)
1127
1128     if not options.output_name:
1129         options.output_name = os.path.basename (filename) 
1130         options.output_name = os.path.splitext (options.output_name)[0]
1131     elif re.match (".*\.ly", options.output_name):
1132         options.output_name = os.path.splitext (options.output_name)[0]
1133
1134
1135     defs_ly_name = options.output_name + '-defs.ly'
1136     driver_ly_name = options.output_name + '.ly'
1137
1138     printer = musicexp.Output_printer()
1139     progress ("Output to `%s'" % defs_ly_name)
1140     printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1141
1142     print_ly_preamble (printer, filename)
1143     score_information.print_ly (printer)
1144     print_voice_definitions (printer, part_list, voices)
1145     
1146     printer.close ()
1147     
1148     
1149     progress ("Output to `%s'" % driver_ly_name)
1150     printer = musicexp.Output_printer()
1151     printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1152     print_ly_preamble (printer, filename)
1153     printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1154     score_structure.print_ly (printer)
1155     printer.newline ()
1156
1157     return voices
1158
1159 def get_existing_filename_with_extension (filename, ext):
1160     if os.path.exists (filename):
1161         return filename
1162     newfilename = filename + ".xml"
1163     if os.path.exists (newfilename):
1164         return newfilename;
1165     newfilename = filename + "xml"
1166     if os.path.exists (newfilename):
1167         return newfilename;
1168     return ''
1169
1170 def main ():
1171     opt_parser = option_parser()
1172
1173     (options, args) = opt_parser.parse_args ()
1174     if not args:
1175         opt_parser.print_usage()
1176         sys.exit (2)
1177     
1178     # Allow the user to leave out the .xml or xml on the filename
1179     filename = get_existing_filename_with_extension (args[0], "xml")
1180     if filename and os.path.exists (filename):
1181         voices = convert (filename, options)
1182     else:
1183         progress ("Unable to find input file %s" % args[0])
1184
1185 if __name__ == '__main__':
1186     main()