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