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