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