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