]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
MusicXML: Convert words, assigned to staves => assign to notes in Lilypond
[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
629     if hasattr (words, 'default-y'):
630         if getattr (words, 'default-y') > 0:
631             event.force_direction = 1
632         else:
633             event.force_direction = -1
634
635     if hasattr (words, 'font-weight'):
636         font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
637         if font_weight:
638             event.markup += font_weight
639     if hasattr (words, 'font-size'):
640         font_size = { "xx-small": '\\smaller\\smaller\\smaller', "x-small": '\\smaller\\smaller', "small": '\\smaller', "medium": '', "large": '\\large', "x-large": '\\large\\large', "xx-large": '\\large\\large\\large' }.get (getattr (words, 'font-size'), '')
641         if font_size:
642             event.markup += font_size
643     #TODO: Convert the other attributes defined in %text-formatting in common.mod:
644     # color, font-family
645
646     event.text = text #re.replace (text, "^ *\n? *(.*) *\n? *", "\1")
647     return event
648
649
650 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
651
652 def musicxml_direction_to_lily (n):
653     # TODO: Handle the <staff> element!
654     res = []
655     dirtype_children = []
656     for dt in n.get_typed_children (musicxml.DirType):
657         dirtype_children += dt.get_all_children ()
658
659     for entry in dirtype_children:
660
661         if entry.get_name () == "dynamics":
662             for dynentry in entry.get_all_children ():
663                 ev = musicxml_dynamics_to_lily_event (dynentry)
664                 if ev:
665                     res.append (ev)
666
667         if entry.get_name () == "words":
668             ev = musicxml_words_to_lily_event (entry)
669             if ev:
670                 res.append (ev)
671
672         # octave shifts. pedal marks, hairpins etc. are spanners:
673         if entry.get_name() in direction_spanners:
674             event = musicxml_spanner_to_lily_event (entry)
675             if event:
676                 res.append (event)
677
678
679     return res
680
681 instrument_drumtype_dict = {
682     'Acoustic Snare Drum': 'acousticsnare',
683     'Side Stick': 'sidestick',
684     'Open Triangle': 'opentriangle',
685     'Mute Triangle': 'mutetriangle',
686     'Tambourine': 'tambourine',
687     'Bass Drum': 'bassdrum',
688 }
689
690 def musicxml_note_to_lily_main_event (n):
691     pitch  = None
692     duration = None
693         
694     mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
695     event = None
696     if mxl_pitch:
697         pitch = musicxml_pitch_to_lily (mxl_pitch)
698         event = musicexp.NoteEvent()
699         event.pitch = pitch
700
701         acc = n.get_maybe_exist_named_child ('accidental')
702         if acc:
703             # let's not force accs everywhere. 
704             event.cautionary = acc.editorial
705         
706     elif n.get_maybe_exist_typed_child (musicxml.Rest):
707         # rests can have display-octave and display-step, which are
708         # treated like an ordinary note pitch
709         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
710         event = musicexp.RestEvent()
711         pitch = musicxml_restdisplay_to_lily (rest)
712         event.pitch = pitch
713     elif n.instrument_name:
714         event = musicexp.NoteEvent ()
715         drum_type = instrument_drumtype_dict.get (n.instrument_name)
716         if drum_type:
717             event.drum_type = drum_type
718         else:
719             n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
720             event.drum_type = 'acousticsnare'
721     
722     if not event:
723         n.message ("cannot find suitable event")
724
725     event.duration = musicxml_duration_to_lily (n)
726     return event
727
728
729 ## TODO
730 class NegativeSkip:
731     def __init__ (self, here, dest):
732         self.here = here
733         self.dest = dest
734
735 class LilyPondVoiceBuilder:
736     def __init__ (self):
737         self.elements = []
738         self.pending_dynamics = []
739         self.end_moment = Rational (0)
740         self.begin_moment = Rational (0)
741         self.pending_multibar = Rational (0)
742         self.ignore_skips = False
743
744     def _insert_multibar (self):
745         r = musicexp.MultiMeasureRest ()
746         r.duration = musicexp.Duration()
747         r.duration.duration_log = 0
748         r.duration.factor = self.pending_multibar
749         self.elements.append (r)
750         self.begin_moment = self.end_moment
751         self.end_moment = self.begin_moment + self.pending_multibar
752         self.pending_multibar = Rational (0)
753         
754     def add_multibar_rest (self, duration):
755         self.pending_multibar += duration
756
757     def set_duration (self, duration):
758         self.end_moment = self.begin_moment + duration
759     def current_duration (self):
760         return self.end_moment - self.begin_moment
761         
762     def add_music (self, music, duration):
763         assert isinstance (music, musicexp.Music)
764         if self.pending_multibar > Rational (0):
765             self._insert_multibar ()
766
767         self.elements.append (music)
768         self.begin_moment = self.end_moment
769         self.set_duration (duration)
770         
771         # Insert all pending dynamics right after the note/rest:
772         if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
773             for d in self.pending_dynamics:
774                 music.append (d)
775             self.pending_dynamics = []
776
777     # Insert some music command that does not affect the position in the measure
778     def add_command (self, command):
779         assert isinstance (command, musicexp.Music)
780         if self.pending_multibar > Rational (0):
781             self._insert_multibar ()
782         self.elements.append (command)
783     def add_barline (self, barline):
784         # TODO: Implement merging of default barline and custom bar line
785         self.add_music (barline, Rational (0))
786     def add_partial (self, command):
787         self.ignore_skips = True
788         self.add_command (command)
789
790     def add_dynamics (self, dynamic):
791         # store the dynamic item(s) until we encounter the next note/rest:
792         self.pending_dynamics.append (dynamic)
793
794     def add_bar_check (self, number):
795         b = musicexp.BarLine ()
796         b.bar_number = number
797         self.add_barline (b)
798
799     def jumpto (self, moment):
800         current_end = self.end_moment + self.pending_multibar
801         diff = moment - current_end
802         
803         if diff < Rational (0):
804             error_message ('Negative skip %s' % diff)
805             diff = Rational (0)
806
807         if diff > Rational (0) and not self.ignore_skips:
808             skip = musicexp.SkipEvent()
809             skip.duration.duration_log = 0
810             skip.duration.factor = diff
811
812             evc = musicexp.EventChord ()
813             evc.elements.append (skip)
814             self.add_music (evc, diff)
815
816         if diff > Rational (0) and moment == 0:
817             self.ignore_skips = False
818
819     def last_event_chord (self, starting_at):
820
821         value = None
822
823         # if the position matches, find the last EventChord, do not cross a bar line!
824         at = len( self.elements ) - 1
825         while (at >= 0 and
826                not isinstance (self.elements[at], musicexp.EventChord) and
827                not isinstance (self.elements[at], musicexp.BarLine)):
828             at -= 1
829
830         if (self.elements
831             and at >= 0
832             and isinstance (self.elements[at], musicexp.EventChord)
833             and self.begin_moment == starting_at):
834             value = self.elements[at]
835         else:
836             self.jumpto (starting_at)
837             value = None
838         return value
839         
840     def correct_negative_skip (self, goto):
841         self.end_moment = goto
842         self.begin_moment = goto
843         evc = musicexp.EventChord ()
844         self.elements.append (evc)
845         
846 def musicxml_voice_to_lily_voice (voice):
847     tuplet_events = []
848     modes_found = {}
849     lyrics = {}
850         
851     # TODO: Make sure that the keys in the dict don't get reordered, since
852     #       we need the correct ordering of the lyrics stanzas! By default,
853     #       a dict will reorder its keys
854     for k in voice.get_lyrics_numbers ():
855         lyrics[k] = []
856
857     voice_builder = LilyPondVoiceBuilder()
858
859     for n in voice._elements:
860         if n.get_name () == 'forward':
861             continue
862
863         if isinstance (n, musicxml.Partial) and n.partial > 0:
864             a = musicxml_partial_to_lily (n.partial)
865             if a:
866                 voice_builder.add_partial (a)
867             continue
868
869         if isinstance (n, musicxml.Direction):
870             for a in musicxml_direction_to_lily (n):
871                 if a.wait_for_note ():
872                     voice_builder.add_dynamics (a)
873                 else:
874                     voice_builder.add_command (a)
875             continue
876         
877         if not n.get_maybe_exist_named_child ('chord'):
878             try:
879                 voice_builder.jumpto (n._when)
880             except NegativeSkip, neg:
881                 voice_builder.correct_negative_skip (n._when)
882                 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
883             
884         if isinstance (n, musicxml.Attributes):
885             if n.is_first () and n._measure_position == Rational (0):
886                 try:
887                     number = int (n.get_parent ().number)
888                 except ValueError:
889                     number = 0
890                 if number > 0:
891                     voice_builder.add_bar_check (number)
892
893             for a in musicxml_attributes_to_lily (n):
894                 voice_builder.add_command (a)
895             continue
896
897         if isinstance (n, musicxml.Barline):
898             barlines = musicxml_barline_to_lily (n)
899             for a in barlines:
900                 if isinstance (a, musicexp.BarLine):
901                     voice_builder.add_barline (a)
902                 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
903                     voice_builder.add_command (a)
904             continue
905
906         if not n.__class__.__name__ == 'Note':
907             error_message ('not a Note or Attributes? %s' % n)
908             continue
909
910         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
911         if (rest
912             and rest.is_whole_measure ()):
913
914             voice_builder.add_multibar_rest (n._duration)
915             continue
916
917         if n.is_first () and n._measure_position == Rational (0):
918             try: 
919                 num = int (n.get_parent ().number)
920             except ValueError:
921                 num = 0
922             if num > 0:
923                 voice_builder.add_bar_check (num)
924         
925         main_event = musicxml_note_to_lily_main_event (n)
926
927         if hasattr (main_event, 'drum_type') and main_event.drum_type:
928             modes_found['drummode'] = True
929
930
931         ev_chord = voice_builder.last_event_chord (n._when)
932         if not ev_chord: 
933             ev_chord = musicexp.EventChord()
934             voice_builder.add_music (ev_chord, n._duration)
935
936         grace = n.get_maybe_exist_typed_child (musicxml.Grace)
937         if grace:
938             grace_chord = None
939             if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
940                 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
941             if not grace_chord:
942                 grace_chord = musicexp.EventChord ()
943                 ev_chord.append_grace (grace_chord)
944             if hasattr (grace, 'slash'):
945                 # TODO: use grace_type = "appoggiatura" for slurred grace notes
946                 if grace.slash == "yes":
947                     ev_chord.grace_type = "acciaccatura"
948                 elif grace.slash == "no":
949                     ev_chord.grace_type = "grace"
950             # now that we have inserted the chord into the grace music, insert
951             # everything into that chord instead of the ev_chord
952             ev_chord = grace_chord
953             ev_chord.append (main_event)
954         else:
955             ev_chord.append (main_event)
956             # When a note/chord has grace notes (duration==0), the duration of the
957             # event chord is not yet known, but the event chord was already added
958             # with duration 0. The following correct this when we hit the real note!
959             if voice_builder.current_duration () == 0 and n._duration > 0:
960                 voice_builder.set_duration (n._duration)
961         
962         notations = n.get_maybe_exist_typed_child (musicxml.Notations)
963         tuplet_event = None
964         span_events = []
965         
966         # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
967         # +tied | +slur | +tuplet | glissando | slide | 
968         #    ornaments | technical | articulations | dynamics |
969         #    +fermata | arpeggiate | non-arpeggiate | 
970         #    accidental-mark | other-notation
971         if notations:
972             if notations.get_tuplet():
973                 tuplet_event = notations.get_tuplet()
974                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
975                 frac = (1,1)
976                 if mod:
977                     frac = mod.get_fraction ()
978                 
979                 tuplet_events.append ((ev_chord, tuplet_event, frac))
980
981             slurs = [s for s in notations.get_named_children ('slur')
982                 if s.get_type () in ('start','stop')]
983             if slurs:
984                 if len (slurs) > 1:
985                     error_message ('more than 1 slur?')
986
987                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
988                 ev_chord.append (lily_ev)
989
990             mxl_tie = notations.get_tie ()
991             if mxl_tie and mxl_tie.type == 'start':
992                 ev_chord.append (musicexp.TieEvent ())
993                 
994             fermatas = notations.get_named_children ('fermata')
995             for a in fermatas:
996                 ev = musicxml_fermata_to_lily_event (a)
997                 if ev: 
998                     ev_chord.append (ev)
999
1000             arpeggiate = notations.get_named_children ('arpeggiate')
1001             for a in arpeggiate:
1002                 ev_chord.append (musicexp.ArpeggioEvent ())
1003
1004             glissandos = notations.get_named_children ('glissando')
1005             for a in glissandos:
1006                 ev = musicxml_spanner_to_lily_event (a)
1007                 if ev:
1008                     ev_chord.append (ev)
1009                 
1010             # Articulations can contain the following child elements:
1011             #         accent | strong-accent | staccato | tenuto |
1012             #         detached-legato | staccatissimo | spiccato |
1013             #         scoop | plop | doit | falloff | breath-mark | 
1014             #         caesura | stress | unstress
1015             # Technical can contain the following child elements:
1016             #         up-bow | down-bow | harmonic | open-string |
1017             #         thumb-position | fingering | pluck | double-tongue |
1018             #         triple-tongue | stopped | snap-pizzicato | fret |
1019             #         string | hammer-on | pull-off | bend | tap | heel |
1020             #         toe | fingernails | other-technical
1021             # Ornaments can contain the following child elements:
1022             #         trill-mark | turn | delayed-turn | inverted-turn |
1023             #         shake | wavy-line | mordent | inverted-mordent | 
1024             #         schleifer | tremolo | other-ornament, accidental-mark
1025             ornaments = notations.get_named_children ('ornaments')
1026             for a in ornaments:
1027                 for ch in a.get_named_children ('tremolo'):
1028                     ev = musicxml_tremolo_to_lily_event (ch)
1029                     if ev: 
1030                         ev_chord.append (ev)
1031
1032             ornaments += notations.get_named_children ('articulations')
1033             ornaments += notations.get_named_children ('technical')
1034
1035             for a in ornaments:
1036                 for ch in a.get_all_children ():
1037                     ev = musicxml_articulation_to_lily_event (ch)
1038                     if ev: 
1039                         ev_chord.append (ev)
1040
1041             dynamics = notations.get_named_children ('dynamics')
1042             for a in dynamics:
1043                 for ch in a.get_all_children ():
1044                     ev = musicxml_dynamics_to_lily_event (ch)
1045                     if ev:
1046                         ev_chord.append (ev)
1047
1048         # Extract the lyrics
1049         if not rest:
1050             note_lyrics_processed = []
1051             note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1052             for l in note_lyrics_elements:
1053                 if l.get_number () < 0:
1054                     for k in lyrics.keys ():
1055                         lyrics[k].append (l.lyric_to_text ())
1056                         note_lyrics_processed.append (k)
1057                 else:
1058                     lyrics[l.number].append(l.lyric_to_text ())
1059                     note_lyrics_processed.append (l.number)
1060             for lnr in lyrics.keys ():
1061                 if not lnr in note_lyrics_processed:
1062                     lyrics[lnr].append ("\skip4")
1063
1064
1065         mxl_beams = [b for b in n.get_named_children ('beam')
1066                      if (b.get_type () in ('begin', 'end')
1067                          and b.is_primary ())] 
1068         if mxl_beams:
1069             beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1070             if beam_ev:
1071                 ev_chord.append (beam_ev)
1072             
1073         if tuplet_event:
1074             mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1075             frac = (1,1)
1076             if mod:
1077                 frac = mod.get_fraction ()
1078                 
1079             tuplet_events.append ((ev_chord, tuplet_event, frac))
1080
1081     ## force trailing mm rests to be written out.   
1082     voice_builder.add_music (musicexp.EventChord (), Rational (0))
1083     
1084     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1085     ly_voice = group_repeats (ly_voice)
1086
1087     seq_music = musicexp.SequentialMusic ()
1088
1089     if 'drummode' in modes_found.keys ():
1090         ## \key <pitch> barfs in drummode.
1091         ly_voice = [e for e in ly_voice
1092                     if not isinstance(e, musicexp.KeySignatureChange)]
1093     
1094     seq_music.elements = ly_voice
1095     lyrics_dict = {}
1096     for k in lyrics.keys ():
1097         lyrics_dict[k] = musicexp.Lyrics ()
1098         lyrics_dict[k].lyrics_syllables = lyrics[k]
1099     
1100     
1101     if len (modes_found) > 1:
1102        error_message ('Too many modes found %s' % modes_found.keys ())
1103
1104     return_value = seq_music
1105     for mode in modes_found.keys ():
1106         v = musicexp.ModeChangingMusicWrapper()
1107         v.element = return_value
1108         v.mode = mode
1109         return_value = v
1110     
1111     return (return_value, lyrics_dict)
1112
1113
1114 def musicxml_id_to_lily (id):
1115     digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1116               'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1117     
1118     for digit in digits:
1119         d = digits.index (digit)
1120         id = re.sub ('%d' % d, digit, id)
1121
1122     id = re.sub  ('[^a-zA-Z]', 'X', id)
1123     return id
1124
1125
1126 def musicxml_pitch_to_lily (mxl_pitch):
1127     p = musicexp.Pitch()
1128     p.alteration = mxl_pitch.get_alteration ()
1129     p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1130     p.octave = mxl_pitch.get_octave () - 4
1131     return p
1132
1133 def musicxml_restdisplay_to_lily (mxl_rest):
1134     p = None
1135     step = mxl_rest.get_step ()
1136     if step:
1137         p = musicexp.Pitch()
1138         p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1139     octave = mxl_rest.get_octave ()
1140     if octave and p:
1141         p.octave = octave - 4
1142     return p
1143
1144 def voices_in_part (part):
1145     """Return a Name -> Voice dictionary for PART"""
1146     part.interpret ()
1147     part.extract_voices ()
1148     voice_dict = part.get_voices ()
1149
1150     return voice_dict
1151
1152 def voices_in_part_in_parts (parts):
1153     """return a Part -> Name -> Voice dictionary"""
1154     return dict([(p, voices_in_part (p)) for p in parts])
1155
1156
1157 def get_all_voices (parts):
1158     all_voices = voices_in_part_in_parts (parts)
1159
1160     all_ly_voices = {}
1161     for p, name_voice in all_voices.items ():
1162
1163         part_ly_voices = {}
1164         for n, v in name_voice.items ():
1165             progress ("Converting to LilyPond expressions...")
1166             # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1167             part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
1168
1169         all_ly_voices[p] = part_ly_voices
1170         
1171     return all_ly_voices
1172
1173
1174 def option_parser ():
1175     p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1176                              version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1177                                       +
1178 _ ("""This program is free software.  It is covered by the GNU General Public
1179 License and you are welcome to change it and/or distribute copies of it
1180 under certain conditions.  Invoke as `%s --warranty' for more
1181 information.""") % 'lilypond'
1182 + """
1183 Copyright (c) 2005--2007 by
1184     Han-Wen Nienhuys <hanwen@xs4all.nl> and
1185     Jan Nieuwenhuizen <janneke@gnu.org>
1186 """),
1187                              description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1188     p.add_option ('-v', '--verbose',
1189                   action="store_true",
1190                   dest='verbose',
1191                   help=_ ("be verbose"))
1192
1193     p.add_option ('', '--lxml',
1194                   action="store_true",
1195                   default=False,
1196                   dest="use_lxml",
1197                   help=_ ("Use lxml.etree; uses less memory and cpu time."))
1198     
1199     p.add_option ('-o', '--output',
1200                   metavar=_ ("FILE"),
1201                   action="store",
1202                   default=None,
1203                   type='string',
1204                   dest='output_name',
1205                   help=_ ("set output filename to FILE"))
1206     p.add_option_group ('bugs',
1207                         description=(_ ("Report bugs via")
1208                                      + ''' http://post.gmane.org/post.php'''
1209                                      '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1210     return p
1211
1212 def music_xml_voice_name_to_lily_name (part, name):
1213     str = "Part%sVoice%s" % (part.id, name)
1214     return musicxml_id_to_lily (str) 
1215
1216 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1217     str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1218     return musicxml_id_to_lily (str) 
1219
1220 def print_voice_definitions (printer, part_list, voices):
1221     part_dict={}
1222     for (part, nv_dict) in voices.items():
1223         part_dict[part.id] = (part, nv_dict)
1224
1225     for part in part_list:
1226         (p, nv_dict) = part_dict.get (part.id, (None, {}))
1227         for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1228             k = music_xml_voice_name_to_lily_name (p, name)
1229             printer.dump ('%s = ' % k)
1230             voice.print_ly (printer)
1231             printer.newline()
1232             
1233             for l in lyrics.keys ():
1234                 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1235                 printer.dump ('%s = ' %lname )
1236                 lyrics[l].print_ly (printer)
1237                 printer.newline()
1238
1239             
1240 def uniq_list (l):
1241     return dict ([(elt,1) for elt in l]).keys ()
1242
1243 # format the information about the staff in the form 
1244 #     [staffid,
1245 #         [
1246 #            [voiceid1, [lyricsid11, lyricsid12,...] ...],
1247 #            [voiceid2, [lyricsid21, lyricsid22,...] ...],
1248 #            ...
1249 #         ]
1250 #     ]
1251 # raw_voices is of the form [(voicename, lyrics)*]
1252 def format_staff_info (part, staff_id, raw_voices):
1253     voices = []
1254     for (v, lyrics) in raw_voices:
1255         voice_name = music_xml_voice_name_to_lily_name (part, v)
1256         voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1257                    for l in lyrics.keys ()]
1258         voices.append ([voice_name, voice_lyrics])
1259     return [staff_id, voices]
1260
1261 def update_score_setup (score_structure, part_list, voices):
1262     part_dict = dict ([(p.id, p) for p in voices.keys ()])
1263     final_part_dict = {}
1264
1265     for part_definition in part_list:
1266         part_name = part_definition.id
1267         part = part_dict.get (part_name)
1268         if not part:
1269             error_message ('unknown part in part-list: %s' % part_name)
1270             continue
1271
1272         nv_dict = voices.get (part)
1273         staves = reduce (lambda x,y: x+ y,
1274                 [mxlvoice._staves.keys ()
1275                  for (v, mxlvoice) in nv_dict.values ()],
1276                 [])
1277         staves_info = []
1278         if len (staves) > 1:
1279             staves_info = []
1280             staves = uniq_list (staves)
1281             staves.sort ()
1282             for s in staves:
1283                 thisstaff_raw_voices = [(voice_name, lyrics) 
1284                     for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1285                     if mxlvoice._start_staff == s]
1286                 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1287         else:
1288             thisstaff_raw_voices = [(voice_name, lyrics) 
1289                 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1290             staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1291         score_structure.setPartInformation (part_name, staves_info)
1292
1293 def print_ly_preamble (printer, filename):
1294     printer.dump_version ()
1295     printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1296
1297 def read_musicxml (filename, use_lxml):
1298     if use_lxml:
1299         import lxml.etree
1300         
1301         tree = lxml.etree.parse (filename)
1302         mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1303         return mxl_tree
1304     else:
1305         from xml.dom import minidom, Node
1306         
1307         doc = minidom.parse(filename)
1308         node = doc.documentElement
1309         return musicxml.minidom_demarshal_node (node)
1310
1311     return None
1312
1313
1314 def convert (filename, options):
1315     progress ("Reading MusicXML from %s ..." % filename)
1316     
1317     tree = read_musicxml (filename, options.use_lxml)
1318
1319     score_structure = None
1320     mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1321     if mxl_pl:
1322         score_structure = extract_score_layout (mxl_pl)
1323         part_list = mxl_pl.get_named_children ("score-part")
1324
1325     # score information is contained in the <work>, <identification> or <movement-title> tags
1326     score_information = extract_score_information (tree)
1327     parts = tree.get_typed_children (musicxml.Part)
1328     voices = get_all_voices (parts)
1329     update_score_setup (score_structure, part_list, voices)
1330
1331     if not options.output_name:
1332         options.output_name = os.path.basename (filename) 
1333         options.output_name = os.path.splitext (options.output_name)[0]
1334     elif re.match (".*\.ly", options.output_name):
1335         options.output_name = os.path.splitext (options.output_name)[0]
1336
1337
1338     defs_ly_name = options.output_name + '-defs.ly'
1339     driver_ly_name = options.output_name + '.ly'
1340
1341     printer = musicexp.Output_printer()
1342     progress ("Output to `%s'" % defs_ly_name)
1343     printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1344
1345     print_ly_preamble (printer, filename)
1346     score_information.print_ly (printer)
1347     print_voice_definitions (printer, part_list, voices)
1348     
1349     printer.close ()
1350     
1351     
1352     progress ("Output to `%s'" % driver_ly_name)
1353     printer = musicexp.Output_printer()
1354     printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1355     print_ly_preamble (printer, filename)
1356     printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1357     score_structure.print_ly (printer)
1358     printer.newline ()
1359
1360     return voices
1361
1362 def get_existing_filename_with_extension (filename, ext):
1363     if os.path.exists (filename):
1364         return filename
1365     newfilename = filename + ".xml"
1366     if os.path.exists (newfilename):
1367         return newfilename;
1368     newfilename = filename + "xml"
1369     if os.path.exists (newfilename):
1370         return newfilename;
1371     return ''
1372
1373 def main ():
1374     opt_parser = option_parser()
1375
1376     (options, args) = opt_parser.parse_args ()
1377     if not args:
1378         opt_parser.print_usage()
1379         sys.exit (2)
1380     
1381     # Allow the user to leave out the .xml or xml on the filename
1382     filename = get_existing_filename_with_extension (args[0], "xml")
1383     if filename and os.path.exists (filename):
1384         voices = convert (filename, options)
1385     else:
1386         progress ("Unable to find input file %s" % args[0])
1387
1388 if __name__ == '__main__':
1389     main()