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