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