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