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