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