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