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