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