]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
MusicXML: Fix graces to allow beams, chords, etc.
[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
687         grace = n.get_maybe_exist_typed_child (musicxml.Grace)
688         if grace:
689             grace_chord = None
690             if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
691                 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
692             if not grace_chord:
693                 grace_chord = musicexp.EventChord ()
694                 ev_chord.append_grace (grace_chord)
695             if hasattr (grace, 'slash'):
696                 # TODO: use grace_type = "appoggiatura" for slurred grace notes
697                 if grace.slash == "yes":
698                     ev_chord.grace_type = "acciaccatura"
699                 elif grace.slash == "no":
700                     ev_chord.grace_type = "grace"
701             # now that we have inserted the chord into the grace music, insert
702             # everything into that chord instead of the ev_chord
703             ev_chord = grace_chord
704             ev_chord.append (main_event)
705         else:
706             ev_chord.append (main_event)
707             # When a note/chord has grace notes (duration==0), the duration of the
708             # event chord is not yet known, but the event chord was already added
709             # with duration 0. The following correct this when we hit the real note!
710             if voice_builder.current_duration () == 0 and n._duration > 0:
711                 voice_builder.set_duration (n._duration)
712         
713         notations = n.get_maybe_exist_typed_child (musicxml.Notations)
714         tuplet_event = None
715         span_events = []
716         
717         # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
718         # +tied | +slur | +tuplet | glissando | slide | 
719         #    ornaments | technical | articulations | dynamics |
720         #    +fermata | arpeggiate | non-arpeggiate | 
721         #    accidental-mark | other-notation
722         if notations:
723             if notations.get_tuplet():
724                 tuplet_event = notations.get_tuplet()
725                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
726                 frac = (1,1)
727                 if mod:
728                     frac = mod.get_fraction ()
729                 
730                 tuplet_events.append ((ev_chord, tuplet_event, frac))
731
732             slurs = [s for s in notations.get_named_children ('slur')
733                 if s.get_type () in ('start','stop')]
734             if slurs:
735                 if len (slurs) > 1:
736                     error_message ('more than 1 slur?')
737
738                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
739                 ev_chord.append (lily_ev)
740
741             mxl_tie = notations.get_tie ()
742             if mxl_tie and mxl_tie.type == 'start':
743                 ev_chord.append (musicexp.TieEvent ())
744                 
745             fermatas = notations.get_named_children ('fermata')
746             for a in fermatas:
747                 ev = musicxml_fermata_to_lily_event (a)
748                 if ev: 
749                     ev_chord.append (ev)
750
751             arpeggiate = notations.get_named_children ('arpeggiate')
752             for a in arpeggiate:
753                 ev_chord.append (musicexp.ArpeggioEvent ())
754
755             glissandos = notations.get_named_children ('glissando')
756             for a in glissandos:
757                 ev = musicxml_spanner_to_lily_event (a)
758                 if ev:
759                     ev_chord.append (ev)
760                 
761             # Articulations can contain the following child elements:
762             #         accent | strong-accent | staccato | tenuto |
763             #         detached-legato | staccatissimo | spiccato |
764             #         scoop | plop | doit | falloff | breath-mark | 
765             #         caesura | stress | unstress
766             # Technical can contain the following child elements:
767             #         up-bow | down-bow | harmonic | open-string |
768             #         thumb-position | fingering | pluck | double-tongue |
769             #         triple-tongue | stopped | snap-pizzicato | fret |
770             #         string | hammer-on | pull-off | bend | tap | heel |
771             #         toe | fingernails | other-technical
772             # Ornaments can contain the following child elements:
773             #         trill-mark | turn | delayed-turn | inverted-turn |
774             #         shake | wavy-line | mordent | inverted-mordent | 
775             #         schleifer | tremolo | other-ornament, accidental-mark
776             ornaments = notations.get_named_children ('ornaments')
777             for a in ornaments:
778                 for ch in a.get_named_children ('tremolo'):
779                     ev = musicxml_tremolo_to_lily_event (ch)
780                     if ev: 
781                         ev_chord.append (ev)
782
783             ornaments += notations.get_named_children ('articulations')
784             ornaments += notations.get_named_children ('technical')
785
786             for a in ornaments:
787                 for ch in a.get_all_children ():
788                     ev = musicxml_articulation_to_lily_event (ch)
789                     if ev: 
790                         ev_chord.append (ev)
791
792             dynamics = notations.get_named_children ('dynamics')
793             for a in dynamics:
794                 for ch in a.get_all_children ():
795                     ev = musicxml_dynamics_to_lily_event (ch)
796                     if ev:
797                         ev_chord.append (ev)
798
799         # Extract the lyrics
800         if not rest:
801             note_lyrics_processed = []
802             note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
803             for l in note_lyrics_elements:
804                 if l.get_number () < 0:
805                     for k in lyrics.keys ():
806                         lyrics[k].append (l.lyric_to_text ())
807                         note_lyrics_processed.append (k)
808                 else:
809                     lyrics[l.number].append(l.lyric_to_text ())
810                     note_lyrics_processed.append (l.number)
811             for lnr in lyrics.keys ():
812                 if not lnr in note_lyrics_processed:
813                     lyrics[lnr].append ("\skip4")
814
815
816         mxl_beams = [b for b in n.get_named_children ('beam')
817                      if (b.get_type () in ('begin', 'end')
818                          and b.is_primary ())] 
819         if mxl_beams:
820             beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
821             if beam_ev:
822                 ev_chord.append (beam_ev)
823             
824         if tuplet_event:
825             mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
826             frac = (1,1)
827             if mod:
828                 frac = mod.get_fraction ()
829                 
830             tuplet_events.append ((ev_chord, tuplet_event, frac))
831
832     ## force trailing mm rests to be written out.   
833     voice_builder.add_music (musicexp.EventChord (), Rational (0))
834     
835     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
836
837     seq_music = musicexp.SequentialMusic ()
838
839     if 'drummode' in modes_found.keys ():
840         ## \key <pitch> barfs in drummode.
841         ly_voice = [e for e in ly_voice
842                     if not isinstance(e, musicexp.KeySignatureChange)]
843     
844     seq_music.elements = ly_voice
845     lyrics_dict = {}
846     for k in lyrics.keys ():
847         lyrics_dict[k] = musicexp.Lyrics ()
848         lyrics_dict[k].lyrics_syllables = lyrics[k]
849     
850     
851     if len (modes_found) > 1:
852        error_message ('Too many modes found %s' % modes_found.keys ())
853
854     return_value = seq_music
855     for mode in modes_found.keys ():
856         v = musicexp.ModeChangingMusicWrapper()
857         v.element = return_value
858         v.mode = mode
859         return_value = v
860     
861     return (return_value, lyrics_dict)
862
863
864 def musicxml_id_to_lily (id):
865     digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
866               'Six', 'Seven', 'Eight', 'Nine', 'Ten']
867     
868     for digit in digits:
869         d = digits.index (digit)
870         id = re.sub ('%d' % d, digit, id)
871
872     id = re.sub  ('[^a-zA-Z]', 'X', id)
873     return id
874
875
876 def musicxml_pitch_to_lily (mxl_pitch):
877     p = musicexp.Pitch()
878     p.alteration = mxl_pitch.get_alteration ()
879     p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
880     p.octave = mxl_pitch.get_octave () - 4
881     return p
882
883 def musicxml_restdisplay_to_lily (mxl_rest):
884     p = None
885     step = mxl_rest.get_step ()
886     if step:
887         p = musicexp.Pitch()
888         p.step = (ord (step) - ord ('A') + 7 - 2) % 7
889     octave = mxl_rest.get_octave ()
890     if octave and p:
891         p.octave = octave - 4
892     return p
893
894 def voices_in_part (part):
895     """Return a Name -> Voice dictionary for PART"""
896     part.interpret ()
897     part.extract_voices ()
898     voice_dict = part.get_voices ()
899
900     return voice_dict
901
902 def voices_in_part_in_parts (parts):
903     """return a Part -> Name -> Voice dictionary"""
904     return dict([(p, voices_in_part (p)) for p in parts])
905
906
907 def get_all_voices (parts):
908     all_voices = voices_in_part_in_parts (parts)
909
910     all_ly_voices = {}
911     for p, name_voice in all_voices.items ():
912
913         part_ly_voices = {}
914         for n, v in name_voice.items ():
915             progress ("Converting to LilyPond expressions...")
916             # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
917             part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
918
919         all_ly_voices[p] = part_ly_voices
920         
921     return all_ly_voices
922
923
924 def option_parser ():
925     p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
926                              version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
927                                       +
928 _ ("""This program is free software.  It is covered by the GNU General Public
929 License and you are welcome to change it and/or distribute copies of it
930 under certain conditions.  Invoke as `%s --warranty' for more
931 information.""") % 'lilypond'
932 + """
933 Copyright (c) 2005--2007 by
934     Han-Wen Nienhuys <hanwen@xs4all.nl> and
935     Jan Nieuwenhuizen <janneke@gnu.org>
936 """),
937                              description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
938     p.add_option ('-v', '--verbose',
939                   action="store_true",
940                   dest='verbose',
941                   help=_ ("be verbose"))
942
943     p.add_option ('', '--lxml',
944                   action="store_true",
945                   default=False,
946                   dest="use_lxml",
947                   help=_ ("Use lxml.etree; uses less memory and cpu time."))
948     
949     p.add_option ('-o', '--output',
950                   metavar=_ ("FILE"),
951                   action="store",
952                   default=None,
953                   type='string',
954                   dest='output_name',
955                   help=_ ("set output filename to FILE"))
956     p.add_option_group ('bugs',
957                         description=(_ ("Report bugs via")
958                                      + ''' http://post.gmane.org/post.php'''
959                                      '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
960     return p
961
962 def music_xml_voice_name_to_lily_name (part, name):
963     str = "Part%sVoice%s" % (part.id, name)
964     return musicxml_id_to_lily (str) 
965
966 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
967     str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
968     return musicxml_id_to_lily (str) 
969
970 def print_voice_definitions (printer, part_list, voices):
971     part_dict={}
972     for (part, nv_dict) in voices.items():
973         part_dict[part.id] = (part, nv_dict)
974
975     for part in part_list:
976         (p, nv_dict) = part_dict.get (part.id, (None, {}))
977         for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
978             k = music_xml_voice_name_to_lily_name (p, name)
979             printer.dump ('%s = ' % k)
980             voice.print_ly (printer)
981             printer.newline()
982             
983             for l in lyrics.keys ():
984                 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
985                 printer.dump ('%s = ' %lname )
986                 lyrics[l].print_ly (printer)
987                 printer.newline()
988
989             
990 def uniq_list (l):
991     return dict ([(elt,1) for elt in l]).keys ()
992
993 # format the information about the staff in the form 
994 #     [staffid,
995 #         [
996 #            [voiceid1, [lyricsid11, lyricsid12,...] ...],
997 #            [voiceid2, [lyricsid21, lyricsid22,...] ...],
998 #            ...
999 #         ]
1000 #     ]
1001 # raw_voices is of the form [(voicename, lyrics)*]
1002 def format_staff_info (part, staff_id, raw_voices):
1003     voices = []
1004     for (v, lyrics) in raw_voices:
1005         voice_name = music_xml_voice_name_to_lily_name (part, v)
1006         voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1007                    for l in lyrics.keys ()]
1008         voices.append ([voice_name, voice_lyrics])
1009     return [staff_id, voices]
1010
1011 def update_score_setup (score_structure, part_list, voices):
1012     part_dict = dict ([(p.id, p) for p in voices.keys ()])
1013     final_part_dict = {}
1014
1015     for part_definition in part_list:
1016         part_name = part_definition.id
1017         part = part_dict.get (part_name)
1018         if not part:
1019             error_message ('unknown part in part-list: %s' % part_name)
1020             continue
1021
1022         nv_dict = voices.get (part)
1023         staves = reduce (lambda x,y: x+ y,
1024                 [mxlvoice._staves.keys ()
1025                  for (v, mxlvoice) in nv_dict.values ()],
1026                 [])
1027         staves_info = []
1028         if len (staves) > 1:
1029             staves_info = []
1030             staves = uniq_list (staves)
1031             staves.sort ()
1032             for s in staves:
1033                 thisstaff_raw_voices = [(voice_name, lyrics) 
1034                     for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1035                     if mxlvoice._start_staff == s]
1036                 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1037         else:
1038             thisstaff_raw_voices = [(voice_name, lyrics) 
1039                 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1040             staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1041         score_structure.setPartInformation (part_name, staves_info)
1042
1043 def print_ly_preamble (printer, filename):
1044     printer.dump_version ()
1045     printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1046
1047 def read_musicxml (filename, use_lxml):
1048     if use_lxml:
1049         import lxml.etree
1050         
1051         tree = lxml.etree.parse (filename)
1052         mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1053         return mxl_tree
1054     else:
1055         from xml.dom import minidom, Node
1056         
1057         doc = minidom.parse(filename)
1058         node = doc.documentElement
1059         return musicxml.minidom_demarshal_node (node)
1060
1061     return None
1062
1063
1064 def convert (filename, options):
1065     progress ("Reading MusicXML from %s ..." % filename)
1066     
1067     tree = read_musicxml (filename, options.use_lxml)
1068
1069     score_structure = None
1070     mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1071     if mxl_pl:
1072         score_structure = extract_score_layout (mxl_pl)
1073         part_list = mxl_pl.get_named_children ("score-part")
1074
1075     # score information is contained in the <work>, <identification> or <movement-title> tags
1076     score_information = extract_score_information (tree)
1077     parts = tree.get_typed_children (musicxml.Part)
1078     voices = get_all_voices (parts)
1079     update_score_setup (score_structure, part_list, voices)
1080
1081     if not options.output_name:
1082         options.output_name = os.path.basename (filename) 
1083         options.output_name = os.path.splitext (options.output_name)[0]
1084     elif re.match (".*\.ly", options.output_name):
1085         options.output_name = os.path.splitext (options.output_name)[0]
1086
1087
1088     defs_ly_name = options.output_name + '-defs.ly'
1089     driver_ly_name = options.output_name + '.ly'
1090
1091     printer = musicexp.Output_printer()
1092     progress ("Output to `%s'" % defs_ly_name)
1093     printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1094
1095     print_ly_preamble (printer, filename)
1096     score_information.print_ly (printer)
1097     print_voice_definitions (printer, part_list, voices)
1098     
1099     printer.close ()
1100     
1101     
1102     progress ("Output to `%s'" % driver_ly_name)
1103     printer = musicexp.Output_printer()
1104     printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1105     print_ly_preamble (printer, filename)
1106     printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1107     score_structure.print_ly (printer)
1108     printer.newline ()
1109
1110     return voices
1111
1112 def get_existing_filename_with_extension (filename, ext):
1113     if os.path.exists (filename):
1114         return filename
1115     newfilename = filename + ".xml"
1116     if os.path.exists (newfilename):
1117         return newfilename;
1118     newfilename = filename + "xml"
1119     if os.path.exists (newfilename):
1120         return newfilename;
1121     return ''
1122
1123 def main ():
1124     opt_parser = option_parser()
1125
1126     (options, args) = opt_parser.parse_args ()
1127     if not args:
1128         opt_parser.print_usage()
1129         sys.exit (2)
1130     
1131     # Allow the user to leave out the .xml or xml on the filename
1132     filename = get_existing_filename_with_extension (args[0], "xml")
1133     if filename and os.path.exists (filename):
1134         voices = convert (filename, options)
1135     else:
1136         progress ("Unable to find input file %s" % args[0])
1137
1138 if __name__ == '__main__':
1139     main()