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