]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
MusicXML: Fix problem with lyrics on notes with grace notes
[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 import codecs
9 from gettext import gettext as _
10
11 """
12 @relocate-preamble@
13 """
14
15 import lilylib as ly
16
17 import musicxml
18 import musicexp
19
20 from rational import Rational
21
22
23 def progress (str):
24     sys.stderr.write (str + '\n')
25     sys.stderr.flush ()
26
27 def error_message (str):
28     sys.stderr.write (str + '\n')
29     sys.stderr.flush ()
30
31 # score information is contained in the <work>, <identification> or <movement-title> tags
32 # extract those into a hash, indexed by proper lilypond header attributes
33 def extract_score_information (tree):
34     header = musicexp.Header ()
35     def set_if_exists (field, value):
36         if value:
37             header.set_field (field, musicxml.escape_ly_output_string (value))
38
39     work = tree.get_maybe_exist_named_child ('work')
40     if work:
41         set_if_exists ('title', work.get_work_title ())
42         set_if_exists ('worknumber', work.get_work_number ())
43         set_if_exists ('opus', work.get_opus ())
44     else:
45         movement_title = tree.get_maybe_exist_named_child ('movement-title')
46         if movement_title:
47             set_if_exists ('title', movement_title.get_text ())
48     
49     identifications = tree.get_named_children ('identification')
50     for ids in identifications:
51         set_if_exists ('copyright', ids.get_rights ())
52         set_if_exists ('composer', ids.get_composer ())
53         set_if_exists ('arranger', ids.get_arranger ())
54         set_if_exists ('editor', ids.get_editor ())
55         set_if_exists ('poet', ids.get_poet ())
56             
57         set_if_exists ('tagline', ids.get_encoding_software ())
58         set_if_exists ('encodingsoftware', ids.get_encoding_software ())
59         set_if_exists ('encodingdate', ids.get_encoding_date ())
60         set_if_exists ('encoder', ids.get_encoding_person ())
61         set_if_exists ('encodingdescription', ids.get_encoding_description ())
62
63     return header
64
65
66 def extract_score_layout (part_list):
67     layout = musicexp.StaffGroup (None)
68     currentgroups_dict = {}
69     currentgroups = []
70     if not part_list:
71         return layout
72
73     def insert_into_layout (object):
74             if len (currentgroups) > 0:
75                 group_to_insert = currentgroups_dict.get (currentgroups [-1], layout)
76             else:
77                 group_to_insert = layout
78             group_to_insert.appendStaff (object)
79             return group_to_insert
80
81     def read_score_part (el):
82         if not isinstance (el, musicxml.Score_part):
83             return
84         staff = musicexp.Staff ()
85         staff.id = el.id
86         partname = el.get_maybe_exist_named_child ('part-name')
87         # Finale gives unnamed parts the name "MusicXML Part" automatically!
88         if partname and partname.get_text() != "MusicXML Part":
89             staff.instrument_name = partname.get_text ()
90         if el.get_maybe_exist_named_child ('part-abbreviation'):
91             staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
92         # TODO: Read in the MIDI device / instrument
93         return staff
94
95
96     parts_groups = part_list.get_all_children ()
97     # the start/end group tags are not necessarily ordered correctly, so
98     # we can't go through the children sequentially!
99
100     if len (parts_groups) == 1 and isinstance (parts_group[1], musicxml.Score_part):
101         return read_score_part (parts_group[1])
102
103     for el in parts_groups:
104         if isinstance (el, musicxml.Score_part):
105             staff = read_score_part (el)
106             insert_into_layout (staff)
107         elif isinstance (el, musicxml.Part_group):
108             if el.type == "start":
109                 group = musicexp.StaffGroup ()
110                 staff_group = insert_into_layout (group)
111                 # If we're inserting a nested staffgroup, we need to use InnerStaffGroup
112                 if staff_group != layout:
113                     group.stafftype = "InnerStaffGroup"
114                 if hasattr (el, 'number'):
115                     id = el.number
116                     group.id = id
117                     currentgroups_dict[id] = group
118                     currentgroups.append (id)
119                 if el.get_maybe_exist_named_child ('group-name'):
120                     group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
121                 if el.get_maybe_exist_named_child ('group-abbreviation'):
122                     group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
123                 if el.get_maybe_exist_named_child ('group-symbol'):
124                     group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
125                 if el.get_maybe_exist_named_child ('group-barline'):
126                     group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
127
128             elif el.type == "stop":
129                 # end the part-group, i.e. simply remove it from the lists
130                 if hasattr (el, 'number'):
131                     pid = el.number
132                 elif len (currentgroups) > 0:
133                     pid = el[-1]
134                 if pid:
135                     del currentgroups_dict[pid]
136                     currentgroups.remove (pid)
137     return layout
138
139
140
141 def musicxml_duration_to_lily (mxl_note):
142     d = musicexp.Duration ()
143     # if the note has no Type child, then that method spits out a warning and 
144     # returns 0, i.e. a whole note
145     d.duration_log = mxl_note.get_duration_log ()
146
147     d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
148     # Grace notes by specification have duration 0, so no time modification 
149     # factor is possible. It even messes up the output with *0/1
150     if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
151         d.factor = mxl_note._duration / d.get_length ()
152
153     return d
154
155 def rational_to_lily_duration (rational_len):
156     d = musicexp.Duration ()
157     d.duration_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (rational_len.denominator (), -1)
158     d.factor = Rational (rational_len.numerator ())
159     if d.duration_log < 0:
160         error_message ("Encountered rational duration with denominator %s, "
161                        "unable to convert to lilypond duration" %
162                        rational_len.denominator ())
163         # TODO: Test the above error message
164         return None
165     else:
166         return d
167
168 def musicxml_partial_to_lily (partial_len):
169     if partial_len > 0:
170         p = musicexp.Partial ()
171         p.partial = rational_to_lily_duration (partial_len)
172         return p
173     else:
174         return Null
175
176 # Detect repeats and alternative endings in the chord event list (music_list)
177 # and convert them to the corresponding musicexp objects, containing nested
178 # music
179 def group_repeats (music_list):
180     repeat_replaced = True
181     music_start = 0
182     i = 0
183     # Walk through the list of expressions, looking for repeat structure
184     # (repeat start/end, corresponding endings). If we find one, try to find the
185     # last event of the repeat, replace the whole structure and start over again.
186     # For nested repeats, as soon as we encounter another starting repeat bar,
187     # treat that one first, and start over for the outer repeat.
188     while repeat_replaced and i < 100:
189         i += 1
190         repeat_start = -1  # position of repeat start / end
191         repeat_end = -1 # position of repeat start / end
192         repeat_times = 0
193         ending_start = -1 # position of current ending start
194         endings = [] # list of already finished endings
195         pos = 0
196         last = len (music_list) - 1
197         repeat_replaced = False
198         final_marker = 0
199         while pos < len (music_list) and not repeat_replaced:
200             e = music_list[pos]
201             repeat_finished = False
202             if isinstance (e, RepeatMarker):
203                 if not repeat_times and e.times:
204                     repeat_times = e.times
205                 if e.direction == -1:
206                     if repeat_end >= 0:
207                         repeat_finished = True
208                     else:
209                         repeat_start = pos
210                         repeat_end = -1
211                         ending_start = -1
212                         endings = []
213                 elif e.direction == 1:
214                     if repeat_start < 0:
215                         repeat_start = 0
216                     if repeat_end < 0:
217                         repeat_end = pos
218                     final_marker = pos
219             elif isinstance (e, EndingMarker):
220                 if e.direction == -1:
221                     if repeat_start < 0:
222                         repeat_start = 0
223                     if repeat_end < 0:
224                         repeat_end = pos
225                     ending_start = pos
226                 elif e.direction == 1:
227                     if ending_start < 0:
228                         ending_start = 0
229                     endings.append ([ending_start, pos])
230                     ending_start = -1
231                     final_marker = pos
232             elif not isinstance (e, musicexp.BarLine):
233                 # As soon as we encounter an element when repeat start and end
234                 # is set and we are not inside an alternative ending,
235                 # this whole repeat structure is finished => replace it
236                 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
237                     repeat_finished = True
238
239             # Finish off all repeats without explicit ending bar (e.g. when
240             # we convert only one page of a multi-page score with repeats)
241             if pos == last and repeat_start >= 0:
242                 repeat_finished = True
243                 final_marker = pos
244                 if repeat_end < 0:
245                     repeat_end = pos
246                 if ending_start >= 0:
247                     endings.append ([ending_start, pos])
248                     ending_start = -1
249
250             if repeat_finished:
251                 # We found the whole structure replace it!
252                 r = musicexp.RepeatedMusic ()
253                 if repeat_times <= 0:
254                     repeat_times = 2
255                 r.repeat_count = repeat_times
256                 # don't erase the first element for "implicit" repeats (i.e. no
257                 # starting repeat bars at the very beginning)
258                 start = repeat_start+1
259                 if repeat_start == music_start:
260                     start = music_start
261                 r.set_music (music_list[start:repeat_end])
262                 for (start, end) in endings:
263                     s = musicexp.SequentialMusic ()
264                     s.elements = music_list[start+1:end]
265                     r.add_ending (s)
266                 del music_list[repeat_start:final_marker+1]
267                 music_list.insert (repeat_start, r)
268                 repeat_replaced = True
269             pos += 1
270         # TODO: Implement repeats until the end without explicit ending bar
271     return music_list
272
273
274
275 def group_tuplets (music_list, events):
276
277
278     """Collect Musics from
279     MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
280     """
281
282     
283     indices = []
284
285     j = 0
286     for (ev_chord, tuplet_elt, fraction) in events:
287         while (j < len (music_list)):
288             if music_list[j] == ev_chord:
289                 break
290             j += 1
291         if tuplet_elt.type == 'start':
292             indices.append ((j, None, fraction))
293         elif tuplet_elt.type == 'stop':
294             indices[-1] = (indices[-1][0], j, indices[-1][2])
295
296     new_list = []
297     last = 0
298     for (i1, i2, frac) in indices:
299         if i1 >= i2:
300             continue
301
302         new_list.extend (music_list[last:i1])
303         seq = musicexp.SequentialMusic ()
304         last = i2 + 1
305         seq.elements = music_list[i1:last]
306
307         tsm = musicexp.TimeScaledMusic ()
308         tsm.element = seq
309
310         tsm.numerator = frac[0]
311         tsm.denominator  = frac[1]
312
313         new_list.append (tsm)
314
315     new_list.extend (music_list[last:])
316     return new_list
317
318
319 def musicxml_clef_to_lily (attributes):
320     change = musicexp.ClefChange ()
321     (change.type, change.position, change.octave) = attributes.get_clef_information ()
322     return change
323     
324 def musicxml_time_to_lily (attributes):
325     (beats, type) = attributes.get_time_signature ()
326
327     change = musicexp.TimeSignatureChange()
328     change.fraction = (beats, type)
329     
330     return change
331
332 def musicxml_key_to_lily (attributes):
333     start_pitch  = musicexp.Pitch ()
334     (fifths, mode) = attributes.get_key_signature () 
335     try:
336         (n,a) = {
337             'major' : (0,0),
338             'minor' : (5,0),
339             }[mode]
340         start_pitch.step = n
341         start_pitch.alteration = a
342     except  KeyError:
343         error_message ('unknown mode %s' % mode)
344
345     fifth = musicexp.Pitch()
346     fifth.step = 4
347     if fifths < 0:
348         fifths *= -1
349         fifth.step *= -1
350         fifth.normalize ()
351     
352     for x in range (fifths):
353         start_pitch = start_pitch.transposed (fifth)
354
355     start_pitch.octave = 0
356
357     change = musicexp.KeySignatureChange()
358     change.mode = mode
359     change.tonic = start_pitch
360     return change
361     
362 def musicxml_attributes_to_lily (attrs):
363     elts = []
364     attr_dispatch =  {
365         'clef': musicxml_clef_to_lily,
366         'time': musicxml_time_to_lily,
367         'key': musicxml_key_to_lily
368     }
369     for (k, func) in attr_dispatch.items ():
370         children = attrs.get_named_children (k)
371         if children:
372             elts.append (func (attrs))
373     
374     return elts
375
376 class Marker (musicexp.Music):
377     def __init__ (self):
378         self.direction = 0
379         self.event = None
380     def print_ly (self, printer):
381         sys.stderr.write ("Encountered unprocessed marker %s\n" % self)
382         pass
383     def ly_expression (self):
384         return ""
385 class RepeatMarker (Marker):
386     def __init__ (self):
387         Marker.__init__ (self)
388         self.times = 0
389 class EndingMarker (Marker):
390     pass
391
392 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
393 # and to RepeatMarker and EndingMarker objects for repeat and
394 # alternatives start/stops
395 def musicxml_barline_to_lily (barline):
396     # retval contains all possible markers in the order:
397     # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
398     retval = {}
399     bartype_element = barline.get_maybe_exist_named_child ("bar-style")
400     repeat_element = barline.get_maybe_exist_named_child ("repeat")
401     ending_element = barline.get_maybe_exist_named_child ("ending")
402
403     bartype = None
404     if bartype_element:
405         bartype = bartype_element.get_text ()
406
407     if repeat_element and hasattr (repeat_element, 'direction'):
408         repeat = RepeatMarker ()
409         repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
410
411         if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
412              (repeat_element.direction == "backward" and bartype == "light-heavy") ):
413             bartype = None
414         if hasattr (repeat_element, 'times'):
415             try:
416                 repeat.times = int (repeat_element.times)
417             except ValueError:
418                 repeat.times = 2
419         repeat.event = barline
420         if repeat.direction == -1:
421             retval[3] = repeat
422         else:
423             retval[1] = repeat
424
425     if ending_element and hasattr (ending_element, 'type'):
426         ending = EndingMarker ()
427         ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
428         ending.event = barline
429         if ending.direction == -1:
430             retval[4] = ending
431         else:
432             retval[0] = ending
433
434     if bartype:
435         b = musicexp.BarLine ()
436         b.type = bartype
437         retval[2] = b
438
439     return retval.values ()
440
441 spanner_event_dict = {
442     'slur' : musicexp.SlurEvent,
443     'beam' : musicexp.BeamEvent,
444     'glissando' : musicexp.GlissandoEvent,
445     'pedal' : musicexp.PedalEvent,
446     'wavy-line' : musicexp.TrillSpanEvent,
447     'octave-shift' : musicexp.OctaveShiftEvent,
448     'wedge' : musicexp.HairpinEvent
449 }
450 spanner_type_dict = {
451     'start': -1,
452     'begin': -1,
453     'crescendo': -1,
454     'decreschendo': -1,
455     'diminuendo': -1,
456     'continue': 0,
457     'up': -1,
458     'down': -1,
459     'stop': 1,
460     'end' : 1
461 }
462
463 def musicxml_spanner_to_lily_event (mxl_event):
464     ev = None
465     
466     name = mxl_event.get_name()
467     func = spanner_event_dict.get (name)
468     if func:
469         ev = func()
470     else:
471         error_message ('unknown span event %s' % mxl_event)
472
473
474     type = mxl_event.get_type ()
475     span_direction = spanner_type_dict.get (type)
476     # really check for None, because some types will be translated to 0, which
477     # would otherwise also lead to the unknown span warning
478     if span_direction != None:
479         ev.span_direction = span_direction
480     else:
481         error_message ('unknown span type %s for %s' % (type, name))
482
483     ev.set_span_type (type)
484     ev.line_type = getattr (mxl_event, 'line-type', 'solid')
485
486     # assign the size, which is used for octave-shift, etc.
487     ev.size = mxl_event.get_size ()
488
489     return ev
490
491 def musicxml_direction_to_indicator (direction):
492     return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
493
494 def musicxml_fermata_to_lily_event (mxl_event):
495     ev = musicexp.ArticulationEvent ()
496     ev.type = "fermata"
497     if hasattr (mxl_event, 'type'):
498       dir = musicxml_direction_to_indicator (mxl_event.type)
499       if dir:
500         ev.force_direction = dir
501     return ev
502
503 def musicxml_tremolo_to_lily_event (mxl_event):
504     ev = musicexp.TremoloEvent ()
505     ev.bars = mxl_event.get_text ()
506     return ev
507
508 def musicxml_bend_to_lily_event (mxl_event):
509     ev = musicexp.BendEvent ()
510     ev.alter = mxl_event.bend_alter ()
511     return ev
512
513
514 def musicxml_fingering_event (mxl_event):
515     ev = musicexp.ShortArticulationEvent ()
516     ev.type = mxl_event.get_text ()
517     return ev
518
519 def musicxml_accidental_mark (mxl_event):
520     ev = musicexp.MarkupEvent ()
521     contents = { "sharp": "\\sharp",
522       "natural": "\\natural",
523       "flat": "\\flat",
524       "double-sharp": "\\doublesharp",
525       "sharp-sharp": "\\sharp\\sharp",
526       "flat-flat": "\\flat\\flat",
527       "flat-flat": "\\doubleflat",
528       "natural-sharp": "\\natural\\sharp",
529       "natural-flat": "\\natural\\flat",
530       "quarter-flat": "\\semiflat",
531       "quarter-sharp": "\\semisharp",
532       "three-quarters-flat": "\\sesquiflat",
533       "three-quarters-sharp": "\\sesquisharp",
534     }.get (mxl_event.get_text ())
535     if contents:
536         ev.contents = contents
537         return ev
538     else:
539         return None
540
541 # translate articulations, ornaments and other notations into ArticulationEvents
542 # possible values:
543 #   -) string  (ArticulationEvent with that name)
544 #   -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
545 #   -) (class, name)  (like string, only that a different class than ArticulationEvent is used)
546 # TODO: Some translations are missing!
547 articulations_dict = {
548     "accent": (musicexp.ShortArticulationEvent, ">"),
549     "accidental-mark": musicxml_accidental_mark,
550     "bend": musicxml_bend_to_lily_event,
551     "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
552     #"caesura": "caesura",
553     #"delayed-turn": "?",
554     #"detached-legato": "",
555     #"doit": "",
556     #"double-tongue": "",
557     "down-bow": "downbow",
558     #"falloff": "",
559     "fingering": musicxml_fingering_event,
560     #"fingernails": "",
561     #"fret": "",
562     #"hammer-on": "",
563     "harmonic": "flageolet",
564     #"heel": "",
565     "inverted-mordent": "prall",
566     "inverted-turn": "reverseturn",
567     "mordent": "mordent",
568     #"open-string": "",
569     #"plop": "",
570     #"pluck": "",
571     #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
572     #"pull-off": "",
573     #"schleifer": "?",
574     #"scoop": "",
575     #"shake": "?",
576     #"snap-pizzicato": "",
577     #"spiccato": "",
578     "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
579     "staccato": (musicexp.ShortArticulationEvent, "."),
580     "stopped": (musicexp.ShortArticulationEvent, "+"),
581     #"stress": "",
582     #"string": "",
583     "strong-accent": (musicexp.ShortArticulationEvent, "^"),
584     #"tap": "",
585     "tenuto": (musicexp.ShortArticulationEvent, "-"),
586     #"thumb-position": "",
587     #"toe": "",
588     "turn": "turn",
589     "tremolo": musicxml_tremolo_to_lily_event,
590     "trill-mark": "trill",
591     #"triple-tongue": "",
592     #"unstress": ""
593     "up-bow": "upbow",
594     #"wavy-line": "?",
595 }
596 articulation_spanners = [ "wavy-line" ]
597
598 def musicxml_articulation_to_lily_event (mxl_event):
599     # wavy-line elements are treated as trill spanners, not as articulation ornaments
600     if mxl_event.get_name () in articulation_spanners:
601         return musicxml_spanner_to_lily_event (mxl_event)
602
603     tmp_tp = articulations_dict.get (mxl_event.get_name ())
604     if not tmp_tp:
605         return
606
607     if isinstance (tmp_tp, str):
608         ev = musicexp.ArticulationEvent ()
609         ev.type = tmp_tp
610     elif isinstance (tmp_tp, tuple):
611         ev = tmp_tp[0] ()
612         ev.type = tmp_tp[1]
613     else:
614         ev = tmp_tp (mxl_event)
615
616     # Some articulations use the type attribute, other the placement...
617     dir = None
618     if hasattr (mxl_event, 'type'):
619         dir = musicxml_direction_to_indicator (mxl_event.type)
620     if hasattr (mxl_event, 'placement'):
621         dir = musicxml_direction_to_indicator (mxl_event.placement)
622     return ev
623
624
625 def musicxml_dynamics_to_lily_event (dynentry):
626     dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
627         "f", "ff", "fff", "ffff", "fffff", "ffffff",
628         "mp", "mf", "sf", "sfp", "sfpp", "fp",
629         "rf", "rfz", "sfz", "sffz", "fz" )
630     if not dynentry.get_name() in dynamics_available:
631         return
632     event = musicexp.DynamicsEvent ()
633     event.type = dynentry.get_name ()
634     return event
635
636 # Convert single-color two-byte strings to numbers 0.0 - 1.0
637 def hexcolorval_to_nr (hex_val):
638     try:
639         v = int (hex_val, 16)
640         if v == 255:
641             v = 256
642         return v / 256.
643     except ValueError:
644         return 0.
645
646 def hex_to_color (hex_val):
647     res = re.match (r'#([0-9a-f][0-9a-f]|)([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$', hex_val, re.IGNORECASE)
648     if res:
649         return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
650     else:
651         return None
652
653 def musicxml_words_to_lily_event (words):
654     event = musicexp.TextEvent ()
655     text = words.get_text ()
656     text = re.sub ('^ *\n? *', '', text)
657     text = re.sub (' *\n? *$', '', text)
658     event.text = text
659
660     if hasattr (words, 'default-y'):
661         offset = getattr (words, 'default-y')
662         try:
663             off = string.atoi (offset)
664             if off > 0:
665                 event.force_direction = 1
666             else:
667                 event.force_direction = -1
668         except ValueError:
669             event.force_direction = 0
670
671     if hasattr (words, 'font-weight'):
672         font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
673         if font_weight:
674             event.markup += font_weight
675
676     if hasattr (words, 'font-size'):
677         size = getattr (words, 'font-size')
678         font_size = {
679             "xx-small": '\\teeny',
680             "x-small": '\\tiny',
681             "small": '\\small',
682             "medium": '',
683             "large": '\\large',
684             "x-large": '\\huge',
685             "xx-large": '\\bigger\\huge'
686         }.get (size, '')
687         if font_size:
688             event.markup += font_size
689
690     if hasattr (words, 'color'):
691         color = getattr (words, 'color')
692         rgb = hex_to_color (color)
693         if rgb:
694             event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
695
696     if hasattr (words, 'font-style'):
697         font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
698         if font_style:
699             event.markup += font_style
700
701     # TODO: How should I best convert the font-family attribute?
702
703     # TODO: How can I represent the underline, overline and line-through
704     #       attributes in Lilypond? Values of these attributes indicate
705     #       the number of lines
706
707     return event
708
709
710 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
711
712 def musicxml_direction_to_lily (n):
713     # TODO: Handle the <staff> element!
714     res = []
715     dirtype_children = []
716     for dt in n.get_typed_children (musicxml.DirType):
717         dirtype_children += dt.get_all_children ()
718
719     for entry in dirtype_children:
720
721         if entry.get_name () == "dynamics":
722             for dynentry in entry.get_all_children ():
723                 ev = musicxml_dynamics_to_lily_event (dynentry)
724                 if ev:
725                     res.append (ev)
726
727         if entry.get_name () == "words":
728             ev = musicxml_words_to_lily_event (entry)
729             if ev:
730                 res.append (ev)
731
732         # octave shifts. pedal marks, hairpins etc. are spanners:
733         if entry.get_name() in direction_spanners:
734             event = musicxml_spanner_to_lily_event (entry)
735             if event:
736                 res.append (event)
737
738
739     return res
740
741 def musicxml_frame_to_lily_event (frame):
742     ev = musicexp.FretEvent ()
743     ev.strings = frame.get_strings ()
744     ev.frets = frame.get_frets ()
745     #offset = frame.get_first_fret () - 1
746     barre = []
747     for fn in frame.get_named_children ('frame-note'):
748         fret = fn.get_fret ()
749         if fret <= 0:
750             fret = "o"
751         el = [ fn.get_string (), fret ]
752         fingering = fn.get_fingering ()
753         if fingering >= 0:
754             el.append (fingering)
755         ev.elements.append (el)
756         b = fn.get_barre ()
757         if b == 'start':
758             barre[0] = el[0] # start string
759             barre[2] = el[1] # fret
760         elif b == 'stop':
761             barre[1] = el[0] # end string
762     if barre:
763         ev.barre = barre
764     return ev
765
766 def musicxml_harmony_to_lily (n):
767     res = []
768     for f in n.get_named_children ('frame'):
769         ev = musicxml_frame_to_lily_event (f)
770         if ev:
771             res.append (ev)
772
773     return res
774
775 instrument_drumtype_dict = {
776     'Acoustic Snare Drum': 'acousticsnare',
777     'Side Stick': 'sidestick',
778     'Open Triangle': 'opentriangle',
779     'Mute Triangle': 'mutetriangle',
780     'Tambourine': 'tambourine',
781     'Bass Drum': 'bassdrum',
782 }
783
784 def musicxml_note_to_lily_main_event (n):
785     pitch  = None
786     duration = None
787         
788     mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
789     event = None
790     if mxl_pitch:
791         pitch = musicxml_pitch_to_lily (mxl_pitch)
792         event = musicexp.NoteEvent()
793         event.pitch = pitch
794
795         acc = n.get_maybe_exist_named_child ('accidental')
796         if acc:
797             # let's not force accs everywhere. 
798             event.cautionary = acc.editorial
799         
800     elif n.get_maybe_exist_typed_child (musicxml.Rest):
801         # rests can have display-octave and display-step, which are
802         # treated like an ordinary note pitch
803         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
804         event = musicexp.RestEvent()
805         pitch = musicxml_restdisplay_to_lily (rest)
806         event.pitch = pitch
807     elif n.instrument_name:
808         event = musicexp.NoteEvent ()
809         drum_type = instrument_drumtype_dict.get (n.instrument_name)
810         if drum_type:
811             event.drum_type = drum_type
812         else:
813             n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
814             event.drum_type = 'acousticsnare'
815     
816     if not event:
817         n.message ("cannot find suitable event")
818
819     event.duration = musicxml_duration_to_lily (n)
820     return event
821
822
823 ## TODO
824 class NegativeSkip:
825     def __init__ (self, here, dest):
826         self.here = here
827         self.dest = dest
828
829 class LilyPondVoiceBuilder:
830     def __init__ (self):
831         self.elements = []
832         self.pending_dynamics = []
833         self.end_moment = Rational (0)
834         self.begin_moment = Rational (0)
835         self.pending_multibar = Rational (0)
836         self.ignore_skips = False
837
838     def _insert_multibar (self):
839         r = musicexp.MultiMeasureRest ()
840         r.duration = musicexp.Duration()
841         r.duration.duration_log = 0
842         r.duration.factor = self.pending_multibar
843         self.elements.append (r)
844         self.begin_moment = self.end_moment
845         self.end_moment = self.begin_moment + self.pending_multibar
846         self.pending_multibar = Rational (0)
847         
848     def add_multibar_rest (self, duration):
849         self.pending_multibar += duration
850
851     def set_duration (self, duration):
852         self.end_moment = self.begin_moment + duration
853     def current_duration (self):
854         return self.end_moment - self.begin_moment
855         
856     def add_music (self, music, duration):
857         assert isinstance (music, musicexp.Music)
858         if self.pending_multibar > Rational (0):
859             self._insert_multibar ()
860
861         self.elements.append (music)
862         self.begin_moment = self.end_moment
863         self.set_duration (duration)
864         
865         # Insert all pending dynamics right after the note/rest:
866         if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
867             for d in self.pending_dynamics:
868                 music.append (d)
869             self.pending_dynamics = []
870
871     # Insert some music command that does not affect the position in the measure
872     def add_command (self, command):
873         assert isinstance (command, musicexp.Music)
874         if self.pending_multibar > Rational (0):
875             self._insert_multibar ()
876         self.elements.append (command)
877     def add_barline (self, barline):
878         # TODO: Implement merging of default barline and custom bar line
879         self.add_music (barline, Rational (0))
880     def add_partial (self, command):
881         self.ignore_skips = True
882         self.add_command (command)
883
884     def add_dynamics (self, dynamic):
885         # store the dynamic item(s) until we encounter the next note/rest:
886         self.pending_dynamics.append (dynamic)
887
888     def add_bar_check (self, number):
889         b = musicexp.BarLine ()
890         b.bar_number = number
891         self.add_barline (b)
892
893     def jumpto (self, moment):
894         current_end = self.end_moment + self.pending_multibar
895         diff = moment - current_end
896         
897         if diff < Rational (0):
898             error_message ('Negative skip %s' % diff)
899             diff = Rational (0)
900
901         if diff > Rational (0) and not (self.ignore_skips and moment == 0):
902             skip = musicexp.SkipEvent()
903             skip.duration.duration_log = 0
904             skip.duration.factor = diff
905
906             evc = musicexp.EventChord ()
907             evc.elements.append (skip)
908             self.add_music (evc, diff)
909
910         if diff > Rational (0) and moment == 0:
911             self.ignore_skips = False
912
913     def last_event_chord (self, starting_at):
914
915         value = None
916
917         # if the position matches, find the last EventChord, do not cross a bar line!
918         at = len( self.elements ) - 1
919         while (at >= 0 and
920                not isinstance (self.elements[at], musicexp.EventChord) and
921                not isinstance (self.elements[at], musicexp.BarLine)):
922             at -= 1
923
924         if (self.elements
925             and at >= 0
926             and isinstance (self.elements[at], musicexp.EventChord)
927             and self.begin_moment == starting_at):
928             value = self.elements[at]
929         else:
930             self.jumpto (starting_at)
931             value = None
932         return value
933         
934     def correct_negative_skip (self, goto):
935         self.end_moment = goto
936         self.begin_moment = goto
937         evc = musicexp.EventChord ()
938         self.elements.append (evc)
939         
940 def musicxml_voice_to_lily_voice (voice):
941     tuplet_events = []
942     modes_found = {}
943     lyrics = {}
944
945     # Needed for melismata detection (ignore lyrics on those notes!):
946     inside_slur = False
947     is_tied = False
948     is_chord = False
949     ignore_lyrics = False
950
951     current_staff = None
952
953     # TODO: Make sure that the keys in the dict don't get reordered, since
954     #       we need the correct ordering of the lyrics stanzas! By default,
955     #       a dict will reorder its keys
956     for k in voice.get_lyrics_numbers ():
957         lyrics[k] = []
958
959     voice_builder = LilyPondVoiceBuilder()
960
961     for n in voice._elements:
962         if n.get_name () == 'forward':
963             continue
964         staff = n.get_maybe_exist_named_child ('staff')
965         if staff:
966             staff = staff.get_text ()
967             if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
968                 voice_builder.add_command (musicexp.StaffChange (staff))
969             current_staff = staff
970
971         if isinstance (n, musicxml.Partial) and n.partial > 0:
972             a = musicxml_partial_to_lily (n.partial)
973             if a:
974                 voice_builder.add_partial (a)
975             continue
976
977         if isinstance (n, musicxml.Direction):
978             for a in musicxml_direction_to_lily (n):
979                 if a.wait_for_note ():
980                     voice_builder.add_dynamics (a)
981                 else:
982                     voice_builder.add_command (a)
983             continue
984
985         if isinstance (n, musicxml.Harmony):
986             for a in musicxml_harmony_to_lily (n):
987                 if a.wait_for_note ():
988                     voice_builder.add_dynamics (a)
989                 else:
990                     voice_builder.add_command (a)
991             continue
992
993         is_chord = n.get_maybe_exist_named_child ('chord')
994         if not is_chord:
995             try:
996                 voice_builder.jumpto (n._when)
997             except NegativeSkip, neg:
998                 voice_builder.correct_negative_skip (n._when)
999                 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
1000             
1001         if isinstance (n, musicxml.Attributes):
1002             if n.is_first () and n._measure_position == Rational (0):
1003                 try:
1004                     number = int (n.get_parent ().number)
1005                 except ValueError:
1006                     number = 0
1007                 if number > 0:
1008                     voice_builder.add_bar_check (number)
1009
1010             for a in musicxml_attributes_to_lily (n):
1011                 voice_builder.add_command (a)
1012             continue
1013
1014         if isinstance (n, musicxml.Barline):
1015             barlines = musicxml_barline_to_lily (n)
1016             for a in barlines:
1017                 if isinstance (a, musicexp.BarLine):
1018                     voice_builder.add_barline (a)
1019                 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
1020                     voice_builder.add_command (a)
1021             continue
1022
1023         if not n.__class__.__name__ == 'Note':
1024             error_message ('not a Note or Attributes? %s' % n)
1025             continue
1026
1027         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1028         if (rest
1029             and rest.is_whole_measure ()):
1030
1031             voice_builder.add_multibar_rest (n._duration)
1032             continue
1033
1034         if n.is_first () and n._measure_position == Rational (0):
1035             try: 
1036                 num = int (n.get_parent ().number)
1037             except ValueError:
1038                 num = 0
1039             if num > 0:
1040                 voice_builder.add_bar_check (num)
1041
1042         main_event = musicxml_note_to_lily_main_event (n)
1043         ignore_lyrics = inside_slur or is_tied or is_chord
1044
1045         if hasattr (main_event, 'drum_type') and main_event.drum_type:
1046             modes_found['drummode'] = True
1047
1048
1049         ev_chord = voice_builder.last_event_chord (n._when)
1050         if not ev_chord: 
1051             ev_chord = musicexp.EventChord()
1052             voice_builder.add_music (ev_chord, n._duration)
1053
1054         grace = n.get_maybe_exist_typed_child (musicxml.Grace)
1055         if grace:
1056             grace_chord = None
1057             if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
1058                 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
1059             if not grace_chord:
1060                 grace_chord = musicexp.EventChord ()
1061                 ev_chord.append_grace (grace_chord)
1062             if hasattr (grace, 'slash'):
1063                 # TODO: use grace_type = "appoggiatura" for slurred grace notes
1064                 if grace.slash == "yes":
1065                     ev_chord.grace_type = "acciaccatura"
1066                 elif grace.slash == "no":
1067                     ev_chord.grace_type = "grace"
1068             # now that we have inserted the chord into the grace music, insert
1069             # everything into that chord instead of the ev_chord
1070             ev_chord = grace_chord
1071             ev_chord.append (main_event)
1072             ignore_lyrics = True
1073         else:
1074             ev_chord.append (main_event)
1075             # When a note/chord has grace notes (duration==0), the duration of the
1076             # event chord is not yet known, but the event chord was already added
1077             # with duration 0. The following correct this when we hit the real note!
1078             if voice_builder.current_duration () == 0 and n._duration > 0:
1079                 voice_builder.set_duration (n._duration)
1080         
1081         notations = n.get_maybe_exist_typed_child (musicxml.Notations)
1082         tuplet_event = None
1083         span_events = []
1084
1085         # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
1086         # +tied | +slur | +tuplet | glissando | slide | 
1087         #    ornaments | technical | articulations | dynamics |
1088         #    +fermata | arpeggiate | non-arpeggiate | 
1089         #    accidental-mark | other-notation
1090         if notations:
1091             if notations.get_tuplet():
1092                 tuplet_event = notations.get_tuplet()
1093                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1094                 frac = (1,1)
1095                 if mod:
1096                     frac = mod.get_fraction ()
1097                 
1098                 tuplet_events.append ((ev_chord, tuplet_event, frac))
1099
1100             slurs = [s for s in notations.get_named_children ('slur')
1101                 if s.get_type () in ('start','stop')]
1102             if slurs:
1103                 if len (slurs) > 1:
1104                     error_message ('more than 1 slur?')
1105                 # record the slur status for the next note in the loop
1106                 if not grace:
1107                     if slurs[0].get_type () == 'start':
1108                         inside_slur = True
1109                     elif slurs[0].get_type () == 'stop':
1110                         inside_slur = False
1111                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
1112                 ev_chord.append (lily_ev)
1113
1114             if not grace:
1115                 mxl_tie = notations.get_tie ()
1116                 if mxl_tie and mxl_tie.type == 'start':
1117                     ev_chord.append (musicexp.TieEvent ())
1118                     is_tied = True
1119                 else:
1120                     is_tied = False
1121
1122             fermatas = notations.get_named_children ('fermata')
1123             for a in fermatas:
1124                 ev = musicxml_fermata_to_lily_event (a)
1125                 if ev: 
1126                     ev_chord.append (ev)
1127
1128             arpeggiate = notations.get_named_children ('arpeggiate')
1129             for a in arpeggiate:
1130                 ev_chord.append (musicexp.ArpeggioEvent ())
1131
1132             glissandos = notations.get_named_children ('glissando')
1133             for a in glissandos:
1134                 ev = musicxml_spanner_to_lily_event (a)
1135                 if ev:
1136                     ev_chord.append (ev)
1137                 
1138             # Articulations can contain the following child elements:
1139             #         accent | strong-accent | staccato | tenuto |
1140             #         detached-legato | staccatissimo | spiccato |
1141             #         scoop | plop | doit | falloff | breath-mark | 
1142             #         caesura | stress | unstress
1143             # Technical can contain the following child elements:
1144             #         up-bow | down-bow | harmonic | open-string |
1145             #         thumb-position | fingering | pluck | double-tongue |
1146             #         triple-tongue | stopped | snap-pizzicato | fret |
1147             #         string | hammer-on | pull-off | bend | tap | heel |
1148             #         toe | fingernails | other-technical
1149             # Ornaments can contain the following child elements:
1150             #         trill-mark | turn | delayed-turn | inverted-turn |
1151             #         shake | wavy-line | mordent | inverted-mordent | 
1152             #         schleifer | tremolo | other-ornament, accidental-mark
1153             ornaments = notations.get_named_children ('ornaments')
1154             for a in ornaments:
1155                 for ch in a.get_named_children ('tremolo'):
1156                     ev = musicxml_tremolo_to_lily_event (ch)
1157                     if ev: 
1158                         ev_chord.append (ev)
1159
1160             ornaments += notations.get_named_children ('articulations')
1161             ornaments += notations.get_named_children ('technical')
1162
1163             for a in ornaments:
1164                 for ch in a.get_all_children ():
1165                     ev = musicxml_articulation_to_lily_event (ch)
1166                     if ev: 
1167                         ev_chord.append (ev)
1168
1169             dynamics = notations.get_named_children ('dynamics')
1170             for a in dynamics:
1171                 for ch in a.get_all_children ():
1172                     ev = musicxml_dynamics_to_lily_event (ch)
1173                     if ev:
1174                         ev_chord.append (ev)
1175
1176         # Extract the lyrics
1177         if not rest and not ignore_lyrics:
1178             note_lyrics_processed = []
1179             note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1180             for l in note_lyrics_elements:
1181                 if l.get_number () < 0:
1182                     for k in lyrics.keys ():
1183                         lyrics[k].append (l.lyric_to_text ())
1184                         note_lyrics_processed.append (k)
1185                 else:
1186                     lyrics[l.number].append(l.lyric_to_text ())
1187                     note_lyrics_processed.append (l.number)
1188             for lnr in lyrics.keys ():
1189                 if not lnr in note_lyrics_processed:
1190                     lyrics[lnr].append ("\skip4")
1191
1192
1193         mxl_beams = [b for b in n.get_named_children ('beam')
1194                      if (b.get_type () in ('begin', 'end')
1195                          and b.is_primary ())] 
1196         if mxl_beams:
1197             beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1198             if beam_ev:
1199                 ev_chord.append (beam_ev)
1200             
1201         if tuplet_event:
1202             mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1203             frac = (1,1)
1204             if mod:
1205                 frac = mod.get_fraction ()
1206                 
1207             tuplet_events.append ((ev_chord, tuplet_event, frac))
1208
1209     ## force trailing mm rests to be written out.   
1210     voice_builder.add_music (musicexp.EventChord (), Rational (0))
1211     
1212     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1213     ly_voice = group_repeats (ly_voice)
1214
1215     seq_music = musicexp.SequentialMusic ()
1216
1217     if 'drummode' in modes_found.keys ():
1218         ## \key <pitch> barfs in drummode.
1219         ly_voice = [e for e in ly_voice
1220                     if not isinstance(e, musicexp.KeySignatureChange)]
1221     
1222     seq_music.elements = ly_voice
1223     lyrics_dict = {}
1224     for k in lyrics.keys ():
1225         lyrics_dict[k] = musicexp.Lyrics ()
1226         lyrics_dict[k].lyrics_syllables = lyrics[k]
1227     
1228     
1229     if len (modes_found) > 1:
1230        error_message ('Too many modes found %s' % modes_found.keys ())
1231
1232     return_value = seq_music
1233     for mode in modes_found.keys ():
1234         v = musicexp.ModeChangingMusicWrapper()
1235         v.element = return_value
1236         v.mode = mode
1237         return_value = v
1238     
1239     return (return_value, lyrics_dict)
1240
1241
1242 def musicxml_id_to_lily (id):
1243     digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1244               'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1245     
1246     for digit in digits:
1247         d = digits.index (digit)
1248         id = re.sub ('%d' % d, digit, id)
1249
1250     id = re.sub  ('[^a-zA-Z]', 'X', id)
1251     return id
1252
1253
1254 def musicxml_pitch_to_lily (mxl_pitch):
1255     p = musicexp.Pitch()
1256     p.alteration = mxl_pitch.get_alteration ()
1257     p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1258     p.octave = mxl_pitch.get_octave () - 4
1259     return p
1260
1261 def musicxml_restdisplay_to_lily (mxl_rest):
1262     p = None
1263     step = mxl_rest.get_step ()
1264     if step:
1265         p = musicexp.Pitch()
1266         p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1267     octave = mxl_rest.get_octave ()
1268     if octave and p:
1269         p.octave = octave - 4
1270     return p
1271
1272 def voices_in_part (part):
1273     """Return a Name -> Voice dictionary for PART"""
1274     part.interpret ()
1275     part.extract_voices ()
1276     voice_dict = part.get_voices ()
1277
1278     return voice_dict
1279
1280 def voices_in_part_in_parts (parts):
1281     """return a Part -> Name -> Voice dictionary"""
1282     return dict([(p, voices_in_part (p)) for p in parts])
1283
1284
1285 def get_all_voices (parts):
1286     all_voices = voices_in_part_in_parts (parts)
1287
1288     all_ly_voices = {}
1289     for p, name_voice in all_voices.items ():
1290
1291         part_ly_voices = {}
1292         for n, v in name_voice.items ():
1293             progress ("Converting to LilyPond expressions...")
1294             # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1295             part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
1296
1297         all_ly_voices[p] = part_ly_voices
1298         
1299     return all_ly_voices
1300
1301
1302 def option_parser ():
1303     p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1304                              version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1305                                       +
1306 _ ("""This program is free software.  It is covered by the GNU General Public
1307 License and you are welcome to change it and/or distribute copies of it
1308 under certain conditions.  Invoke as `%s --warranty' for more
1309 information.""") % 'lilypond'
1310 + """
1311 Copyright (c) 2005--2007 by
1312     Han-Wen Nienhuys <hanwen@xs4all.nl> and
1313     Jan Nieuwenhuizen <janneke@gnu.org>
1314 """),
1315                              description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1316     p.add_option ('-v', '--verbose',
1317                   action="store_true",
1318                   dest='verbose',
1319                   help=_ ("be verbose"))
1320
1321     p.add_option ('', '--lxml',
1322                   action="store_true",
1323                   default=False,
1324                   dest="use_lxml",
1325                   help=_ ("Use lxml.etree; uses less memory and cpu time."))
1326     
1327     p.add_option ('-o', '--output',
1328                   metavar=_ ("FILE"),
1329                   action="store",
1330                   default=None,
1331                   type='string',
1332                   dest='output_name',
1333                   help=_ ("set output filename to FILE"))
1334     p.add_option_group ('bugs',
1335                         description=(_ ("Report bugs via")
1336                                      + ''' http://post.gmane.org/post.php'''
1337                                      '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1338     return p
1339
1340 def music_xml_voice_name_to_lily_name (part, name):
1341     str = "Part%sVoice%s" % (part.id, name)
1342     return musicxml_id_to_lily (str) 
1343
1344 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1345     str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1346     return musicxml_id_to_lily (str) 
1347
1348 def print_voice_definitions (printer, part_list, voices):
1349     part_dict={}
1350     for (part, nv_dict) in voices.items():
1351         part_dict[part.id] = (part, nv_dict)
1352
1353     for part in part_list:
1354         (p, nv_dict) = part_dict.get (part.id, (None, {}))
1355         for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1356             k = music_xml_voice_name_to_lily_name (p, name)
1357             printer.dump ('%s = ' % k)
1358             voice.print_ly (printer)
1359             printer.newline()
1360             
1361             for l in lyrics.keys ():
1362                 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1363                 printer.dump ('%s = ' %lname )
1364                 lyrics[l].print_ly (printer)
1365                 printer.newline()
1366
1367             
1368 def uniq_list (l):
1369     return dict ([(elt,1) for elt in l]).keys ()
1370
1371 # format the information about the staff in the form 
1372 #     [staffid,
1373 #         [
1374 #            [voiceid1, [lyricsid11, lyricsid12,...] ...],
1375 #            [voiceid2, [lyricsid21, lyricsid22,...] ...],
1376 #            ...
1377 #         ]
1378 #     ]
1379 # raw_voices is of the form [(voicename, lyrics)*]
1380 def format_staff_info (part, staff_id, raw_voices):
1381     voices = []
1382     for (v, lyrics) in raw_voices:
1383         voice_name = music_xml_voice_name_to_lily_name (part, v)
1384         voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1385                    for l in lyrics.keys ()]
1386         voices.append ([voice_name, voice_lyrics])
1387     return [staff_id, voices]
1388
1389 def update_score_setup (score_structure, part_list, voices):
1390     part_dict = dict ([(p.id, p) for p in voices.keys ()])
1391     final_part_dict = {}
1392
1393     for part_definition in part_list:
1394         part_name = part_definition.id
1395         part = part_dict.get (part_name)
1396         if not part:
1397             error_message ('unknown part in part-list: %s' % part_name)
1398             continue
1399
1400         nv_dict = voices.get (part)
1401         staves = reduce (lambda x,y: x+ y,
1402                 [mxlvoice._staves.keys ()
1403                  for (v, mxlvoice) in nv_dict.values ()],
1404                 [])
1405         staves_info = []
1406         if len (staves) > 1:
1407             staves_info = []
1408             staves = uniq_list (staves)
1409             staves.sort ()
1410             for s in staves:
1411                 thisstaff_raw_voices = [(voice_name, lyrics) 
1412                     for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1413                     if mxlvoice._start_staff == s]
1414                 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1415         else:
1416             thisstaff_raw_voices = [(voice_name, lyrics) 
1417                 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1418             staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1419         score_structure.setPartInformation (part_name, staves_info)
1420
1421 def print_ly_preamble (printer, filename):
1422     printer.dump_version ()
1423     printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1424
1425 def read_musicxml (filename, use_lxml):
1426     if use_lxml:
1427         import lxml.etree
1428         
1429         tree = lxml.etree.parse (filename)
1430         mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1431         return mxl_tree
1432     else:
1433         from xml.dom import minidom, Node
1434         
1435         doc = minidom.parse(filename)
1436         node = doc.documentElement
1437         return musicxml.minidom_demarshal_node (node)
1438
1439     return None
1440
1441
1442 def convert (filename, options):
1443     progress ("Reading MusicXML from %s ..." % filename)
1444     
1445     tree = read_musicxml (filename, options.use_lxml)
1446
1447     score_structure = None
1448     mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1449     if mxl_pl:
1450         score_structure = extract_score_layout (mxl_pl)
1451         part_list = mxl_pl.get_named_children ("score-part")
1452
1453     # score information is contained in the <work>, <identification> or <movement-title> tags
1454     score_information = extract_score_information (tree)
1455     parts = tree.get_typed_children (musicxml.Part)
1456     voices = get_all_voices (parts)
1457     update_score_setup (score_structure, part_list, voices)
1458
1459     if not options.output_name:
1460         options.output_name = os.path.basename (filename) 
1461         options.output_name = os.path.splitext (options.output_name)[0]
1462     elif re.match (".*\.ly", options.output_name):
1463         options.output_name = os.path.splitext (options.output_name)[0]
1464
1465
1466     defs_ly_name = options.output_name + '-defs.ly'
1467     driver_ly_name = options.output_name + '.ly'
1468
1469     printer = musicexp.Output_printer()
1470     progress ("Output to `%s'" % defs_ly_name)
1471     printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1472
1473     print_ly_preamble (printer, filename)
1474     score_information.print_ly (printer)
1475     print_voice_definitions (printer, part_list, voices)
1476     
1477     printer.close ()
1478     
1479     
1480     progress ("Output to `%s'" % driver_ly_name)
1481     printer = musicexp.Output_printer()
1482     printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1483     print_ly_preamble (printer, filename)
1484     printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1485     score_structure.print_ly (printer)
1486     printer.newline ()
1487
1488     return voices
1489
1490 def get_existing_filename_with_extension (filename, ext):
1491     if os.path.exists (filename):
1492         return filename
1493     newfilename = filename + ".xml"
1494     if os.path.exists (newfilename):
1495         return newfilename;
1496     newfilename = filename + "xml"
1497     if os.path.exists (newfilename):
1498         return newfilename;
1499     return ''
1500
1501 def main ():
1502     opt_parser = option_parser()
1503
1504     (options, args) = opt_parser.parse_args ()
1505     if not args:
1506         opt_parser.print_usage()
1507         sys.exit (2)
1508     
1509     # Allow the user to leave out the .xml or xml on the filename
1510     filename = get_existing_filename_with_extension (args[0], "xml")
1511     if filename and os.path.exists (filename):
1512         voices = convert (filename, options)
1513     else:
1514         progress ("Unable to find input file %s" % args[0])
1515
1516 if __name__ == '__main__':
1517     main()