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