9 from gettext import gettext as _
20 from rational import Rational
24 sys.stderr.write (str + '\n')
27 def error_message (str):
28 sys.stderr.write (str + '\n')
31 needed_additional_definitions = []
32 additional_definitions = {
33 "snappizzicato": """#(define-markup-command (snappizzicato layout props) ()
34 (interpret-markup layout props
36 (ly:stencil-translate-axis
38 (make-circle-stencil 0.7 0.1 #f)
40 (list 'draw-line 0.1 0 0.1 0 1)
41 '(-0.1 . 0.1) '(0.1 . 1)
52 def round_to_two_digits (val):
53 return round (val * 100) / 100
55 def extract_layout_information (tree):
56 paper = musicexp.Paper ()
57 defaults = tree.get_maybe_exist_named_child ('defaults')
61 scaling = defaults.get_maybe_exist_named_child ('scaling')
63 mm = scaling.get_named_child ('millimeters')
64 mm = string.atof (mm.get_text ())
65 tn = scaling.get_maybe_exist_named_child ('tenths')
66 tn = string.atof (tn.get_text ())
68 paper.global_staff_size = mm * 72.27 / 25.4
69 # We need the scaling (i.e. the size of staff tenths for everything!
73 def from_tenths (txt):
74 return round_to_two_digits (string.atof (txt) * tenths / 10)
75 def set_paper_variable (varname, parent, element_name):
76 el = parent.get_maybe_exist_named_child (element_name)
77 if el: # Convert to cm from tenths
78 setattr (paper, varname, from_tenths (el.get_text ()))
80 pagelayout = defaults.get_maybe_exist_named_child ('page-layout')
82 # TODO: How can one have different margins for even and odd pages???
83 set_paper_variable ("page_height", pagelayout, 'page-height')
84 set_paper_variable ("page_width", pagelayout, 'page-width')
86 pmargins = pagelayout.get_named_children ('page-margins')
88 set_paper_variable ("left_margin", pm, 'left-margin')
89 set_paper_variable ("right_margin", pm, 'right-margin')
90 set_paper_variable ("bottom_margin", pm, 'bottom-margin')
91 set_paper_variable ("top_margin", pm, 'top-margin')
93 systemlayout = defaults.get_maybe_exist_named_child ('system-layout')
95 sl = systemlayout.get_maybe_exist_named_child ('system-margins')
97 set_paper_variable ("system_left_margin", sl, 'left-margin')
98 set_paper_variable ("system_right_margin", sl, 'right-margin')
99 set_paper_variable ("system_distance", systemlayout, 'system-distance')
100 set_paper_variable ("top_system_distance", systemlayout, 'top-system-distance')
102 stafflayout = defaults.get_named_children ('staff-layout')
103 for sl in stafflayout:
104 nr = getattr (sl, 'number', 1)
105 dist = sl.get_named_child ('staff-distance')
106 #TODO: the staff distance needs to be set in the Staff context!!!
108 # TODO: Finish appearance?, music-font?, word-font?, lyric-font*, lyric-language*
109 appearance = defaults.get_named_child ('appearance')
111 lws = appearance.get_named_children ('line-width')
113 # Possible types are: beam, bracket, dashes,
114 # enclosure, ending, extend, heavy barline, leger,
115 # light barline, octave shift, pedal, slur middle, slur tip,
116 # staff, stem, tie middle, tie tip, tuplet bracket, and wedge
118 w = from_tenths (lw.get_data ())
119 # TODO: Do something with these values!
120 nss = appearance.get_named_children ('note-size')
122 # Possible types are: cue, grace and large
124 sz = from_tenths (ns.get_data ())
125 # TODO: Do something with these values!
126 # <other-appearance> elements have no specified meaning
128 rawmusicfont = defaults.get_named_child ('music-font')
130 # TODO: Convert the font
132 rawwordfont = defaults.get_named_child ('word-font')
134 # TODO: Convert the font
136 rawlyricsfonts = defaults.get_named_children ('lyric-font')
137 for lyricsfont in rawlyricsfonts:
138 # TODO: Convert the font
145 # score information is contained in the <work>, <identification> or <movement-title> tags
146 # extract those into a hash, indexed by proper lilypond header attributes
147 def extract_score_information (tree):
148 header = musicexp.Header ()
149 def set_if_exists (field, value):
151 header.set_field (field, musicxml.escape_ly_output_string (value))
153 work = tree.get_maybe_exist_named_child ('work')
155 set_if_exists ('title', work.get_work_title ())
156 set_if_exists ('worknumber', work.get_work_number ())
157 set_if_exists ('opus', work.get_opus ())
159 movement_title = tree.get_maybe_exist_named_child ('movement-title')
161 set_if_exists ('title', movement_title.get_text ())
163 identifications = tree.get_named_children ('identification')
164 for ids in identifications:
165 set_if_exists ('copyright', ids.get_rights ())
166 set_if_exists ('composer', ids.get_composer ())
167 set_if_exists ('arranger', ids.get_arranger ())
168 set_if_exists ('editor', ids.get_editor ())
169 set_if_exists ('poet', ids.get_poet ())
171 set_if_exists ('tagline', ids.get_encoding_software ())
172 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
173 set_if_exists ('encodingdate', ids.get_encoding_date ())
174 set_if_exists ('encoder', ids.get_encoding_person ())
175 set_if_exists ('encodingdescription', ids.get_encoding_description ())
184 return len (self.start) + len (self.end) == 0
185 def add_start (self, g):
186 self.start[getattr (g, 'number', "1")] = g
187 def add_end (self, g):
188 self.end[getattr (g, 'number', "1")] = g
189 def print_ly (self, printer):
190 error_message ("Unprocessed PartGroupInfo %s encountered" % self)
191 def ly_expression (self):
192 error_message ("Unprocessed PartGroupInfo %s encountered" % self)
196 def staff_attributes_to_string_tunings (mxl_attr):
197 details = mxl_attr.get_maybe_exist_named_child ('staff-details')
201 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
203 lines = string.atoi (staff_lines.get_text ())
206 staff_tunings = details.get_named_children ('staff-tuning')
207 for i in staff_tunings:
211 line = string.atoi (i.line) - 1
216 step = i.get_named_child (u'tuning-step')
217 step = step.get_text ().strip ()
218 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
220 octave = i.get_named_child (u'tuning-octave')
221 octave = octave.get_text ().strip ()
222 p.octave = int (octave) - 4
224 alter = i.get_named_child (u'tuning-alter')
226 p.alteration = int (alter.get_text ().strip ())
227 # lilypond seems to use the opposite ordering than MusicXML...
233 def staff_attributes_to_lily_staff (mxl_attr):
235 return musicexp.Staff ()
237 (staff_id, attributes) = mxl_attr.items ()[0]
239 # distinguish by clef:
240 # percussion (percussion and rhythmic), tab, and everything else
242 clef = attributes.get_maybe_exist_named_child ('clef')
244 sign = clef.get_maybe_exist_named_child ('sign')
246 clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
249 details = attributes.get_maybe_exist_named_child ('staff-details')
251 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
253 lines = string.atoi (staff_lines.get_text ())
256 if clef_sign == "percussion" and lines == 1:
257 staff = musicexp.RhythmicStaff ()
258 elif clef_sign == "percussion":
259 staff = musicexp.DrumStaff ()
260 # staff.drum_style_table = ???
261 elif clef_sign == "tab":
262 staff = musicexp.TabStaff ()
263 staff.string_tunings = staff_attributes_to_string_tunings (attributes)
264 # staff.tablature_format = ???
266 # TODO: Handle case with lines <> 5!
267 staff = musicexp.Staff ()
272 def extract_score_layout (part_list, staffinfo):
273 layout = musicexp.StaffGroup (None)
277 def read_score_part (el):
278 if not isinstance (el, musicxml.Score_part):
280 # Depending on the attributes of the first measure, we create different
281 # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
282 staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
286 partname = el.get_maybe_exist_named_child ('part-name')
287 # Finale gives unnamed parts the name "MusicXML Part" automatically!
288 if partname and partname.get_text() != "MusicXML Part":
289 staff.instrument_name = partname.get_text ()
290 if el.get_maybe_exist_named_child ('part-abbreviation'):
291 staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
292 # TODO: Read in the MIDI device / instrument
295 def read_score_group (el):
296 if not isinstance (el, musicxml.Part_group):
298 group = musicexp.StaffGroup ()
299 if hasattr (el, 'number'):
302 #currentgroups_dict[id] = group
303 #currentgroups.append (id)
304 if el.get_maybe_exist_named_child ('group-name'):
305 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
306 if el.get_maybe_exist_named_child ('group-abbreviation'):
307 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
308 if el.get_maybe_exist_named_child ('group-symbol'):
309 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
310 if el.get_maybe_exist_named_child ('group-barline'):
311 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
315 parts_groups = part_list.get_all_children ()
317 # the start/end group tags are not necessarily ordered correctly and groups
318 # might even overlap, so we can't go through the children sequentially!
320 # 1) Replace all Score_part objects by their corresponding Staff objects,
321 # also collect all group start/stop points into one PartGroupInfo object
323 group_info = PartGroupInfo ()
324 for el in parts_groups:
325 if isinstance (el, musicxml.Score_part):
326 if not group_info.is_empty ():
327 staves.append (group_info)
328 group_info = PartGroupInfo ()
329 staff = read_score_part (el)
331 staves.append (staff)
332 elif isinstance (el, musicxml.Part_group):
333 if el.type == "start":
334 group_info.add_start (el)
335 elif el.type == "stop":
336 group_info.add_end (el)
337 if not group_info.is_empty ():
338 staves.append (group_info)
340 # 2) Now, detect the groups:
343 while pos < len (staves):
345 if isinstance (el, PartGroupInfo):
347 if len (group_starts) > 0:
348 prev_start = group_starts[-1]
349 elif len (el.end) > 0: # no group to end here
351 if len (el.end) > 0: # closes an existing group
352 ends = el.end.keys ()
353 prev_started = staves[prev_start].start.keys ()
355 intersection = filter(lambda x:x in ends, prev_started)
356 if len (intersection) > 0:
357 grpid = intersection[0]
359 # Close the last started group
360 grpid = staves[prev_start].start.keys () [0]
361 # Find the corresponding closing tag and remove it!
364 while j < len (staves) and not foundclosing:
365 if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
367 del staves[j].end[grpid]
368 if staves[j].is_empty ():
371 grpobj = staves[prev_start].start[grpid]
372 group = read_score_group (grpobj)
373 # remove the id from both the start and end
374 if el.end.has_key (grpid):
376 del staves[prev_start].start[grpid]
379 # replace the staves with the whole group
380 for j in staves[(prev_start + 1):pos]:
382 j.stafftype = "InnerStaffGroup"
383 group.append_staff (j)
384 del staves[(prev_start + 1):pos]
385 staves.insert (prev_start + 1, group)
386 # reset pos so that we continue at the correct position
388 # remove an empty start group
389 if staves[prev_start].is_empty ():
390 del staves[prev_start]
391 group_starts.remove (prev_start)
393 elif len (el.start) > 0: # starts new part groups
394 group_starts.append (pos)
397 if len (staves) == 1:
400 layout.append_staff (i)
405 def musicxml_duration_to_lily (mxl_note):
406 d = musicexp.Duration ()
407 # if the note has no Type child, then that method spits out a warning and
408 # returns 0, i.e. a whole note
409 d.duration_log = mxl_note.get_duration_log ()
411 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
412 # Grace notes by specification have duration 0, so no time modification
413 # factor is possible. It even messes up the output with *0/1
414 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
415 d.factor = mxl_note._duration / d.get_length ()
419 def rational_to_lily_duration (rational_len):
420 d = musicexp.Duration ()
421 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)
422 d.factor = Rational (rational_len.numerator ())
423 if d.duration_log < 0:
424 error_message ("Encountered rational duration with denominator %s, "
425 "unable to convert to lilypond duration" %
426 rational_len.denominator ())
427 # TODO: Test the above error message
432 def musicxml_partial_to_lily (partial_len):
434 p = musicexp.Partial ()
435 p.partial = rational_to_lily_duration (partial_len)
440 # Detect repeats and alternative endings in the chord event list (music_list)
441 # and convert them to the corresponding musicexp objects, containing nested
443 def group_repeats (music_list):
444 repeat_replaced = True
447 # Walk through the list of expressions, looking for repeat structure
448 # (repeat start/end, corresponding endings). If we find one, try to find the
449 # last event of the repeat, replace the whole structure and start over again.
450 # For nested repeats, as soon as we encounter another starting repeat bar,
451 # treat that one first, and start over for the outer repeat.
452 while repeat_replaced and i < 100:
454 repeat_start = -1 # position of repeat start / end
455 repeat_end = -1 # position of repeat start / end
457 ending_start = -1 # position of current ending start
458 endings = [] # list of already finished endings
460 last = len (music_list) - 1
461 repeat_replaced = False
463 while pos < len (music_list) and not repeat_replaced:
465 repeat_finished = False
466 if isinstance (e, RepeatMarker):
467 if not repeat_times and e.times:
468 repeat_times = e.times
469 if e.direction == -1:
471 repeat_finished = True
477 elif e.direction == 1:
483 elif isinstance (e, EndingMarker):
484 if e.direction == -1:
490 elif e.direction == 1:
493 endings.append ([ending_start, pos])
496 elif not isinstance (e, musicexp.BarLine):
497 # As soon as we encounter an element when repeat start and end
498 # is set and we are not inside an alternative ending,
499 # this whole repeat structure is finished => replace it
500 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
501 repeat_finished = True
503 # Finish off all repeats without explicit ending bar (e.g. when
504 # we convert only one page of a multi-page score with repeats)
505 if pos == last and repeat_start >= 0:
506 repeat_finished = True
510 if ending_start >= 0:
511 endings.append ([ending_start, pos])
515 # We found the whole structure replace it!
516 r = musicexp.RepeatedMusic ()
517 if repeat_times <= 0:
519 r.repeat_count = repeat_times
520 # don't erase the first element for "implicit" repeats (i.e. no
521 # starting repeat bars at the very beginning)
522 start = repeat_start+1
523 if repeat_start == music_start:
525 r.set_music (music_list[start:repeat_end])
526 for (start, end) in endings:
527 s = musicexp.SequentialMusic ()
528 s.elements = music_list[start+1:end]
530 del music_list[repeat_start:final_marker+1]
531 music_list.insert (repeat_start, r)
532 repeat_replaced = True
534 # TODO: Implement repeats until the end without explicit ending bar
539 def group_tuplets (music_list, events):
542 """Collect Musics from
543 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
550 for (ev_chord, tuplet_elt, fraction) in events:
551 while (j < len (music_list)):
552 if music_list[j] == ev_chord:
555 if tuplet_elt.type == 'start':
556 indices.append ((j, None, fraction))
557 elif tuplet_elt.type == 'stop':
558 indices[-1] = (indices[-1][0], j, indices[-1][2])
562 for (i1, i2, frac) in indices:
566 new_list.extend (music_list[last:i1])
567 seq = musicexp.SequentialMusic ()
569 seq.elements = music_list[i1:last]
571 tsm = musicexp.TimeScaledMusic ()
574 tsm.numerator = frac[0]
575 tsm.denominator = frac[1]
577 new_list.append (tsm)
579 new_list.extend (music_list[last:])
583 def musicxml_clef_to_lily (attributes):
584 change = musicexp.ClefChange ()
585 (change.type, change.position, change.octave) = attributes.get_clef_information ()
588 def musicxml_time_to_lily (attributes):
589 (beats, type) = attributes.get_time_signature ()
591 change = musicexp.TimeSignatureChange()
592 change.fraction = (beats, type)
596 def musicxml_key_to_lily (attributes):
597 start_pitch = musicexp.Pitch ()
598 (fifths, mode) = attributes.get_key_signature ()
605 start_pitch.alteration = a
607 error_message ('unknown mode %s' % mode)
609 fifth = musicexp.Pitch()
616 for x in range (fifths):
617 start_pitch = start_pitch.transposed (fifth)
619 start_pitch.octave = 0
621 change = musicexp.KeySignatureChange()
623 change.tonic = start_pitch
626 def musicxml_attributes_to_lily (attrs):
629 'clef': musicxml_clef_to_lily,
630 'time': musicxml_time_to_lily,
631 'key': musicxml_key_to_lily
633 for (k, func) in attr_dispatch.items ():
634 children = attrs.get_named_children (k)
636 elts.append (func (attrs))
640 class Marker (musicexp.Music):
644 def print_ly (self, printer):
645 sys.stderr.write ("Encountered unprocessed marker %s\n" % self)
647 def ly_expression (self):
649 class RepeatMarker (Marker):
651 Marker.__init__ (self)
653 class EndingMarker (Marker):
656 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
657 # and to RepeatMarker and EndingMarker objects for repeat and
658 # alternatives start/stops
659 def musicxml_barline_to_lily (barline):
660 # retval contains all possible markers in the order:
661 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
663 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
664 repeat_element = barline.get_maybe_exist_named_child ("repeat")
665 ending_element = barline.get_maybe_exist_named_child ("ending")
669 bartype = bartype_element.get_text ()
671 if repeat_element and hasattr (repeat_element, 'direction'):
672 repeat = RepeatMarker ()
673 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
675 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
676 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
678 if hasattr (repeat_element, 'times'):
680 repeat.times = int (repeat_element.times)
683 repeat.event = barline
684 if repeat.direction == -1:
689 if ending_element and hasattr (ending_element, 'type'):
690 ending = EndingMarker ()
691 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
692 ending.event = barline
693 if ending.direction == -1:
699 b = musicexp.BarLine ()
703 return retval.values ()
705 spanner_event_dict = {
706 'slur' : musicexp.SlurEvent,
707 'beam' : musicexp.BeamEvent,
708 'glissando' : musicexp.GlissandoEvent,
709 'pedal' : musicexp.PedalEvent,
710 'wavy-line' : musicexp.TrillSpanEvent,
711 'octave-shift' : musicexp.OctaveShiftEvent,
712 'wedge' : musicexp.HairpinEvent
714 spanner_type_dict = {
727 def musicxml_spanner_to_lily_event (mxl_event):
730 name = mxl_event.get_name()
731 func = spanner_event_dict.get (name)
735 error_message ('unknown span event %s' % mxl_event)
738 type = mxl_event.get_type ()
739 span_direction = spanner_type_dict.get (type)
740 # really check for None, because some types will be translated to 0, which
741 # would otherwise also lead to the unknown span warning
742 if span_direction != None:
743 ev.span_direction = span_direction
745 error_message ('unknown span type %s for %s' % (type, name))
747 ev.set_span_type (type)
748 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
750 # assign the size, which is used for octave-shift, etc.
751 ev.size = mxl_event.get_size ()
755 def musicxml_direction_to_indicator (direction):
756 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
758 def musicxml_fermata_to_lily_event (mxl_event):
759 ev = musicexp.ArticulationEvent ()
761 if hasattr (mxl_event, 'type'):
762 dir = musicxml_direction_to_indicator (mxl_event.type)
764 ev.force_direction = dir
768 def musicxml_arpeggiate_to_lily_event (mxl_event):
769 ev = musicexp.ArpeggioEvent ()
770 ev.direction = {"up": 1, "down": -1}.get (getattr (mxl_event, 'direction', None), 0)
774 def musicxml_tremolo_to_lily_event (mxl_event):
775 ev = musicexp.TremoloEvent ()
776 ev.bars = mxl_event.get_text ()
779 def musicxml_bend_to_lily_event (mxl_event):
780 ev = musicexp.BendEvent ()
781 ev.alter = mxl_event.bend_alter ()
785 def musicxml_fingering_event (mxl_event):
786 ev = musicexp.ShortArticulationEvent ()
787 ev.type = mxl_event.get_text ()
790 def musicxml_snappizzicato_event (mxl_event):
791 needed_additional_definitions.append ("snappizzicato")
792 ev = musicexp.MarkupEvent ()
793 ev.contents = "\\snappizzicato"
796 def musicxml_string_event (mxl_event):
797 ev = musicexp.NoDirectionArticulationEvent ()
798 ev.type = mxl_event.get_text ()
801 def musicxml_accidental_mark (mxl_event):
802 ev = musicexp.MarkupEvent ()
803 contents = { "sharp": "\\sharp",
804 "natural": "\\natural",
806 "double-sharp": "\\doublesharp",
807 "sharp-sharp": "\\sharp\\sharp",
808 "flat-flat": "\\flat\\flat",
809 "flat-flat": "\\doubleflat",
810 "natural-sharp": "\\natural\\sharp",
811 "natural-flat": "\\natural\\flat",
812 "quarter-flat": "\\semiflat",
813 "quarter-sharp": "\\semisharp",
814 "three-quarters-flat": "\\sesquiflat",
815 "three-quarters-sharp": "\\sesquisharp",
816 }.get (mxl_event.get_text ())
818 ev.contents = contents
823 # translate articulations, ornaments and other notations into ArticulationEvents
825 # -) string (ArticulationEvent with that name)
826 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
827 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
828 # TODO: Some translations are missing!
829 articulations_dict = {
830 "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
831 "accidental-mark": musicxml_accidental_mark,
832 "bend": musicxml_bend_to_lily_event,
833 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
834 #"caesura": "caesura",
835 #"delayed-turn": "?",
836 "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
838 #"double-tongue": "",
839 "down-bow": "downbow",
841 "fingering": musicxml_fingering_event,
845 "harmonic": "flageolet",
847 "inverted-mordent": "prall",
848 "inverted-turn": "reverseturn",
849 "mordent": "mordent",
850 "open-string": "open",
857 "snap-pizzicato": musicxml_snappizzicato_event,
859 "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
860 "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
861 "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
863 "string": musicxml_string_event,
864 "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
866 "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
867 #"thumb-position": "",
870 "tremolo": musicxml_tremolo_to_lily_event,
871 "trill-mark": "trill",
872 #"triple-tongue": "",
877 articulation_spanners = [ "wavy-line" ]
879 def musicxml_articulation_to_lily_event (mxl_event):
880 # wavy-line elements are treated as trill spanners, not as articulation ornaments
881 if mxl_event.get_name () in articulation_spanners:
882 return musicxml_spanner_to_lily_event (mxl_event)
884 tmp_tp = articulations_dict.get (mxl_event.get_name ())
888 if isinstance (tmp_tp, str):
889 ev = musicexp.ArticulationEvent ()
891 elif isinstance (tmp_tp, tuple):
895 ev = tmp_tp (mxl_event)
897 # Some articulations use the type attribute, other the placement...
899 if hasattr (mxl_event, 'type'):
900 dir = musicxml_direction_to_indicator (mxl_event.type)
901 if hasattr (mxl_event, 'placement'):
902 dir = musicxml_direction_to_indicator (mxl_event.placement)
906 def musicxml_dynamics_to_lily_event (dynentry):
907 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
908 "f", "ff", "fff", "ffff", "fffff", "ffffff",
909 "mp", "mf", "sf", "sfp", "sfpp", "fp",
910 "rf", "rfz", "sfz", "sffz", "fz" )
911 if not dynentry.get_name() in dynamics_available:
913 event = musicexp.DynamicsEvent ()
914 event.type = dynentry.get_name ()
917 # Convert single-color two-byte strings to numbers 0.0 - 1.0
918 def hexcolorval_to_nr (hex_val):
920 v = int (hex_val, 16)
927 def hex_to_color (hex_val):
928 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)
930 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
934 def musicxml_words_to_lily_event (words):
935 event = musicexp.TextEvent ()
936 text = words.get_text ()
937 text = re.sub ('^ *\n? *', '', text)
938 text = re.sub (' *\n? *$', '', text)
941 if hasattr (words, 'default-y'):
942 offset = getattr (words, 'default-y')
944 off = string.atoi (offset)
946 event.force_direction = 1
948 event.force_direction = -1
950 event.force_direction = 0
952 if hasattr (words, 'font-weight'):
953 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
955 event.markup += font_weight
957 if hasattr (words, 'font-size'):
958 size = getattr (words, 'font-size')
960 "xx-small": '\\teeny',
966 "xx-large": '\\bigger\\huge'
969 event.markup += font_size
971 if hasattr (words, 'color'):
972 color = getattr (words, 'color')
973 rgb = hex_to_color (color)
975 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
977 if hasattr (words, 'font-style'):
978 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
980 event.markup += font_style
982 # TODO: How should I best convert the font-family attribute?
984 # TODO: How can I represent the underline, overline and line-through
985 # attributes in Lilypond? Values of these attributes indicate
986 # the number of lines
991 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
993 def musicxml_direction_to_lily (n):
994 # TODO: Handle the <staff> element!
996 dirtype_children = []
997 for dt in n.get_typed_children (musicxml.DirType):
998 dirtype_children += dt.get_all_children ()
1000 for entry in dirtype_children:
1002 if entry.get_name () == "dynamics":
1003 for dynentry in entry.get_all_children ():
1004 ev = musicxml_dynamics_to_lily_event (dynentry)
1008 if entry.get_name () == "words":
1009 ev = musicxml_words_to_lily_event (entry)
1013 # octave shifts. pedal marks, hairpins etc. are spanners:
1014 if entry.get_name() in direction_spanners:
1015 event = musicxml_spanner_to_lily_event (entry)
1022 def musicxml_frame_to_lily_event (frame):
1023 ev = musicexp.FretEvent ()
1024 ev.strings = frame.get_strings ()
1025 ev.frets = frame.get_frets ()
1026 #offset = frame.get_first_fret () - 1
1028 for fn in frame.get_named_children ('frame-note'):
1029 fret = fn.get_fret ()
1032 el = [ fn.get_string (), fret ]
1033 fingering = fn.get_fingering ()
1035 el.append (fingering)
1036 ev.elements.append (el)
1039 barre[0] = el[0] # start string
1040 barre[2] = el[1] # fret
1042 barre[1] = el[0] # end string
1047 def musicxml_harmony_to_lily (n):
1049 for f in n.get_named_children ('frame'):
1050 ev = musicxml_frame_to_lily_event (f)
1056 instrument_drumtype_dict = {
1057 'Acoustic Snare Drum': 'acousticsnare',
1058 'Side Stick': 'sidestick',
1059 'Open Triangle': 'opentriangle',
1060 'Mute Triangle': 'mutetriangle',
1061 'Tambourine': 'tambourine',
1062 'Bass Drum': 'bassdrum',
1065 def musicxml_note_to_lily_main_event (n):
1069 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1072 pitch = musicxml_pitch_to_lily (mxl_pitch)
1073 event = musicexp.NoteEvent()
1076 acc = n.get_maybe_exist_named_child ('accidental')
1078 # let's not force accs everywhere.
1079 event.cautionary = acc.editorial
1081 elif n.get_maybe_exist_typed_child (musicxml.Rest):
1082 # rests can have display-octave and display-step, which are
1083 # treated like an ordinary note pitch
1084 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1085 event = musicexp.RestEvent()
1086 pitch = musicxml_restdisplay_to_lily (rest)
1088 elif n.instrument_name:
1089 event = musicexp.NoteEvent ()
1090 drum_type = instrument_drumtype_dict.get (n.instrument_name)
1092 event.drum_type = drum_type
1094 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
1095 event.drum_type = 'acousticsnare'
1098 n.message ("cannot find suitable event")
1100 event.duration = musicxml_duration_to_lily (n)
1106 def __init__ (self, here, dest):
1110 class LilyPondVoiceBuilder:
1111 def __init__ (self):
1113 self.pending_dynamics = []
1114 self.end_moment = Rational (0)
1115 self.begin_moment = Rational (0)
1116 self.pending_multibar = Rational (0)
1117 self.ignore_skips = False
1119 def _insert_multibar (self):
1120 r = musicexp.MultiMeasureRest ()
1121 r.duration = musicexp.Duration()
1122 r.duration.duration_log = 0
1123 r.duration.factor = self.pending_multibar
1124 self.elements.append (r)
1125 self.begin_moment = self.end_moment
1126 self.end_moment = self.begin_moment + self.pending_multibar
1127 self.pending_multibar = Rational (0)
1129 def add_multibar_rest (self, duration):
1130 self.pending_multibar += duration
1132 def set_duration (self, duration):
1133 self.end_moment = self.begin_moment + duration
1134 def current_duration (self):
1135 return self.end_moment - self.begin_moment
1137 def add_music (self, music, duration):
1138 assert isinstance (music, musicexp.Music)
1139 if self.pending_multibar > Rational (0):
1140 self._insert_multibar ()
1142 self.elements.append (music)
1143 self.begin_moment = self.end_moment
1144 self.set_duration (duration)
1146 # Insert all pending dynamics right after the note/rest:
1147 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
1148 for d in self.pending_dynamics:
1150 self.pending_dynamics = []
1152 # Insert some music command that does not affect the position in the measure
1153 def add_command (self, command):
1154 assert isinstance (command, musicexp.Music)
1155 if self.pending_multibar > Rational (0):
1156 self._insert_multibar ()
1157 self.elements.append (command)
1158 def add_barline (self, barline):
1159 # TODO: Implement merging of default barline and custom bar line
1160 self.add_music (barline, Rational (0))
1161 def add_partial (self, command):
1162 self.ignore_skips = True
1163 self.add_command (command)
1165 def add_dynamics (self, dynamic):
1166 # store the dynamic item(s) until we encounter the next note/rest:
1167 self.pending_dynamics.append (dynamic)
1169 def add_bar_check (self, number):
1170 b = musicexp.BarLine ()
1171 b.bar_number = number
1172 self.add_barline (b)
1174 def jumpto (self, moment):
1175 current_end = self.end_moment + self.pending_multibar
1176 diff = moment - current_end
1178 if diff < Rational (0):
1179 error_message ('Negative skip %s' % diff)
1182 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
1183 skip = musicexp.SkipEvent()
1184 skip.duration.duration_log = 0
1185 skip.duration.factor = diff
1187 evc = musicexp.EventChord ()
1188 evc.elements.append (skip)
1189 self.add_music (evc, diff)
1191 if diff > Rational (0) and moment == 0:
1192 self.ignore_skips = False
1194 def last_event_chord (self, starting_at):
1198 # if the position matches, find the last EventChord, do not cross a bar line!
1199 at = len( self.elements ) - 1
1201 not isinstance (self.elements[at], musicexp.EventChord) and
1202 not isinstance (self.elements[at], musicexp.BarLine)):
1207 and isinstance (self.elements[at], musicexp.EventChord)
1208 and self.begin_moment == starting_at):
1209 value = self.elements[at]
1211 self.jumpto (starting_at)
1215 def correct_negative_skip (self, goto):
1216 self.end_moment = goto
1217 self.begin_moment = goto
1218 evc = musicexp.EventChord ()
1219 self.elements.append (evc)
1223 def __init__ (self):
1224 self.voicedata = None
1225 self.ly_voice = None
1226 self.lyrics_dict = {}
1227 self.lyrics_order = []
1229 def musicxml_voice_to_lily_voice (voice):
1233 return_value = VoiceData ()
1234 return_value.voicedata = voice
1236 # Needed for melismata detection (ignore lyrics on those notes!):
1240 ignore_lyrics = False
1242 current_staff = None
1244 # Make sure that the keys in the dict don't get reordered, since
1245 # we need the correct ordering of the lyrics stanzas! By default,
1246 # a dict will reorder its keys
1247 return_value.lyrics_order = voice.get_lyrics_numbers ()
1248 for k in return_value.lyrics_order:
1251 voice_builder = LilyPondVoiceBuilder()
1253 for n in voice._elements:
1254 if n.get_name () == 'forward':
1256 staff = n.get_maybe_exist_named_child ('staff')
1258 staff = staff.get_text ()
1259 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
1260 voice_builder.add_command (musicexp.StaffChange (staff))
1261 current_staff = staff
1263 if isinstance (n, musicxml.Partial) and n.partial > 0:
1264 a = musicxml_partial_to_lily (n.partial)
1266 voice_builder.add_partial (a)
1269 if isinstance (n, musicxml.Direction):
1270 for a in musicxml_direction_to_lily (n):
1271 if a.wait_for_note ():
1272 voice_builder.add_dynamics (a)
1274 voice_builder.add_command (a)
1277 if isinstance (n, musicxml.Harmony):
1278 for a in musicxml_harmony_to_lily (n):
1279 if a.wait_for_note ():
1280 voice_builder.add_dynamics (a)
1282 voice_builder.add_command (a)
1285 is_chord = n.get_maybe_exist_named_child ('chord')
1288 voice_builder.jumpto (n._when)
1289 except NegativeSkip, neg:
1290 voice_builder.correct_negative_skip (n._when)
1291 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
1293 if isinstance (n, musicxml.Attributes):
1294 if n.is_first () and n._measure_position == Rational (0):
1296 number = int (n.get_parent ().number)
1300 voice_builder.add_bar_check (number)
1302 for a in musicxml_attributes_to_lily (n):
1303 voice_builder.add_command (a)
1306 if isinstance (n, musicxml.Barline):
1307 barlines = musicxml_barline_to_lily (n)
1309 if isinstance (a, musicexp.BarLine):
1310 voice_builder.add_barline (a)
1311 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
1312 voice_builder.add_command (a)
1315 if not n.__class__.__name__ == 'Note':
1316 error_message ('not a Note or Attributes? %s' % n)
1319 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1321 and rest.is_whole_measure ()):
1323 voice_builder.add_multibar_rest (n._duration)
1326 if n.is_first () and n._measure_position == Rational (0):
1328 num = int (n.get_parent ().number)
1332 voice_builder.add_bar_check (num)
1334 main_event = musicxml_note_to_lily_main_event (n)
1335 ignore_lyrics = inside_slur or is_tied or is_chord
1337 if hasattr (main_event, 'drum_type') and main_event.drum_type:
1338 modes_found['drummode'] = True
1341 ev_chord = voice_builder.last_event_chord (n._when)
1343 ev_chord = musicexp.EventChord()
1344 voice_builder.add_music (ev_chord, n._duration)
1346 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
1349 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
1350 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
1352 grace_chord = musicexp.EventChord ()
1353 ev_chord.append_grace (grace_chord)
1354 if hasattr (grace, 'slash'):
1355 # TODO: use grace_type = "appoggiatura" for slurred grace notes
1356 if grace.slash == "yes":
1357 ev_chord.grace_type = "acciaccatura"
1358 elif grace.slash == "no":
1359 ev_chord.grace_type = "grace"
1360 # now that we have inserted the chord into the grace music, insert
1361 # everything into that chord instead of the ev_chord
1362 ev_chord = grace_chord
1363 ev_chord.append (main_event)
1364 ignore_lyrics = True
1366 ev_chord.append (main_event)
1367 # When a note/chord has grace notes (duration==0), the duration of the
1368 # event chord is not yet known, but the event chord was already added
1369 # with duration 0. The following correct this when we hit the real note!
1370 if voice_builder.current_duration () == 0 and n._duration > 0:
1371 voice_builder.set_duration (n._duration)
1373 notations_children = n.get_typed_children (musicxml.Notations)
1377 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
1378 # +tied | +slur | +tuplet | glissando | slide |
1379 # ornaments | technical | articulations | dynamics |
1380 # +fermata | arpeggiate | non-arpeggiate |
1381 # accidental-mark | other-notation
1382 for notations in notations_children:
1383 if notations.get_tuplet():
1384 tuplet_event = notations.get_tuplet()
1385 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1388 frac = mod.get_fraction ()
1390 tuplet_events.append ((ev_chord, tuplet_event, frac))
1392 slurs = [s for s in notations.get_named_children ('slur')
1393 if s.get_type () in ('start','stop')]
1396 error_message ('more than 1 slur?')
1397 # record the slur status for the next note in the loop
1399 if slurs[0].get_type () == 'start':
1401 elif slurs[0].get_type () == 'stop':
1403 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
1404 ev_chord.append (lily_ev)
1407 mxl_tie = notations.get_tie ()
1408 if mxl_tie and mxl_tie.type == 'start':
1409 ev_chord.append (musicexp.TieEvent ())
1414 fermatas = notations.get_named_children ('fermata')
1416 ev = musicxml_fermata_to_lily_event (a)
1418 ev_chord.append (ev)
1420 arpeggiate = notations.get_named_children ('arpeggiate')
1421 for a in arpeggiate:
1422 ev = musicxml_arpeggiate_to_lily_event (a)
1424 ev_chord.append (ev)
1426 glissandos = notations.get_named_children ('glissando')
1427 for a in glissandos:
1428 ev = musicxml_spanner_to_lily_event (a)
1430 ev_chord.append (ev)
1432 # Articulations can contain the following child elements:
1433 # accent | strong-accent | staccato | tenuto |
1434 # detached-legato | staccatissimo | spiccato |
1435 # scoop | plop | doit | falloff | breath-mark |
1436 # caesura | stress | unstress
1437 # Technical can contain the following child elements:
1438 # up-bow | down-bow | harmonic | open-string |
1439 # thumb-position | fingering | pluck | double-tongue |
1440 # triple-tongue | stopped | snap-pizzicato | fret |
1441 # string | hammer-on | pull-off | bend | tap | heel |
1442 # toe | fingernails | other-technical
1443 # Ornaments can contain the following child elements:
1444 # trill-mark | turn | delayed-turn | inverted-turn |
1445 # shake | wavy-line | mordent | inverted-mordent |
1446 # schleifer | tremolo | other-ornament, accidental-mark
1447 ornaments = notations.get_named_children ('ornaments')
1449 for ch in a.get_named_children ('tremolo'):
1450 ev = musicxml_tremolo_to_lily_event (ch)
1452 ev_chord.append (ev)
1454 ornaments += notations.get_named_children ('articulations')
1455 ornaments += notations.get_named_children ('technical')
1458 for ch in a.get_all_children ():
1459 ev = musicxml_articulation_to_lily_event (ch)
1461 ev_chord.append (ev)
1463 dynamics = notations.get_named_children ('dynamics')
1465 for ch in a.get_all_children ():
1466 ev = musicxml_dynamics_to_lily_event (ch)
1468 ev_chord.append (ev)
1470 # Extract the lyrics
1471 if not rest and not ignore_lyrics:
1472 note_lyrics_processed = []
1473 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1474 for l in note_lyrics_elements:
1475 if l.get_number () < 0:
1476 for k in lyrics.keys ():
1477 lyrics[k].append (l.lyric_to_text ())
1478 note_lyrics_processed.append (k)
1480 lyrics[l.number].append(l.lyric_to_text ())
1481 note_lyrics_processed.append (l.number)
1482 for lnr in lyrics.keys ():
1483 if not lnr in note_lyrics_processed:
1484 lyrics[lnr].append ("\skip4")
1487 mxl_beams = [b for b in n.get_named_children ('beam')
1488 if (b.get_type () in ('begin', 'end')
1489 and b.is_primary ())]
1491 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1493 ev_chord.append (beam_ev)
1496 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1499 frac = mod.get_fraction ()
1501 tuplet_events.append ((ev_chord, tuplet_event, frac))
1503 ## force trailing mm rests to be written out.
1504 voice_builder.add_music (musicexp.EventChord (), Rational (0))
1506 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1507 ly_voice = group_repeats (ly_voice)
1509 seq_music = musicexp.SequentialMusic ()
1511 if 'drummode' in modes_found.keys ():
1512 ## \key <pitch> barfs in drummode.
1513 ly_voice = [e for e in ly_voice
1514 if not isinstance(e, musicexp.KeySignatureChange)]
1516 seq_music.elements = ly_voice
1517 for k in lyrics.keys ():
1518 return_value.lyrics_dict[k] = musicexp.Lyrics ()
1519 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
1522 if len (modes_found) > 1:
1523 error_message ('Too many modes found %s' % modes_found.keys ())
1525 return_value.ly_voice = seq_music
1526 for mode in modes_found.keys ():
1527 v = musicexp.ModeChangingMusicWrapper()
1528 v.element = seq_music
1530 return_value.ly_voice = v
1535 def musicxml_id_to_lily (id):
1536 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1537 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1539 for digit in digits:
1540 d = digits.index (digit)
1541 id = re.sub ('%d' % d, digit, id)
1543 id = re.sub ('[^a-zA-Z]', 'X', id)
1547 def musicxml_pitch_to_lily (mxl_pitch):
1548 p = musicexp.Pitch()
1549 p.alteration = mxl_pitch.get_alteration ()
1550 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1551 p.octave = mxl_pitch.get_octave () - 4
1554 def musicxml_restdisplay_to_lily (mxl_rest):
1556 step = mxl_rest.get_step ()
1558 p = musicexp.Pitch()
1559 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1560 octave = mxl_rest.get_octave ()
1562 p.octave = octave - 4
1565 def voices_in_part (part):
1566 """Return a Name -> Voice dictionary for PART"""
1568 part.extract_voices ()
1569 voices = part.get_voices ()
1570 part_info = part.get_staff_attributes ()
1572 return (voices, part_info)
1574 def voices_in_part_in_parts (parts):
1575 """return a Part -> Name -> Voice dictionary"""
1576 return dict([(p.id, voices_in_part (p)) for p in parts])
1579 def get_all_voices (parts):
1580 all_voices = voices_in_part_in_parts (parts)
1583 all_ly_staffinfo = {}
1584 for p, (name_voice, staff_info) in all_voices.items ():
1587 for n, v in name_voice.items ():
1588 progress ("Converting to LilyPond expressions...")
1589 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1590 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
1592 all_ly_voices[p] = part_ly_voices
1593 all_ly_staffinfo[p] = staff_info
1595 return (all_ly_voices, all_ly_staffinfo)
1598 def option_parser ():
1599 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1600 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1602 _ ("""This program is free software. It is covered by the GNU General Public
1603 License and you are welcome to change it and/or distribute copies of it
1604 under certain conditions. Invoke as `%s --warranty' for more
1605 information.""") % 'lilypond'
1607 Copyright (c) 2005--2007 by
1608 Han-Wen Nienhuys <hanwen@xs4all.nl> and
1609 Jan Nieuwenhuizen <janneke@gnu.org>
1611 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1612 p.add_option ('-v', '--verbose',
1613 action="store_true",
1615 help=_ ("be verbose"))
1617 p.add_option ('', '--lxml',
1618 action="store_true",
1621 help=_ ("Use lxml.etree; uses less memory and cpu time."))
1623 p.add_option ('-l', '--language',
1625 help = _ ("Use a different language file, e.g. 'deutsch' for deutsch.ly."))
1627 p.add_option ('-o', '--output',
1633 help=_ ("set output filename to FILE"))
1634 p.add_option_group ('bugs',
1635 description=(_ ("Report bugs via")
1636 + ''' http://post.gmane.org/post.php'''
1637 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1640 def music_xml_voice_name_to_lily_name (part_id, name):
1641 str = "Part%sVoice%s" % (part_id, name)
1642 return musicxml_id_to_lily (str)
1644 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
1645 str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
1646 return musicxml_id_to_lily (str)
1648 def print_voice_definitions (printer, part_list, voices):
1649 for part in part_list:
1651 nv_dict = voices.get (part_id, {})
1652 for (name, voice) in nv_dict.items ():
1653 k = music_xml_voice_name_to_lily_name (part_id, name)
1654 printer.dump ('%s = ' % k)
1655 voice.ly_voice.print_ly (printer)
1657 for l in voice.lyrics_order:
1658 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
1659 printer.dump ('%s = ' %lname )
1660 voice.lyrics_dict[l].print_ly (printer)
1665 return dict ([(elt,1) for elt in l]).keys ()
1667 # format the information about the staff in the form
1670 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1671 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1675 # raw_voices is of the form [(voicename, lyricsids)*]
1676 def format_staff_info (part_id, staff_id, raw_voices):
1678 for (v, lyricsids) in raw_voices:
1679 voice_name = music_xml_voice_name_to_lily_name (part_id, v)
1680 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
1682 voices.append ([voice_name, voice_lyrics])
1683 return [staff_id, voices]
1685 def update_score_setup (score_structure, part_list, voices):
1687 for part_definition in part_list:
1688 part_id = part_definition.id
1689 nv_dict = voices.get (part_id)
1691 error_message ('unknown part in part-list: %s' % part_id)
1694 staves = reduce (lambda x,y: x+ y,
1695 [voice.voicedata._staves.keys ()
1696 for voice in nv_dict.values ()],
1699 if len (staves) > 1:
1701 staves = uniq_list (staves)
1704 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1705 for (voice_name, voice) in nv_dict.items ()
1706 if voice.voicedata._start_staff == s]
1707 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
1709 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1710 for (voice_name, voice) in nv_dict.items ()]
1711 staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
1712 score_structure.set_part_information (part_id, staves_info)
1714 def print_ly_preamble (printer, filename):
1715 printer.dump_version ()
1716 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1718 def print_ly_additional_definitions (printer, filename):
1719 if needed_additional_definitions:
1721 printer.print_verbatim ('%% additional definitions required by the score:')
1723 for a in set(needed_additional_definitions):
1724 printer.print_verbatim (additional_definitions.get (a, ''))
1728 def read_musicxml (filename, use_lxml):
1732 tree = lxml.etree.parse (filename)
1733 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1736 from xml.dom import minidom, Node
1738 doc = minidom.parse(filename)
1739 node = doc.documentElement
1740 return musicxml.minidom_demarshal_node (node)
1745 def convert (filename, options):
1746 progress ("Reading MusicXML from %s ..." % filename)
1748 tree = read_musicxml (filename, options.use_lxml)
1749 parts = tree.get_typed_children (musicxml.Part)
1750 (voices, staff_info) = get_all_voices (parts)
1752 score_structure = None
1753 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1755 score_structure = extract_score_layout (mxl_pl, staff_info)
1756 part_list = mxl_pl.get_named_children ("score-part")
1758 # score information is contained in the <work>, <identification> or <movement-title> tags
1759 score_information = extract_score_information (tree)
1760 layout_information = extract_layout_information (tree)
1761 update_score_setup (score_structure, part_list, voices)
1763 if not options.output_name:
1764 options.output_name = os.path.basename (filename)
1765 options.output_name = os.path.splitext (options.output_name)[0]
1766 elif re.match (".*\.ly", options.output_name):
1767 options.output_name = os.path.splitext (options.output_name)[0]
1770 defs_ly_name = options.output_name + '-defs.ly'
1771 driver_ly_name = options.output_name + '.ly'
1773 printer = musicexp.Output_printer()
1774 progress ("Output to `%s'" % defs_ly_name)
1775 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1777 print_ly_preamble (printer, filename)
1778 print_ly_additional_definitions (printer, filename)
1779 if score_information:
1780 score_information.print_ly (printer)
1781 if layout_information:
1782 layout_information.print_ly (printer)
1783 print_voice_definitions (printer, part_list, voices)
1788 progress ("Output to `%s'" % driver_ly_name)
1789 printer = musicexp.Output_printer()
1790 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1791 print_ly_preamble (printer, filename)
1792 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1793 score_structure.print_ly (printer)
1798 def get_existing_filename_with_extension (filename, ext):
1799 if os.path.exists (filename):
1801 newfilename = filename + ".xml"
1802 if os.path.exists (newfilename):
1804 newfilename = filename + "xml"
1805 if os.path.exists (newfilename):
1810 opt_parser = option_parser()
1812 (options, args) = opt_parser.parse_args ()
1814 opt_parser.print_usage()
1817 if options.language:
1818 musicexp.set_pitch_language (options.language)
1819 needed_additional_definitions.append (options.language)
1820 additional_definitions[options.language] = "\\include \"%s.ly\"\n" % options.language
1822 # Allow the user to leave out the .xml or xml on the filename
1823 filename = get_existing_filename_with_extension (args[0], "xml")
1824 if filename and os.path.exists (filename):
1825 voices = convert (filename, options)
1827 progress ("Unable to find input file %s" % args[0])
1829 if __name__ == '__main__':