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