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