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