2 # -*- coding: utf-8 -*-
23 from rational import Rational
25 # Store command-line options in a global variable, so we can access them everythwere
28 class Conversion_Settings:
30 self.ignore_beaming = False
32 conversion_settings = Conversion_Settings ()
33 # Use a global variable to store the setting needed inside a \layout block.
34 # whenever we need to change a setting or add/remove an engraver, we can access
35 # this layout and add the corresponding settings
36 layout_information = musicexp.Layout ()
38 needed_additional_definitions = []
39 additional_definitions = {
41 "tuplet-note-wrapper": """ % a formatter function, which is simply a wrapper around an existing
42 % tuplet formatter function. It takes the value returned by the given
43 % function and appends a note of given length.
44 #(define-public ((tuplet-number::append-note-wrapper function note) grob)
45 (let* ((txt (if function (function grob) #f)))
47 (markup txt #:fontsize -5 #:note note UP)
48 (markup #:fontsize -5 #:note note UP)
53 "tuplet-non-default-denominator": """#(define ((tuplet-number::non-default-tuplet-denominator-text denominator) grob)
54 (number->string (if denominator
56 (ly:event-property (event-cause grob) 'denominator))))
59 "tuplet-non-default-fraction": """#(define ((tuplet-number::non-default-tuplet-fraction-text denominator numerator) grob)
60 (let* ((ev (event-cause grob))
61 (den (if denominator denominator (ly:event-property ev 'denominator)))
62 (num (if numerator numerator (ly:event-property ev 'numerator))))
63 (format #f "~a:~a" den num)))
67 def round_to_two_digits (val):
68 return round (val * 100) / 100
70 def extract_paper_information (tree):
71 paper = musicexp.Paper ()
72 defaults = tree.get_maybe_exist_named_child ('defaults')
76 scaling = defaults.get_maybe_exist_named_child ('scaling')
78 mm = scaling.get_named_child ('millimeters')
79 mm = string.atof (mm.get_text ())
80 tn = scaling.get_maybe_exist_named_child ('tenths')
81 tn = string.atof (tn.get_text ())
83 paper.global_staff_size = mm * 72.27 / 25.4
84 # We need the scaling (i.e. the size of staff tenths for everything!
88 def from_tenths (txt):
89 return round_to_two_digits (string.atof (txt) * tenths / 10)
90 def set_paper_variable (varname, parent, element_name):
91 el = parent.get_maybe_exist_named_child (element_name)
92 if el: # Convert to cm from tenths
93 setattr (paper, varname, from_tenths (el.get_text ()))
95 pagelayout = defaults.get_maybe_exist_named_child ('page-layout')
97 # TODO: How can one have different margins for even and odd pages???
98 set_paper_variable ("page_height", pagelayout, 'page-height')
99 set_paper_variable ("page_width", pagelayout, 'page-width')
101 pmargins = pagelayout.get_named_children ('page-margins')
103 set_paper_variable ("left_margin", pm, 'left-margin')
104 set_paper_variable ("right_margin", pm, 'right-margin')
105 set_paper_variable ("bottom_margin", pm, 'bottom-margin')
106 set_paper_variable ("top_margin", pm, 'top-margin')
108 systemlayout = defaults.get_maybe_exist_named_child ('system-layout')
110 sl = systemlayout.get_maybe_exist_named_child ('system-margins')
112 set_paper_variable ("system_left_margin", sl, 'left-margin')
113 set_paper_variable ("system_right_margin", sl, 'right-margin')
114 set_paper_variable ("system_distance", systemlayout, 'system-distance')
115 set_paper_variable ("top_system_distance", systemlayout, 'top-system-distance')
117 stafflayout = defaults.get_named_children ('staff-layout')
118 for sl in stafflayout:
119 nr = getattr (sl, 'number', 1)
120 dist = sl.get_named_child ('staff-distance')
121 #TODO: the staff distance needs to be set in the Staff context!!!
123 # TODO: Finish appearance?, music-font?, word-font?, lyric-font*, lyric-language*
124 appearance = defaults.get_named_child ('appearance')
126 lws = appearance.get_named_children ('line-width')
128 # Possible types are: beam, bracket, dashes,
129 # enclosure, ending, extend, heavy barline, leger,
130 # light barline, octave shift, pedal, slur middle, slur tip,
131 # staff, stem, tie middle, tie tip, tuplet bracket, and wedge
133 w = from_tenths (lw.get_text ())
134 # TODO: Do something with these values!
135 nss = appearance.get_named_children ('note-size')
137 # Possible types are: cue, grace and large
139 sz = from_tenths (ns.get_text ())
140 # TODO: Do something with these values!
141 # <other-appearance> elements have no specified meaning
143 rawmusicfont = defaults.get_named_child ('music-font')
145 # TODO: Convert the font
147 rawwordfont = defaults.get_named_child ('word-font')
149 # TODO: Convert the font
151 rawlyricsfonts = defaults.get_named_children ('lyric-font')
152 for lyricsfont in rawlyricsfonts:
153 # TODO: Convert the font
160 # score information is contained in the <work>, <identification> or <movement-title> tags
161 # extract those into a hash, indexed by proper lilypond header attributes
162 def extract_score_information (tree):
163 header = musicexp.Header ()
164 def set_if_exists (field, value):
166 header.set_field (field, musicxml.escape_ly_output_string (value))
168 movement_title = tree.get_maybe_exist_named_child ('movement-title')
170 set_if_exists ('title', movement_title.get_text ())
171 work = tree.get_maybe_exist_named_child ('work')
173 # Overwrite the title from movement-title with work->title
174 set_if_exists ('title', work.get_work_title ())
175 set_if_exists ('worknumber', work.get_work_number ())
176 set_if_exists ('opus', work.get_opus ())
178 identifications = tree.get_named_children ('identification')
179 for ids in identifications:
180 set_if_exists ('copyright', ids.get_rights ())
181 set_if_exists ('composer', ids.get_composer ())
182 set_if_exists ('arranger', ids.get_arranger ())
183 set_if_exists ('editor', ids.get_editor ())
184 set_if_exists ('poet', ids.get_poet ())
186 set_if_exists ('tagline', ids.get_encoding_software ())
187 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
188 set_if_exists ('encodingdate', ids.get_encoding_date ())
189 set_if_exists ('encoder', ids.get_encoding_person ())
190 set_if_exists ('encodingdescription', ids.get_encoding_description ())
192 set_if_exists ('texidoc', ids.get_file_description ());
194 # Finally, apply the required compatibility modes
195 # Some applications created wrong MusicXML files, so we need to
196 # apply some compatibility mode, e.g. ignoring some features/tags
198 software = ids.get_encoding_software_list ()
200 # Case 1: "Sibelius 5.1" with the "Dolet 3.4 for Sibelius" plugin
201 # is missing all beam ends => ignore all beaming information
202 ignore_beaming_software = {
203 "Dolet 4 for Sibelius, Beta 2": "Dolet 4 for Sibelius, Beta 2",
204 "Dolet 3.5 for Sibelius": "Dolet 3.5 for Sibelius",
205 "Dolet 3.4 for Sibelius": "Dolet 3.4 for Sibelius",
206 "Dolet 3.3 for Sibelius": "Dolet 3.3 for Sibelius",
207 "Dolet 3.2 for Sibelius": "Dolet 3.2 for Sibelius",
208 "Dolet 3.1 for Sibelius": "Dolet 3.1 for Sibelius",
209 "Dolet for Sibelius 1.3": "Dolet for Sibelius 1.3",
210 "Noteworthy Composer": "Noteworthy Composer's nwc2xm[",
213 app_description = ignore_beaming_software.get (s, False);
215 conversion_settings.ignore_beaming = True
216 ly.warning (_ ("Encountered file created by %s, containing "
217 "wrong beaming information. All beaming "
218 "information in the MusicXML file will be "
219 "ignored") % app_description)
221 # TODO: Check for other unsupported features
229 return len (self.start) + len (self.end) == 0
230 def add_start (self, g):
231 self.start[getattr (g, 'number', "1")] = g
232 def add_end (self, g):
233 self.end[getattr (g, 'number', "1")] = g
234 def print_ly (self, printer):
235 ly.warning (_ ("Unprocessed PartGroupInfo %s encountered") % self)
236 def ly_expression (self):
237 ly.warning (_ ("Unprocessed PartGroupInfo %s encountered") % self)
240 def musicxml_step_to_lily (step):
242 return (ord (step) - ord ('A') + 7 - 2) % 7
247 def staff_attributes_to_string_tunings (mxl_attr):
248 details = mxl_attr.get_maybe_exist_named_child ('staff-details')
252 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
254 lines = string.atoi (staff_lines.get_text ())
256 tunings = [musicexp.Pitch()]*lines
257 staff_tunings = details.get_named_children ('staff-tuning')
258 for i in staff_tunings:
262 line = string.atoi (i.line) - 1
267 step = i.get_named_child (u'tuning-step')
268 step = step.get_text ().strip ()
269 p.step = musicxml_step_to_lily (step)
271 octave = i.get_named_child (u'tuning-octave')
272 octave = octave.get_text ().strip ()
273 p.octave = int (octave) - 4
275 alter = i.get_named_child (u'tuning-alter')
277 p.alteration = int (alter.get_text ().strip ())
278 # lilypond seems to use the opposite ordering than MusicXML...
284 def staff_attributes_to_lily_staff (mxl_attr):
286 return musicexp.Staff ()
288 (staff_id, attributes) = mxl_attr.items ()[0]
290 # distinguish by clef:
291 # percussion (percussion and rhythmic), tab, and everything else
293 clef = attributes.get_maybe_exist_named_child ('clef')
295 sign = clef.get_maybe_exist_named_child ('sign')
297 clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
300 details = attributes.get_named_children ('staff-details')
302 staff_lines = d.get_maybe_exist_named_child ('staff-lines')
304 lines = string.atoi (staff_lines.get_text ())
306 # TODO: Handle other staff attributes like staff-space, etc.
309 if clef_sign == "percussion" and lines == 1:
310 staff = musicexp.RhythmicStaff ()
311 elif clef_sign == "percussion":
312 staff = musicexp.DrumStaff ()
313 # staff.drum_style_table = ???
314 elif clef_sign == "tab":
315 staff = musicexp.TabStaff ()
316 staff.string_tunings = staff_attributes_to_string_tunings (attributes)
317 # staff.tablature_format = ???
319 staff = musicexp.Staff ()
320 # TODO: Handle case with lines <> 5!
322 staff.add_context_modification ("\\override StaffSymbol #'line-count = #%s" % lines)
328 def extract_score_structure (part_list, staffinfo):
329 score = musicexp.Score ()
330 structure = musicexp.StaffGroup (None)
331 score.set_contents (structure)
336 def read_score_part (el):
337 if not isinstance (el, musicxml.Score_part):
339 # Depending on the attributes of the first measure, we create different
340 # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
341 staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
345 partname = el.get_maybe_exist_named_child ('part-name')
346 # Finale gives unnamed parts the name "MusicXML Part" automatically!
347 if partname and partname.get_text() != "MusicXML Part":
348 staff.instrument_name = partname.get_text ()
349 # part-name-display overrides part-name!
350 partname = el.get_maybe_exist_named_child ("part-name-display")
352 staff.instrument_name = extract_display_text (partname)
354 partdisplay = el.get_maybe_exist_named_child ('part-abbreviation')
356 staff.short_instrument_name = partdisplay.get_text ()
357 # part-abbreviation-display overrides part-abbreviation!
358 partdisplay = el.get_maybe_exist_named_child ("part-abbreviation-display")
360 staff.short_instrument_name = extract_display_text (partdisplay)
361 # TODO: Read in the MIDI device / instrument
365 def read_score_group (el):
366 if not isinstance (el, musicxml.Part_group):
368 group = musicexp.StaffGroup ()
369 if hasattr (el, 'number'):
372 #currentgroups_dict[id] = group
373 #currentgroups.append (id)
374 if el.get_maybe_exist_named_child ('group-name'):
375 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
376 if el.get_maybe_exist_named_child ('group-abbreviation'):
377 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
378 if el.get_maybe_exist_named_child ('group-symbol'):
379 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
380 if el.get_maybe_exist_named_child ('group-barline'):
381 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
385 parts_groups = part_list.get_all_children ()
387 # the start/end group tags are not necessarily ordered correctly and groups
388 # might even overlap, so we can't go through the children sequentially!
390 # 1) Replace all Score_part objects by their corresponding Staff objects,
391 # also collect all group start/stop points into one PartGroupInfo object
393 group_info = PartGroupInfo ()
394 for el in parts_groups:
395 if isinstance (el, musicxml.Score_part):
396 if not group_info.is_empty ():
397 staves.append (group_info)
398 group_info = PartGroupInfo ()
399 staff = read_score_part (el)
401 staves.append (staff)
402 elif isinstance (el, musicxml.Part_group):
403 if el.type == "start":
404 group_info.add_start (el)
405 elif el.type == "stop":
406 group_info.add_end (el)
407 if not group_info.is_empty ():
408 staves.append (group_info)
410 # 2) Now, detect the groups:
413 while pos < len (staves):
415 if isinstance (el, PartGroupInfo):
417 if len (group_starts) > 0:
418 prev_start = group_starts[-1]
419 elif len (el.end) > 0: # no group to end here
421 if len (el.end) > 0: # closes an existing group
422 ends = el.end.keys ()
423 prev_started = staves[prev_start].start.keys ()
425 intersection = filter(lambda x:x in ends, prev_started)
426 if len (intersection) > 0:
427 grpid = intersection[0]
429 # Close the last started group
430 grpid = staves[prev_start].start.keys () [0]
431 # Find the corresponding closing tag and remove it!
434 while j < len (staves) and not foundclosing:
435 if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
437 del staves[j].end[grpid]
438 if staves[j].is_empty ():
441 grpobj = staves[prev_start].start[grpid]
442 group = read_score_group (grpobj)
443 # remove the id from both the start and end
444 if el.end.has_key (grpid):
446 del staves[prev_start].start[grpid]
449 # replace the staves with the whole group
450 for j in staves[(prev_start + 1):pos]:
451 group.append_staff (j)
452 del staves[(prev_start + 1):pos]
453 staves.insert (prev_start + 1, group)
454 # reset pos so that we continue at the correct position
456 # remove an empty start group
457 if staves[prev_start].is_empty ():
458 del staves[prev_start]
459 group_starts.remove (prev_start)
461 elif len (el.start) > 0: # starts new part groups
462 group_starts.append (pos)
465 if len (staves) == 1:
468 structure.append_staff (i)
472 def musicxml_duration_to_lily (mxl_note):
473 # if the note has no Type child, then that method returns None. In that case,
474 # use the <duration> tag instead. If that doesn't exist, either -> Error
475 dur = mxl_note.get_duration_info ()
477 d = musicexp.Duration ()
478 d.duration_log = dur[0]
480 # Grace notes by specification have duration 0, so no time modification
481 # factor is possible. It even messes up the output with *0/1
482 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
483 d.factor = mxl_note._duration / d.get_length ()
487 if mxl_note._duration > 0:
488 return rational_to_lily_duration (mxl_note._duration)
490 mxl_note.message (_ ("Encountered note at %s without type and duration (=%s)") % (mxl_note.start, mxl_note._duration) )
494 def rational_to_lily_duration (rational_len):
495 d = musicexp.Duration ()
497 rational_len.normalize_self ()
498 d_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)
500 # Duration of the form 1/2^n or 3/2^n can be converted to a simple lilypond duration
501 dots = {1: 0, 3: 1, 7: 2, 15: 3, 31: 4, 63: 5, 127: 6}.get (rational_len.numerator(), -1)
502 if ( d_log >= dots >= 0 ):
503 # account for the dots!
504 d.duration_log = d_log - dots
507 d.duration_log = d_log
508 d.factor = Rational (rational_len.numerator ())
510 ly.warning (_ ("Encountered rational duration with denominator %s, "
511 "unable to convert to lilypond duration") %
512 rational_len.denominator ())
513 # TODO: Test the above error message
518 def musicxml_partial_to_lily (partial_len):
520 p = musicexp.Partial ()
521 p.partial = rational_to_lily_duration (partial_len)
526 # Detect repeats and alternative endings in the chord event list (music_list)
527 # and convert them to the corresponding musicexp objects, containing nested
529 def group_repeats (music_list):
530 repeat_replaced = True
533 # Walk through the list of expressions, looking for repeat structure
534 # (repeat start/end, corresponding endings). If we find one, try to find the
535 # last event of the repeat, replace the whole structure and start over again.
536 # For nested repeats, as soon as we encounter another starting repeat bar,
537 # treat that one first, and start over for the outer repeat.
538 while repeat_replaced and i < 100:
540 repeat_start = -1 # position of repeat start / end
541 repeat_end = -1 # position of repeat start / end
543 ending_start = -1 # position of current ending start
544 endings = [] # list of already finished endings
546 last = len (music_list) - 1
547 repeat_replaced = False
549 while pos < len (music_list) and not repeat_replaced:
551 repeat_finished = False
552 if isinstance (e, RepeatMarker):
553 if not repeat_times and e.times:
554 repeat_times = e.times
555 if e.direction == -1:
557 repeat_finished = True
563 elif e.direction == 1:
569 elif isinstance (e, EndingMarker):
570 if e.direction == -1:
576 elif e.direction == 1:
579 endings.append ([ending_start, pos])
582 elif not isinstance (e, musicexp.BarLine):
583 # As soon as we encounter an element when repeat start and end
584 # is set and we are not inside an alternative ending,
585 # this whole repeat structure is finished => replace it
586 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
587 repeat_finished = True
589 # Finish off all repeats without explicit ending bar (e.g. when
590 # we convert only one page of a multi-page score with repeats)
591 if pos == last and repeat_start >= 0:
592 repeat_finished = True
596 if ending_start >= 0:
597 endings.append ([ending_start, pos])
601 # We found the whole structure replace it!
602 r = musicexp.RepeatedMusic ()
603 if repeat_times <= 0:
605 r.repeat_count = repeat_times
606 # don't erase the first element for "implicit" repeats (i.e. no
607 # starting repeat bars at the very beginning)
608 start = repeat_start+1
609 if repeat_start == music_start:
611 r.set_music (music_list[start:repeat_end])
612 for (start, end) in endings:
613 s = musicexp.SequentialMusic ()
614 s.elements = music_list[start+1:end]
616 del music_list[repeat_start:final_marker+1]
617 music_list.insert (repeat_start, r)
618 repeat_replaced = True
620 # TODO: Implement repeats until the end without explicit ending bar
624 # Extract the settings for tuplets from the <notations><tuplet> and the
625 # <time-modification> elements of the note:
626 def musicxml_tuplet_to_lily (tuplet_elt, time_modification):
627 tsm = musicexp.TimeScaledMusic ()
629 if time_modification:
630 fraction = time_modification.get_fraction ()
631 tsm.numerator = fraction[0]
632 tsm.denominator = fraction[1]
635 normal_type = tuplet_elt.get_normal_type ()
636 if not normal_type and time_modification:
637 normal_type = time_modification.get_normal_type ()
638 if not normal_type and time_modification:
639 note = time_modification.get_parent ()
641 normal_type = note.get_duration_info ()
643 normal_note = musicexp.Duration ()
644 (normal_note.duration_log, normal_note.dots) = normal_type
645 tsm.normal_type = normal_note
647 actual_type = tuplet_elt.get_actual_type ()
649 actual_note = musicexp.Duration ()
650 (actual_note.duration_log, actual_note.dots) = actual_type
651 tsm.actual_type = actual_note
653 # Obtain non-default nrs of notes from the tuplet object!
654 tsm.display_numerator = tuplet_elt.get_normal_nr ()
655 tsm.display_denominator = tuplet_elt.get_actual_nr ()
658 if hasattr (tuplet_elt, 'bracket') and tuplet_elt.bracket == "no":
659 tsm.display_bracket = None
660 elif hasattr (tuplet_elt, 'line-shape') and getattr (tuplet_elt, 'line-shape') == "curved":
661 tsm.display_bracket = "curved"
663 tsm.display_bracket = "bracket"
665 display_values = {"none": None, "actual": "actual", "both": "both"}
666 if hasattr (tuplet_elt, "show-number"):
667 tsm.display_number = display_values.get (getattr (tuplet_elt, "show-number"), "actual")
669 if hasattr (tuplet_elt, "show-type"):
670 tsm.display_type = display_values.get (getattr (tuplet_elt, "show-type"), None)
675 def group_tuplets (music_list, events):
678 """Collect Musics from
679 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
687 for (ev_chord, tuplet_elt, time_modification) in events:
688 while (j < len (music_list)):
689 if music_list[j] == ev_chord:
693 if hasattr (tuplet_elt, 'number'):
694 nr = getattr (tuplet_elt, 'number')
695 if tuplet_elt.type == 'start':
696 tuplet_object = musicxml_tuplet_to_lily (tuplet_elt, time_modification)
697 tuplet_info = [j, None, tuplet_object]
698 indices.append (tuplet_info)
699 brackets[nr] = tuplet_info
700 elif tuplet_elt.type == 'stop':
701 bracket_info = brackets.get (nr, None)
703 bracket_info[1] = j # Set the ending position to j
708 for (i1, i2, tsm) in indices:
712 new_list.extend (music_list[last:i1])
713 seq = musicexp.SequentialMusic ()
715 seq.elements = music_list[i1:last]
719 new_list.append (tsm)
720 #TODO: Handle nested tuplets!!!!
722 new_list.extend (music_list[last:])
726 def musicxml_clef_to_lily (attributes):
727 change = musicexp.ClefChange ()
728 (change.type, change.position, change.octave) = attributes.get_clef_information ()
731 def musicxml_time_to_lily (attributes):
732 sig = attributes.get_time_signature ()
735 change = musicexp.TimeSignatureChange()
736 change.fractions = sig
738 time_elm = attributes.get_maybe_exist_named_child ('time')
739 if time_elm and hasattr (time_elm, 'symbol'):
740 change.style = { 'single-number': "'single-digit",
743 'normal': "'()"}.get (time_elm.symbol, "'()")
747 # TODO: Handle senza-misura measures
748 # TODO: Handle hidden time signatures (print-object="no")
749 # TODO: What shall we do if the symbol clashes with the sig? e.g. "cut"
750 # with 3/8 or "single-number" with (2+3)/8 or 3/8+2/4?
754 def musicxml_key_to_lily (attributes):
755 key_sig = attributes.get_key_signature ()
756 if not key_sig or not (isinstance (key_sig, list) or isinstance (key_sig, tuple)):
757 ly.warning (_ ("Unable to extract key signature!"))
760 change = musicexp.KeySignatureChange()
762 if len (key_sig) == 2 and not isinstance (key_sig[0], list):
763 # standard key signature, (fifths, mode)
764 (fifths, mode) = key_sig
767 start_pitch = musicexp.Pitch ()
768 start_pitch.octave = 0
782 start_pitch.alteration = a
784 ly.warning (_ ("unknown mode %s, expecting 'major' or 'minor' "
785 "or a church mode!") % mode)
787 fifth = musicexp.Pitch()
793 for x in range (fifths):
794 start_pitch = start_pitch.transposed (fifth)
795 change.tonic = start_pitch
798 # Non-standard key signature of the form [[step,alter<,octave>],...]
799 # MusicXML contains C,D,E,F,G,A,B as steps, lily uses 0-7, so convert
802 k[0] = musicxml_step_to_lily (k[0])
803 alterations.append (k)
804 change.non_standard_alterations = alterations
807 def musicxml_transpose_to_lily (attributes):
808 transpose = attributes.get_transposition ()
812 shift = musicexp.Pitch ()
813 octave_change = transpose.get_maybe_exist_named_child ('octave-change')
815 shift.octave = string.atoi (octave_change.get_text ())
816 chromatic_shift = string.atoi (transpose.get_named_child ('chromatic').get_text ())
817 chromatic_shift_normalized = chromatic_shift % 12;
818 (shift.step, shift.alteration) = [
819 (0,0), (0,1), (1,0), (2,-1), (2,0),
820 (3,0), (3,1), (4,0), (5,-1), (5,0),
821 (6,-1), (6,0)][chromatic_shift_normalized];
823 shift.octave += (chromatic_shift - chromatic_shift_normalized) / 12
825 diatonic = transpose.get_maybe_exist_named_child ('diatonic')
827 diatonic_step = string.atoi (diatonic.get_text ()) % 7
828 if diatonic_step != shift.step:
829 # We got the alter incorrect!
830 old_semitones = shift.semitones ()
831 shift.step = diatonic_step
832 new_semitones = shift.semitones ()
833 shift.alteration += old_semitones - new_semitones
835 transposition = musicexp.Transposition ()
836 transposition.pitch = musicexp.Pitch ().transposed (shift)
839 def musicxml_staff_details_to_lily (attributes):
840 details = attributes.get_maybe_exist_named_child ('staff-details')
844 ## TODO: Handle staff-type, staff-lines, staff-tuning, capo, staff-size
847 stafflines = details.get_maybe_exist_named_child ('staff-lines')
849 lines = string.atoi (stafflines.get_text ());
850 lines_event = musicexp.StaffLinesEvent (lines);
851 ret.append (lines_event);
856 def musicxml_attributes_to_lily (attrs):
859 'clef': musicxml_clef_to_lily,
860 'time': musicxml_time_to_lily,
861 'key': musicxml_key_to_lily,
862 'transpose': musicxml_transpose_to_lily,
863 'staff-details': musicxml_staff_details_to_lily,
865 for (k, func) in attr_dispatch.items ():
866 children = attrs.get_named_children (k)
869 if isinstance (ev, list):
877 def extract_display_text (el):
878 child = el.get_maybe_exist_named_child ("display-text")
880 return child.get_text ()
885 def musicxml_print_to_lily (el):
886 # TODO: Implement other print attributes
887 # <!ELEMENT print (page-layout?, system-layout?, staff-layout*,
888 # measure-layout?, measure-numbering?, part-name-display?,
889 # part-abbreviation-display?)>
891 # staff-spacing %tenths; #IMPLIED
892 # new-system %yes-no; #IMPLIED
893 # new-page %yes-no-number; #IMPLIED
894 # blank-page NMTOKEN #IMPLIED
895 # page-number CDATA #IMPLIED
898 if (hasattr (el, "new-system") and conversion_settings.convert_page_layout):
899 val = getattr (el, "new-system")
901 elts.append (musicexp.Break ("break"))
902 if (hasattr (el, "new-page") and conversion_settings.convert_page_layout):
903 val = getattr (el, "new-page")
905 elts.append (musicexp.Break ("pageBreak"))
906 child = el.get_maybe_exist_named_child ("part-name-display")
908 elts.append (musicexp.SetEvent ("Staff.instrumentName",
909 "\"%s\"" % extract_display_text (child)))
910 child = el.get_maybe_exist_named_child ("part-abbreviation-display")
912 elts.append (musicexp.SetEvent ("Staff.shortInstrumentName",
913 "\"%s\"" % extract_display_text (child)))
917 class Marker (musicexp.Music):
921 def print_ly (self, printer):
922 ly.warning (_ ("Encountered unprocessed marker %s\n") % self)
924 def ly_expression (self):
926 class RepeatMarker (Marker):
928 Marker.__init__ (self)
930 class EndingMarker (Marker):
933 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
934 # and to RepeatMarker and EndingMarker objects for repeat and
935 # alternatives start/stops
936 def musicxml_barline_to_lily (barline):
937 # retval contains all possible markers in the order:
938 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
940 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
941 repeat_element = barline.get_maybe_exist_named_child ("repeat")
942 ending_element = barline.get_maybe_exist_named_child ("ending")
946 bartype = bartype_element.get_text ()
948 if repeat_element and hasattr (repeat_element, 'direction'):
949 repeat = RepeatMarker ()
950 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
952 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
953 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
955 if hasattr (repeat_element, 'times'):
957 repeat.times = int (repeat_element.times)
960 repeat.event = barline
961 if repeat.direction == -1:
966 if ending_element and hasattr (ending_element, 'type'):
967 ending = EndingMarker ()
968 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
969 ending.event = barline
970 if ending.direction == -1:
976 b = musicexp.BarLine ()
980 return retval.values ()
982 spanner_event_dict = {
983 'beam' : musicexp.BeamEvent,
984 'dashes' : musicexp.TextSpannerEvent,
985 'bracket' : musicexp.BracketSpannerEvent,
986 'glissando' : musicexp.GlissandoEvent,
987 'octave-shift' : musicexp.OctaveShiftEvent,
988 'pedal' : musicexp.PedalEvent,
989 'slide' : musicexp.GlissandoEvent,
990 'slur' : musicexp.SlurEvent,
991 'wavy-line' : musicexp.TrillSpanEvent,
992 'wedge' : musicexp.HairpinEvent
994 spanner_type_dict = {
1008 def musicxml_spanner_to_lily_event (mxl_event):
1011 name = mxl_event.get_name()
1012 func = spanner_event_dict.get (name)
1016 ly.warning (_ ('unknown span event %s') % mxl_event)
1019 type = mxl_event.get_type ()
1020 span_direction = spanner_type_dict.get (type)
1021 # really check for None, because some types will be translated to 0, which
1022 # would otherwise also lead to the unknown span warning
1023 if span_direction != None:
1024 ev.span_direction = span_direction
1026 ly.warning (_ ('unknown span type %s for %s') % (type, name))
1028 ev.set_span_type (type)
1029 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
1031 # assign the size, which is used for octave-shift, etc.
1032 ev.size = mxl_event.get_size ()
1036 def musicxml_direction_to_indicator (direction):
1037 return { "above": 1, "upright": 1, "up": 1, "below": -1, "downright": -1, "down": -1, "inverted": -1 }.get (direction, 0)
1039 def musicxml_fermata_to_lily_event (mxl_event):
1040 ev = musicexp.ArticulationEvent ()
1041 txt = mxl_event.get_text ()
1042 # The contents of the element defined the shape, possible are normal, angled and square
1043 ev.type = { "angled": "shortfermata", "square": "longfermata" }.get (txt, "fermata")
1044 if hasattr (mxl_event, 'type'):
1045 dir = musicxml_direction_to_indicator (mxl_event.type)
1046 if dir and options.convert_directions:
1047 ev.force_direction = dir
1050 def musicxml_arpeggiate_to_lily_event (mxl_event):
1051 ev = musicexp.ArpeggioEvent ()
1052 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1055 def musicxml_nonarpeggiate_to_lily_event (mxl_event):
1056 ev = musicexp.ArpeggioEvent ()
1057 ev.non_arpeggiate = True
1058 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1061 def musicxml_tremolo_to_lily_event (mxl_event):
1062 ev = musicexp.TremoloEvent ()
1063 txt = mxl_event.get_text ()
1070 def musicxml_falloff_to_lily_event (mxl_event):
1071 ev = musicexp.BendEvent ()
1075 def musicxml_doit_to_lily_event (mxl_event):
1076 ev = musicexp.BendEvent ()
1080 def musicxml_bend_to_lily_event (mxl_event):
1081 ev = musicexp.BendEvent ()
1082 ev.alter = mxl_event.bend_alter ()
1085 def musicxml_caesura_to_lily_event (mxl_event):
1086 ev = musicexp.MarkupEvent ()
1087 # FIXME: default to straight or curved caesura?
1088 ev.contents = "\\musicglyph #\"scripts.caesura.straight\""
1089 ev.force_direction = 1
1092 def musicxml_fingering_event (mxl_event):
1093 ev = musicexp.ShortArticulationEvent ()
1094 ev.type = mxl_event.get_text ()
1097 def musicxml_string_event (mxl_event):
1098 ev = musicexp.NoDirectionArticulationEvent ()
1099 ev.type = mxl_event.get_text ()
1102 def musicxml_accidental_mark (mxl_event):
1103 ev = musicexp.MarkupEvent ()
1104 contents = { "sharp": "\\sharp",
1105 "natural": "\\natural",
1107 "double-sharp": "\\doublesharp",
1108 "sharp-sharp": "\\sharp\\sharp",
1109 "flat-flat": "\\flat\\flat",
1110 "flat-flat": "\\doubleflat",
1111 "natural-sharp": "\\natural\\sharp",
1112 "natural-flat": "\\natural\\flat",
1113 "quarter-flat": "\\semiflat",
1114 "quarter-sharp": "\\semisharp",
1115 "three-quarters-flat": "\\sesquiflat",
1116 "three-quarters-sharp": "\\sesquisharp",
1117 }.get (mxl_event.get_text ())
1119 ev.contents = contents
1124 # translate articulations, ornaments and other notations into ArticulationEvents
1126 # -) string (ArticulationEvent with that name)
1127 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
1128 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
1129 # TODO: Some translations are missing!
1130 articulations_dict = {
1131 "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
1132 "accidental-mark": musicxml_accidental_mark,
1133 "bend": musicxml_bend_to_lily_event,
1134 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
1135 "caesura": musicxml_caesura_to_lily_event,
1136 #"delayed-turn": "?",
1137 "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
1138 "doit": musicxml_doit_to_lily_event,
1139 #"double-tongue": "?",
1140 "down-bow": "downbow",
1141 "falloff": musicxml_falloff_to_lily_event,
1142 "fingering": musicxml_fingering_event,
1143 #"fingernails": "?",
1146 "harmonic": "flageolet",
1148 "inverted-mordent": "prall",
1149 "inverted-turn": "reverseturn",
1150 "mordent": "mordent",
1151 "open-string": "open",
1158 "snap-pizzicato": "snappizzicato",
1160 "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
1161 "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
1162 "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
1164 "string": musicxml_string_event,
1165 "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
1167 "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
1168 "thumb-position": "thumb",
1171 "tremolo": musicxml_tremolo_to_lily_event,
1172 "trill-mark": "trill",
1173 #"triple-tongue": "?",
1178 articulation_spanners = [ "wavy-line" ]
1180 def musicxml_articulation_to_lily_event (mxl_event):
1181 # wavy-line elements are treated as trill spanners, not as articulation ornaments
1182 if mxl_event.get_name () in articulation_spanners:
1183 return musicxml_spanner_to_lily_event (mxl_event)
1185 tmp_tp = articulations_dict.get (mxl_event.get_name ())
1189 if isinstance (tmp_tp, str):
1190 ev = musicexp.ArticulationEvent ()
1192 elif isinstance (tmp_tp, tuple):
1196 ev = tmp_tp (mxl_event)
1198 # Some articulations use the type attribute, other the placement...
1200 if hasattr (mxl_event, 'type') and options.convert_directions:
1201 dir = musicxml_direction_to_indicator (mxl_event.type)
1202 if hasattr (mxl_event, 'placement') and options.convert_directions:
1203 dir = musicxml_direction_to_indicator (mxl_event.placement)
1205 ev.force_direction = dir
1210 def musicxml_dynamics_to_lily_event (dynentry):
1211 dynamics_available = (
1212 "ppppp", "pppp", "ppp", "pp", "p", "mp", "mf",
1213 "f", "ff", "fff", "ffff", "fp", "sf", "sff", "sp", "spp", "sfz", "rfz" )
1214 dynamicsname = dynentry.get_name ()
1215 if dynamicsname == "other-dynamics":
1216 dynamicsname = dynentry.get_text ()
1217 if not dynamicsname or dynamicsname=="#text":
1220 if not dynamicsname in dynamics_available:
1221 # Get rid of - in tag names (illegal in ly tags!)
1222 dynamicstext = dynamicsname
1223 dynamicsname = string.replace (dynamicsname, "-", "")
1224 additional_definitions[dynamicsname] = dynamicsname + \
1225 " = #(make-dynamic-script \"" + dynamicstext + "\")"
1226 needed_additional_definitions.append (dynamicsname)
1227 event = musicexp.DynamicsEvent ()
1228 event.type = dynamicsname
1231 # Convert single-color two-byte strings to numbers 0.0 - 1.0
1232 def hexcolorval_to_nr (hex_val):
1234 v = int (hex_val, 16)
1241 def hex_to_color (hex_val):
1242 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)
1244 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
1248 def musicxml_words_to_lily_event (words):
1249 event = musicexp.TextEvent ()
1250 text = words.get_text ()
1251 text = re.sub ('^ *\n? *', '', text)
1252 text = re.sub (' *\n? *$', '', text)
1255 if hasattr (words, 'default-y') and options.convert_directions:
1256 offset = getattr (words, 'default-y')
1258 off = string.atoi (offset)
1260 event.force_direction = 1
1262 event.force_direction = -1
1264 event.force_direction = 0
1266 if hasattr (words, 'font-weight'):
1267 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
1269 event.markup += font_weight
1271 if hasattr (words, 'font-size'):
1272 size = getattr (words, 'font-size')
1274 "xx-small": '\\teeny',
1275 "x-small": '\\tiny',
1279 "x-large": '\\huge',
1280 "xx-large": '\\larger\\huge'
1283 event.markup += font_size
1285 if hasattr (words, 'color'):
1286 color = getattr (words, 'color')
1287 rgb = hex_to_color (color)
1289 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
1291 if hasattr (words, 'font-style'):
1292 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
1294 event.markup += font_style
1296 # TODO: How should I best convert the font-family attribute?
1298 # TODO: How can I represent the underline, overline and line-through
1299 # attributes in LilyPond? Values of these attributes indicate
1300 # the number of lines
1305 # convert accordion-registration to lilypond.
1306 # Since lilypond does not have any built-in commands, we need to create
1307 # the markup commands manually and define our own variables.
1308 # Idea was taken from: http://lsr.dsi.unimi.it/LSR/Item?id=194
1309 def musicxml_accordion_to_markup (mxl_event):
1310 commandname = "accReg"
1313 high = mxl_event.get_maybe_exist_named_child ('accordion-high')
1316 command += """\\combine
1317 \\raise #2.5 \\musicglyph #\"accordion.dot\"
1319 middle = mxl_event.get_maybe_exist_named_child ('accordion-middle')
1321 # By default, use one dot (when no or invalid content is given). The
1322 # MusicXML spec is quiet about this case...
1325 txt = string.atoi (middle.get_text ())
1329 commandname += "MMM"
1330 command += """\\combine
1331 \\raise #1.5 \\musicglyph #\"accordion.dot\"
1333 \\raise #1.5 \\translate #(cons 1 0) \\musicglyph #\"accordion.dot\"
1335 \\raise #1.5 \\translate #(cons -1 0) \\musicglyph #\"accordion.dot\"
1339 command += """\\combine
1340 \\raise #1.5 \\translate #(cons 0.5 0) \\musicglyph #\"accordion.dot\"
1342 \\raise #1.5 \\translate #(cons -0.5 0) \\musicglyph #\"accordion.dot\"
1346 command += """\\combine
1347 \\raise #1.5 \\musicglyph #\"accordion.dot\"
1349 low = mxl_event.get_maybe_exist_named_child ('accordion-low')
1352 command += """\\combine
1353 \\raise #0.5 \musicglyph #\"accordion.dot\"
1356 command += "\musicglyph #\"accordion.discant\""
1357 command = "\\markup { \\normalsize %s }" % command
1358 # Define the newly built command \accReg[H][MMM][L]
1359 additional_definitions[commandname] = "%s = %s" % (commandname, command)
1360 needed_additional_definitions.append (commandname)
1361 return "\\%s" % commandname
1363 def musicxml_accordion_to_ly (mxl_event):
1364 txt = musicxml_accordion_to_markup (mxl_event)
1366 ev = musicexp.MarkEvent (txt)
1371 def musicxml_rehearsal_to_ly_mark (mxl_event):
1372 text = mxl_event.get_text ()
1375 # default is boxed rehearsal marks!
1377 if hasattr (mxl_event, 'enclosure'):
1378 encl = {"none": None, "square": "box", "circle": "circle" }.get (mxl_event.enclosure, None)
1380 text = "\\%s { %s }" % (encl, text)
1381 ev = musicexp.MarkEvent ("\\markup { %s }" % text)
1384 def musicxml_harp_pedals_to_ly (mxl_event):
1386 result = "\\harp-pedal #\""
1387 for t in mxl_event.get_named_children ('pedal-tuning'):
1388 alter = t.get_named_child ('pedal-alter')
1390 val = int (alter.get_text ().strip ())
1391 result += {1: "v", 0: "-", -1: "^"}.get (val, "")
1395 ev = musicexp.MarkupEvent ()
1396 ev.contents = result + "\""
1399 def musicxml_eyeglasses_to_ly (mxl_event):
1400 needed_additional_definitions.append ("eyeglasses")
1401 return musicexp.MarkEvent ("\\markup { \\eyeglasses }")
1403 def next_non_hash_index (lst, pos):
1405 while pos < len (lst) and isinstance (lst[pos], musicxml.Hash_text):
1409 def musicxml_metronome_to_ly (mxl_event):
1410 children = mxl_event.get_all_children ()
1415 index = next_non_hash_index (children, index)
1416 if isinstance (children[index], musicxml.BeatUnit):
1417 # first form of metronome-mark, using unit and beats/min or other unit
1418 ev = musicexp.TempoMark ()
1419 if hasattr (mxl_event, 'parentheses'):
1420 ev.set_parentheses (mxl_event.parentheses == "yes")
1422 d = musicexp.Duration ()
1423 d.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1424 index = next_non_hash_index (children, index)
1425 if isinstance (children[index], musicxml.BeatUnitDot):
1427 index = next_non_hash_index (children, index)
1428 ev.set_base_duration (d)
1429 if isinstance (children[index], musicxml.BeatUnit):
1430 # Form "note = newnote"
1431 newd = musicexp.Duration ()
1432 newd.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1433 index = next_non_hash_index (children, index)
1434 if isinstance (children[index], musicxml.BeatUnitDot):
1436 index = next_non_hash_index (children, index)
1437 ev.set_new_duration (newd)
1438 elif isinstance (children[index], musicxml.PerMinute):
1441 beats = int (children[index].get_text ())
1442 ev.set_beats_per_minute (beats)
1446 ly.warning (_ ("Unknown metronome mark, ignoring"))
1450 #TODO: Implement the other (more complex) way for tempo marks!
1451 ly.warning (_ ("Metronome marks with complex relations (<metronome-note> in MusicXML) are not yet implemented."))
1454 # translate directions into Events, possible values:
1455 # -) string (MarkEvent with that command)
1456 # -) function (function(mxl_event) needs to return a full Event-derived object
1457 # -) (class, name) (like string, only that a different class than MarkEvent is used)
1459 'accordion-registration' : musicxml_accordion_to_ly,
1460 'coda' : (musicexp.MusicGlyphMarkEvent, "coda"),
1463 'eyeglasses': musicxml_eyeglasses_to_ly,
1464 'harp-pedals' : musicxml_harp_pedals_to_ly,
1466 'metronome' : musicxml_metronome_to_ly,
1467 'rehearsal' : musicxml_rehearsal_to_ly_mark,
1468 # 'scordatura' : ???
1469 'segno' : (musicexp.MusicGlyphMarkEvent, "segno"),
1470 'words' : musicxml_words_to_lily_event,
1472 directions_spanners = [ 'octave-shift', 'pedal', 'wedge', 'dashes', 'bracket' ]
1474 def musicxml_direction_to_lily (n):
1475 # TODO: Handle the <staff> element!
1477 # placement applies to all children!
1479 if hasattr (n, 'placement') and options.convert_directions:
1480 dir = musicxml_direction_to_indicator (n.placement)
1481 dirtype_children = []
1482 # TODO: The direction-type is used for grouping (e.g. dynamics with text),
1483 # so we can't simply flatten them out!
1484 for dt in n.get_typed_children (musicxml.DirType):
1485 dirtype_children += dt.get_all_children ()
1487 for entry in dirtype_children:
1488 # backets, dashes, octave shifts. pedal marks, hairpins etc. are spanners:
1489 if entry.get_name() in directions_spanners:
1490 event = musicxml_spanner_to_lily_event (entry)
1495 # now treat all the "simple" ones, that can be translated using the dict
1497 tmp_tp = directions_dict.get (entry.get_name (), None)
1498 if isinstance (tmp_tp, str): # string means MarkEvent
1499 ev = musicexp.MarkEvent (tmp_tp)
1500 elif isinstance (tmp_tp, tuple): # tuple means (EventClass, "text")
1501 ev = tmp_tp[0] (tmp_tp[1])
1505 # TODO: set the correct direction! Unfortunately, \mark in ly does
1506 # not seem to support directions!
1507 ev.force_direction = dir
1511 if entry.get_name () == "dynamics":
1512 for dynentry in entry.get_all_children ():
1513 ev = musicxml_dynamics_to_lily_event (dynentry)
1519 def musicxml_frame_to_lily_event (frame):
1520 ev = musicexp.FretEvent ()
1521 ev.strings = frame.get_strings ()
1522 ev.frets = frame.get_frets ()
1523 #offset = frame.get_first_fret () - 1
1525 for fn in frame.get_named_children ('frame-note'):
1526 fret = fn.get_fret ()
1529 el = [ fn.get_string (), fret ]
1530 fingering = fn.get_fingering ()
1532 el.append (fingering)
1533 ev.elements.append (el)
1536 barre[0] = el[0] # start string
1537 barre[2] = el[1] # fret
1539 barre[1] = el[0] # end string
1544 def musicxml_harmony_to_lily (n):
1546 for f in n.get_named_children ('frame'):
1547 ev = musicxml_frame_to_lily_event (f)
1553 notehead_styles_dict = {
1555 'triangle': '\'triangle',
1556 'diamond': '\'diamond',
1557 'square': '\'la', # TODO: Proper squared note head
1558 'cross': None, # TODO: + shaped note head
1560 'circle-x': '\'xcircle',
1561 'inverted triangle': None, # TODO: Implement
1562 'arrow down': None, # TODO: Implement
1563 'arrow up': None, # TODO: Implement
1564 'slashed': None, # TODO: Implement
1565 'back slashed': None, # TODO: Implement
1567 'cluster': None, # TODO: Implement
1578 def musicxml_notehead_to_lily (nh):
1582 style = notehead_styles_dict.get (nh.get_text ().strip (), None)
1583 style_elm = musicexp.NotestyleEvent ()
1585 style_elm.style = style
1586 if hasattr (nh, 'filled'):
1587 style_elm.filled = (getattr (nh, 'filled') == "yes")
1588 if style_elm.style or (style_elm.filled != None):
1589 styles.append (style_elm)
1592 if hasattr (nh, 'parentheses') and (nh.parentheses == "yes"):
1593 styles.append (musicexp.ParenthesizeEvent ())
1597 def musicxml_chordpitch_to_lily (mxl_cpitch):
1598 r = musicexp.ChordPitch ()
1599 r.alteration = mxl_cpitch.get_alteration ()
1600 r.step = musicxml_step_to_lily (mxl_cpitch.get_step ())
1606 'augmented': 'aug5',
1607 'diminished': 'dim5',
1610 'dominant-seventh': '7',
1611 'major-seventh': 'maj7',
1612 'minor-seventh': 'm7',
1613 'diminished-seventh': 'dim7',
1614 'augmented-seventh': 'aug7',
1615 'half-diminished': 'dim5m7',
1616 'major-minor': 'maj7m5',
1619 'minor-sixth': 'm6',
1621 'dominant-ninth': '9',
1622 'major-ninth': 'maj9',
1623 'minor-ninth': 'm9',
1624 # 11ths (usually as the basis for alteration):
1625 'dominant-11th': '11',
1626 'major-11th': 'maj11',
1627 'minor-11th': 'm11',
1628 # 13ths (usually as the basis for alteration):
1629 'dominant-13th': '13.11',
1630 'major-13th': 'maj13.11',
1631 'minor-13th': 'm13',
1633 'suspended-second': 'sus2',
1634 'suspended-fourth': 'sus4',
1635 # Functional sixths:
1637 #'Neapolitan': '???',
1642 #'pedal': '???',(pedal-point bass)
1649 def musicxml_chordkind_to_lily (kind):
1650 res = chordkind_dict.get (kind, None)
1651 # Check for None, since a major chord is converted to ''
1653 ly.warning (_ ("Unable to convert chord type %s to lilypond.") % kind)
1656 def musicxml_harmony_to_lily_chordname (n):
1658 root = n.get_maybe_exist_named_child ('root')
1660 ev = musicexp.ChordNameEvent ()
1661 ev.root = musicxml_chordpitch_to_lily (root)
1662 kind = n.get_maybe_exist_named_child ('kind')
1664 ev.kind = musicxml_chordkind_to_lily (kind.get_text ())
1667 bass = n.get_maybe_exist_named_child ('bass')
1669 ev.bass = musicxml_chordpitch_to_lily (bass)
1670 inversion = n.get_maybe_exist_named_child ('inversion')
1672 # TODO: LilyPond does not support inversions, does it?
1674 # Mail from Carl Sorensen on lilypond-devel, June 11, 2008:
1675 # 4. LilyPond supports the first inversion in the form of added
1676 # bass notes. So the first inversion of C major would be c:/g.
1677 # To get the second inversion of C major, you would need to do
1678 # e:6-3-^5 or e:m6-^5. However, both of these techniques
1679 # require you to know the chord and calculate either the fifth
1680 # pitch (for the first inversion) or the third pitch (for the
1681 # second inversion) so they may not be helpful for musicxml2ly.
1682 inversion_count = string.atoi (inversion.get_text ())
1683 if inversion_count == 1:
1684 # TODO: Calculate the bass note for the inversion...
1687 for deg in n.get_named_children ('degree'):
1688 d = musicexp.ChordModification ()
1689 d.type = deg.get_type ()
1690 d.step = deg.get_value ()
1691 d.alteration = deg.get_alter ()
1692 ev.add_modification (d)
1693 #TODO: convert the user-symbols attribute:
1694 #major: a triangle, like Unicode 25B3
1695 #minor: -, like Unicode 002D
1696 #augmented: +, like Unicode 002B
1697 #diminished: (degree), like Unicode 00B0
1698 #half-diminished: (o with slash), like Unicode 00F8
1704 def musicxml_figured_bass_note_to_lily (n):
1705 res = musicexp.FiguredBassNote ()
1706 suffix_dict = { 'sharp' : "+",
1709 'double-sharp' : "++",
1711 'sharp-sharp' : "++",
1713 prefix = n.get_maybe_exist_named_child ('prefix')
1715 res.set_prefix (suffix_dict.get (prefix.get_text (), ""))
1716 fnumber = n.get_maybe_exist_named_child ('figure-number')
1718 res.set_number (fnumber.get_text ())
1719 suffix = n.get_maybe_exist_named_child ('suffix')
1721 res.set_suffix (suffix_dict.get (suffix.get_text (), ""))
1722 if n.get_maybe_exist_named_child ('extend'):
1723 # TODO: Implement extender lines (unfortunately, in lilypond you have
1724 # to use \set useBassFigureExtenders = ##t, which turns them on
1725 # globally, while MusicXML has a property for each note...
1726 # I'm not sure there is a proper way to implement this cleanly
1733 def musicxml_figured_bass_to_lily (n):
1734 if not isinstance (n, musicxml.FiguredBass):
1736 res = musicexp.FiguredBassEvent ()
1737 for i in n.get_named_children ('figure'):
1738 note = musicxml_figured_bass_note_to_lily (i)
1741 dur = n.get_maybe_exist_named_child ('duration')
1743 # apply the duration to res
1744 length = Rational(int(dur.get_text()), n._divisions)*Rational(1,4)
1745 res.set_real_duration (length)
1746 duration = rational_to_lily_duration (length)
1748 res.set_duration (duration)
1749 if hasattr (n, 'parentheses') and n.parentheses == "yes":
1750 res.set_parentheses (True)
1753 instrument_drumtype_dict = {
1754 'Acoustic Snare Drum': 'acousticsnare',
1755 'Side Stick': 'sidestick',
1756 'Open Triangle': 'opentriangle',
1757 'Mute Triangle': 'mutetriangle',
1758 'Tambourine': 'tambourine',
1759 'Bass Drum': 'bassdrum',
1762 def musicxml_note_to_lily_main_event (n):
1767 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1769 pitch = musicxml_pitch_to_lily (mxl_pitch)
1770 event = musicexp.NoteEvent ()
1773 acc = n.get_maybe_exist_named_child ('accidental')
1775 # let's not force accs everywhere.
1776 event.cautionary = acc.cautionary
1777 # TODO: Handle editorial accidentals
1778 # TODO: Handle the level-display setting for displaying brackets/parentheses
1780 elif n.get_maybe_exist_typed_child (musicxml.Unpitched):
1781 # Unpitched elements have display-step and can also have
1783 unpitched = n.get_maybe_exist_typed_child (musicxml.Unpitched)
1784 event = musicexp.NoteEvent ()
1785 event.pitch = musicxml_unpitched_to_lily (unpitched)
1787 elif n.get_maybe_exist_typed_child (musicxml.Rest):
1788 # rests can have display-octave and display-step, which are
1789 # treated like an ordinary note pitch
1790 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1791 event = musicexp.RestEvent ()
1792 if options.convert_rest_positions:
1793 pitch = musicxml_restdisplay_to_lily (rest)
1796 elif n.instrument_name:
1797 event = musicexp.NoteEvent ()
1798 drum_type = instrument_drumtype_dict.get (n.instrument_name)
1800 event.drum_type = drum_type
1802 n.message (_ ("drum %s type unknown, please add to instrument_drumtype_dict") % n.instrument_name)
1803 event.drum_type = 'acousticsnare'
1806 n.message (_ ("cannot find suitable event"))
1809 event.duration = musicxml_duration_to_lily (n)
1811 noteheads = n.get_named_children ('notehead')
1812 for nh in noteheads:
1813 styles = musicxml_notehead_to_lily (nh)
1815 event.add_associated_event (s)
1819 def musicxml_lyrics_to_text (lyrics):
1820 # TODO: Implement text styles for lyrics syllables
1824 for e in lyrics.get_all_children ():
1825 if isinstance (e, musicxml.Syllabic):
1826 continued = e.continued ()
1827 elif isinstance (e, musicxml.Text):
1828 # We need to convert soft hyphens to -, otherwise the ascii codec as well
1829 # as lilypond will barf on that character
1830 text += string.replace( e.get_text(), u'\xad', '-' )
1831 elif isinstance (e, musicxml.Elision):
1836 elif isinstance (e, musicxml.Extend):
1841 if text == "-" and continued:
1843 elif text == "_" and extended:
1845 elif continued and text:
1846 return musicxml.escape_ly_output_string (text) + " --"
1849 elif extended and text:
1850 return musicxml.escape_ly_output_string (text) + " __"
1854 return musicxml.escape_ly_output_string (text)
1860 def __init__ (self, here, dest):
1864 class LilyPondVoiceBuilder:
1865 def __init__ (self):
1867 self.pending_dynamics = []
1868 self.end_moment = Rational (0)
1869 self.begin_moment = Rational (0)
1870 self.pending_multibar = Rational (0)
1871 self.ignore_skips = False
1872 self.has_relevant_elements = False
1873 self.measure_length = Rational (4, 4)
1875 def _insert_multibar (self):
1876 layout_information.set_context_item ('Score', 'skipBars = ##t')
1877 r = musicexp.MultiMeasureRest ()
1878 lenfrac = self.measure_length
1879 r.duration = rational_to_lily_duration (lenfrac)
1880 r.duration.factor *= self.pending_multibar / lenfrac
1881 self.elements.append (r)
1882 self.begin_moment = self.end_moment
1883 self.end_moment = self.begin_moment + self.pending_multibar
1884 self.pending_multibar = Rational (0)
1886 def set_measure_length (self, mlen):
1887 if (mlen != self.measure_length) and self.pending_multibar:
1888 self._insert_multibar ()
1889 self.measure_length = mlen
1891 def add_multibar_rest (self, duration):
1892 self.pending_multibar += duration
1894 def set_duration (self, duration):
1895 self.end_moment = self.begin_moment + duration
1896 def current_duration (self):
1897 return self.end_moment - self.begin_moment
1899 def add_music (self, music, duration, relevant = True):
1900 assert isinstance (music, musicexp.Music)
1901 if self.pending_multibar > Rational (0):
1902 self._insert_multibar ()
1904 self.has_relevant_elements = self.has_relevant_elements or relevant
1905 self.elements.append (music)
1906 self.begin_moment = self.end_moment
1907 self.set_duration (duration)
1909 # Insert all pending dynamics right after the note/rest:
1910 if isinstance (music, musicexp.ChordEvent) and self.pending_dynamics:
1911 for d in self.pending_dynamics:
1913 self.pending_dynamics = []
1915 # Insert some music command that does not affect the position in the measure
1916 def add_command (self, command, relevant = True):
1917 assert isinstance (command, musicexp.Music)
1918 if self.pending_multibar > Rational (0):
1919 self._insert_multibar ()
1920 self.has_relevant_elements = self.has_relevant_elements or relevant
1921 self.elements.append (command)
1922 def add_barline (self, barline, relevant = False):
1923 # Insert only if we don't have a barline already
1924 # TODO: Implement proper merging of default barline and custom bar line
1925 has_relevant = self.has_relevant_elements
1926 if (not (self.elements) or
1927 not (isinstance (self.elements[-1], musicexp.BarLine)) or
1928 (self.pending_multibar > Rational (0))):
1929 self.add_music (barline, Rational (0))
1930 self.has_relevant_elements = has_relevant or relevant
1931 def add_partial (self, command):
1932 self.ignore_skips = True
1933 # insert the partial, but restore relevant_elements (partial is not relevant)
1934 relevant = self.has_relevant_elements
1935 self.add_command (command)
1936 self.has_relevant_elements = relevant
1938 def add_dynamics (self, dynamic):
1939 # store the dynamic item(s) until we encounter the next note/rest:
1940 self.pending_dynamics.append (dynamic)
1942 def add_bar_check (self, number):
1943 # re/store has_relevant_elements, so that a barline alone does not
1944 # trigger output for figured bass, chord names
1945 b = musicexp.BarLine ()
1946 b.bar_number = number
1947 self.add_barline (b)
1949 def jumpto (self, moment):
1950 current_end = self.end_moment + self.pending_multibar
1951 diff = moment - current_end
1953 if diff < Rational (0):
1954 ly.warning (_ ('Negative skip %s (from position %s to %s)') %
1955 (diff, current_end, moment))
1958 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
1959 skip = musicexp.SkipEvent()
1961 duration_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (diff.denominator (), -1)
1963 # TODO: Use the time signature for skips, too. Problem: The skip
1964 # might not start at a measure boundary!
1965 if duration_log > 0: # denominator is a power of 2...
1966 if diff.numerator () == 3:
1970 duration_factor = Rational (diff.numerator ())
1972 # for skips of a whole or more, simply use s1*factor
1974 duration_factor = diff
1975 skip.duration.duration_log = duration_log
1976 skip.duration.factor = duration_factor
1977 skip.duration.dots = duration_dots
1979 evc = musicexp.ChordEvent ()
1980 evc.elements.append (skip)
1981 self.add_music (evc, diff, False)
1983 if diff > Rational (0) and moment == 0:
1984 self.ignore_skips = False
1986 def last_event_chord (self, starting_at):
1990 # if the position matches, find the last ChordEvent, do not cross a bar line!
1991 at = len( self.elements ) - 1
1993 not isinstance (self.elements[at], musicexp.ChordEvent) and
1994 not isinstance (self.elements[at], musicexp.BarLine)):
1999 and isinstance (self.elements[at], musicexp.ChordEvent)
2000 and self.begin_moment == starting_at):
2001 value = self.elements[at]
2003 self.jumpto (starting_at)
2007 def correct_negative_skip (self, goto):
2008 self.end_moment = goto
2009 self.begin_moment = goto
2010 evc = musicexp.ChordEvent ()
2011 self.elements.append (evc)
2015 def __init__ (self):
2016 self.voicename = None
2017 self.voicedata = None
2018 self.ly_voice = None
2019 self.figured_bass = None
2020 self.chordnames = None
2021 self.lyrics_dict = {}
2022 self.lyrics_order = []
2024 def measure_length_from_attributes (attr, current_measure_length):
2025 len = attr.get_measure_length ()
2027 len = current_measure_length
2030 def musicxml_voice_to_lily_voice (voice):
2034 return_value = VoiceData ()
2035 return_value.voicedata = voice
2037 # First pitch needed for relative mode (if selected in command-line options)
2040 # Needed for melismata detection (ignore lyrics on those notes!):
2045 ignore_lyrics = False
2047 current_staff = None
2049 pending_figured_bass = []
2050 pending_chordnames = []
2052 # Make sure that the keys in the dict don't get reordered, since
2053 # we need the correct ordering of the lyrics stanzas! By default,
2054 # a dict will reorder its keys
2055 return_value.lyrics_order = voice.get_lyrics_numbers ()
2056 for k in return_value.lyrics_order:
2059 voice_builder = LilyPondVoiceBuilder ()
2060 figured_bass_builder = LilyPondVoiceBuilder ()
2061 chordnames_builder = LilyPondVoiceBuilder ()
2062 current_measure_length = Rational (4, 4)
2063 voice_builder.set_measure_length (current_measure_length)
2065 for n in voice._elements:
2067 if n.get_name () == 'forward':
2069 staff = n.get_maybe_exist_named_child ('staff')
2071 staff = staff.get_text ()
2072 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
2073 voice_builder.add_command (musicexp.StaffChange (staff))
2074 current_staff = staff
2076 if isinstance (n, musicxml.Partial) and n.partial > 0:
2077 a = musicxml_partial_to_lily (n.partial)
2079 voice_builder.add_partial (a)
2080 figured_bass_builder.add_partial (a)
2081 chordnames_builder.add_partial (a)
2084 is_chord = n.get_maybe_exist_named_child ('chord')
2085 is_after_grace = (isinstance (n, musicxml.Note) and n.is_after_grace ());
2086 if not is_chord and not is_after_grace:
2088 voice_builder.jumpto (n._when)
2089 figured_bass_builder.jumpto (n._when)
2090 chordnames_builder.jumpto (n._when)
2091 except NegativeSkip, neg:
2092 voice_builder.correct_negative_skip (n._when)
2093 figured_bass_builder.correct_negative_skip (n._when)
2094 chordnames_builder.correct_negative_skip (n._when)
2095 n.message (_ ("Negative skip found: from %s to %s, difference is %s") % (neg.here, neg.dest, neg.dest - neg.here))
2097 if isinstance (n, musicxml.Barline):
2098 barlines = musicxml_barline_to_lily (n)
2100 if isinstance (a, musicexp.BarLine):
2101 voice_builder.add_barline (a)
2102 figured_bass_builder.add_barline (a, False)
2103 chordnames_builder.add_barline (a, False)
2104 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
2105 voice_builder.add_command (a)
2106 figured_bass_builder.add_barline (a, False)
2107 chordnames_builder.add_barline (a, False)
2111 if isinstance (n, musicxml.Print):
2112 for a in musicxml_print_to_lily (n):
2113 voice_builder.add_command (a, False)
2116 # Continue any multimeasure-rests before trying to add bar checks!
2117 # Don't handle new MM rests yet, because for them we want bar checks!
2118 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
2119 if (rest and rest.is_whole_measure ()
2120 and voice_builder.pending_multibar > Rational (0)):
2121 voice_builder.add_multibar_rest (n._duration)
2125 # print a bar check at the beginning of each measure!
2126 if n.is_first () and n._measure_position == Rational (0) and n != voice._elements[0]:
2128 num = int (n.get_parent ().number)
2132 voice_builder.add_bar_check (num)
2133 figured_bass_builder.add_bar_check (num)
2134 chordnames_builder.add_bar_check (num)
2136 # Start any new multimeasure rests
2137 if (rest and rest.is_whole_measure ()):
2138 voice_builder.add_multibar_rest (n._duration)
2142 if isinstance (n, musicxml.Direction):
2143 for a in musicxml_direction_to_lily (n):
2144 if a.wait_for_note ():
2145 voice_builder.add_dynamics (a)
2147 voice_builder.add_command (a)
2150 if isinstance (n, musicxml.Harmony):
2151 for a in musicxml_harmony_to_lily (n):
2152 if a.wait_for_note ():
2153 voice_builder.add_dynamics (a)
2155 voice_builder.add_command (a)
2156 for a in musicxml_harmony_to_lily_chordname (n):
2157 pending_chordnames.append (a)
2160 if isinstance (n, musicxml.FiguredBass):
2161 a = musicxml_figured_bass_to_lily (n)
2163 pending_figured_bass.append (a)
2166 if isinstance (n, musicxml.Attributes):
2167 for a in musicxml_attributes_to_lily (n):
2168 voice_builder.add_command (a)
2169 measure_length = measure_length_from_attributes (n, current_measure_length)
2170 if current_measure_length != measure_length:
2171 current_measure_length = measure_length
2172 voice_builder.set_measure_length (current_measure_length)
2175 if not n.__class__.__name__ == 'Note':
2176 n.message (_ ('unexpected %s; expected %s or %s or %s') % (n, 'Note', 'Attributes', 'Barline'))
2179 main_event = musicxml_note_to_lily_main_event (n)
2180 if main_event and not first_pitch:
2181 first_pitch = main_event.pitch
2182 # ignore lyrics for notes inside a slur, tie, chord or beam
2183 ignore_lyrics = inside_slur or is_tied or is_chord or is_beamed
2185 if main_event and hasattr (main_event, 'drum_type') and main_event.drum_type:
2186 modes_found['drummode'] = True
2188 ev_chord = voice_builder.last_event_chord (n._when)
2190 ev_chord = musicexp.ChordEvent()
2191 voice_builder.add_music (ev_chord, n._duration)
2194 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
2196 is_after_grace = ev_chord.has_elements () or n.is_after_grace ();
2197 is_chord = n.get_maybe_exist_typed_child (musicxml.Chord)
2201 # after-graces and other graces use different lists; Depending on
2202 # whether we have a chord or not, obtain either a new ChordEvent or
2203 # the previous one to create a chord
2205 if ev_chord.after_grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2206 grace_chord = ev_chord.after_grace_elements.get_last_event_chord ()
2208 grace_chord = musicexp.ChordEvent ()
2209 ev_chord.append_after_grace (grace_chord)
2211 if ev_chord.grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2212 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
2214 grace_chord = musicexp.ChordEvent ()
2215 ev_chord.append_grace (grace_chord)
2217 if hasattr (grace, 'slash') and not is_after_grace:
2218 # TODO: use grace_type = "appoggiatura" for slurred grace notes
2219 if grace.slash == "yes":
2220 ev_chord.grace_type = "acciaccatura"
2221 # now that we have inserted the chord into the grace music, insert
2222 # everything into that chord instead of the ev_chord
2223 ev_chord = grace_chord
2224 ev_chord.append (main_event)
2225 ignore_lyrics = True
2227 ev_chord.append (main_event)
2228 # When a note/chord has grace notes (duration==0), the duration of the
2229 # event chord is not yet known, but the event chord was already added
2230 # with duration 0. The following correct this when we hit the real note!
2231 if voice_builder.current_duration () == 0 and n._duration > 0:
2232 voice_builder.set_duration (n._duration)
2234 # if we have a figured bass, set its voice builder to the correct position
2235 # and insert the pending figures
2236 if pending_figured_bass:
2238 figured_bass_builder.jumpto (n._when)
2239 except NegativeSkip, neg:
2241 for fb in pending_figured_bass:
2242 # if a duration is given, use that, otherwise the one of the note
2243 dur = fb.real_duration
2245 dur = ev_chord.get_length ()
2247 fb.duration = ev_chord.get_duration ()
2248 figured_bass_builder.add_music (fb, dur)
2249 pending_figured_bass = []
2251 if pending_chordnames:
2253 chordnames_builder.jumpto (n._when)
2254 except NegativeSkip, neg:
2256 for cn in pending_chordnames:
2257 # Assign the duration of the EventChord
2258 cn.duration = ev_chord.get_duration ()
2259 chordnames_builder.add_music (cn, ev_chord.get_length ())
2260 pending_chordnames = []
2262 notations_children = n.get_typed_children (musicxml.Notations)
2266 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
2267 # +tied | +slur | +tuplet | glissando | slide |
2268 # ornaments | technical | articulations | dynamics |
2269 # +fermata | arpeggiate | non-arpeggiate |
2270 # accidental-mark | other-notation
2271 for notations in notations_children:
2272 for tuplet_event in notations.get_tuplets():
2273 time_mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
2274 tuplet_events.append ((ev_chord, tuplet_event, time_mod))
2276 # First, close all open slurs, only then start any new slur
2277 # TODO: Record the number of the open slur to dtermine the correct
2279 endslurs = [s for s in notations.get_named_children ('slur')
2280 if s.get_type () in ('stop')]
2281 if endslurs and not inside_slur:
2282 endslurs[0].message (_ ('Encountered closing slur, but no slur is open'))
2284 if len (endslurs) > 1:
2285 endslurs[0].message (_ ('Cannot have two simultaneous (closing) slurs'))
2286 # record the slur status for the next note in the loop
2288 lily_ev = musicxml_spanner_to_lily_event (endslurs[0])
2289 ev_chord.append (lily_ev)
2291 startslurs = [s for s in notations.get_named_children ('slur')
2292 if s.get_type () in ('start')]
2293 if startslurs and inside_slur:
2294 startslurs[0].message (_ ('Cannot have a slur inside another slur'))
2296 if len (startslurs) > 1:
2297 startslurs[0].message (_ ('Cannot have two simultaneous slurs'))
2298 # record the slur status for the next note in the loop
2300 lily_ev = musicxml_spanner_to_lily_event (startslurs[0])
2301 ev_chord.append (lily_ev)
2305 mxl_tie = notations.get_tie ()
2306 if mxl_tie and mxl_tie.type == 'start':
2307 ev_chord.append (musicexp.TieEvent ())
2313 fermatas = notations.get_named_children ('fermata')
2315 ev = musicxml_fermata_to_lily_event (a)
2317 ev_chord.append (ev)
2319 arpeggiate = notations.get_named_children ('arpeggiate')
2320 for a in arpeggiate:
2321 ev = musicxml_arpeggiate_to_lily_event (a)
2323 ev_chord.append (ev)
2325 arpeggiate = notations.get_named_children ('non-arpeggiate')
2326 for a in arpeggiate:
2327 ev = musicxml_nonarpeggiate_to_lily_event (a)
2329 ev_chord.append (ev)
2331 glissandos = notations.get_named_children ('glissando')
2332 glissandos += notations.get_named_children ('slide')
2333 for a in glissandos:
2334 ev = musicxml_spanner_to_lily_event (a)
2336 ev_chord.append (ev)
2338 # accidental-marks are direct children of <notation>!
2339 for a in notations.get_named_children ('accidental-mark'):
2340 ev = musicxml_articulation_to_lily_event (a)
2342 ev_chord.append (ev)
2344 # Articulations can contain the following child elements:
2345 # accent | strong-accent | staccato | tenuto |
2346 # detached-legato | staccatissimo | spiccato |
2347 # scoop | plop | doit | falloff | breath-mark |
2348 # caesura | stress | unstress
2349 # Technical can contain the following child elements:
2350 # up-bow | down-bow | harmonic | open-string |
2351 # thumb-position | fingering | pluck | double-tongue |
2352 # triple-tongue | stopped | snap-pizzicato | fret |
2353 # string | hammer-on | pull-off | bend | tap | heel |
2354 # toe | fingernails | other-technical
2355 # Ornaments can contain the following child elements:
2356 # trill-mark | turn | delayed-turn | inverted-turn |
2357 # shake | wavy-line | mordent | inverted-mordent |
2358 # schleifer | tremolo | other-ornament, accidental-mark
2359 ornaments = notations.get_named_children ('ornaments')
2360 ornaments += notations.get_named_children ('articulations')
2361 ornaments += notations.get_named_children ('technical')
2364 for ch in a.get_all_children ():
2365 ev = musicxml_articulation_to_lily_event (ch)
2367 ev_chord.append (ev)
2369 dynamics = notations.get_named_children ('dynamics')
2371 for ch in a.get_all_children ():
2372 ev = musicxml_dynamics_to_lily_event (ch)
2374 ev_chord.append (ev)
2377 mxl_beams = [b for b in n.get_named_children ('beam')
2378 if (b.get_type () in ('begin', 'end')
2379 and b.is_primary ())]
2380 if mxl_beams and not conversion_settings.ignore_beaming:
2381 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
2383 ev_chord.append (beam_ev)
2384 if beam_ev.span_direction == -1: # beam and thus melisma starts here
2386 elif beam_ev.span_direction == 1: # beam and thus melisma ends here
2389 # Extract the lyrics
2390 if not rest and not ignore_lyrics:
2391 note_lyrics_processed = []
2392 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
2393 for l in note_lyrics_elements:
2394 if l.get_number () < 0:
2395 for k in lyrics.keys ():
2396 lyrics[k].append (musicxml_lyrics_to_text (l))
2397 note_lyrics_processed.append (k)
2399 lyrics[l.number].append(musicxml_lyrics_to_text (l))
2400 note_lyrics_processed.append (l.number)
2401 for lnr in lyrics.keys ():
2402 if not lnr in note_lyrics_processed:
2403 lyrics[lnr].append ("\skip4")
2405 # Assume that a <tie> element only lasts for one note.
2406 # This might not be correct MusicXML interpretation, but works for
2407 # most cases and fixes broken files, which have the end tag missing
2408 if is_tied and not tie_started:
2411 ## force trailing mm rests to be written out.
2412 voice_builder.add_music (musicexp.ChordEvent (), Rational (0))
2414 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
2415 ly_voice = group_repeats (ly_voice)
2417 seq_music = musicexp.SequentialMusic ()
2419 if 'drummode' in modes_found.keys ():
2420 ## \key <pitch> barfs in drummode.
2421 ly_voice = [e for e in ly_voice
2422 if not isinstance(e, musicexp.KeySignatureChange)]
2424 seq_music.elements = ly_voice
2425 for k in lyrics.keys ():
2426 return_value.lyrics_dict[k] = musicexp.Lyrics ()
2427 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
2430 if len (modes_found) > 1:
2431 ly.warning (_ ('cannot simultaneously have more than one mode: %s') % modes_found.keys ())
2433 if options.relative:
2434 v = musicexp.RelativeMusic ()
2435 v.element = seq_music
2436 v.basepitch = first_pitch
2439 return_value.ly_voice = seq_music
2440 for mode in modes_found.keys ():
2441 v = musicexp.ModeChangingMusicWrapper()
2442 v.element = seq_music
2444 return_value.ly_voice = v
2446 # create \figuremode { figured bass elements }
2447 if figured_bass_builder.has_relevant_elements:
2448 fbass_music = musicexp.SequentialMusic ()
2449 fbass_music.elements = group_repeats (figured_bass_builder.elements)
2450 v = musicexp.ModeChangingMusicWrapper()
2451 v.mode = 'figuremode'
2452 v.element = fbass_music
2453 return_value.figured_bass = v
2455 # create \chordmode { chords }
2456 if chordnames_builder.has_relevant_elements:
2457 cname_music = musicexp.SequentialMusic ()
2458 cname_music.elements = group_repeats (chordnames_builder.elements)
2459 v = musicexp.ModeChangingMusicWrapper()
2460 v.mode = 'chordmode'
2461 v.element = cname_music
2462 return_value.chordnames = v
2466 def musicxml_id_to_lily (id):
2467 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
2468 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
2470 for digit in digits:
2471 d = digits.index (digit)
2472 id = re.sub ('%d' % d, digit, id)
2474 id = re.sub ('[^a-zA-Z]', 'X', id)
2477 def musicxml_pitch_to_lily (mxl_pitch):
2478 p = musicexp.Pitch ()
2479 p.alteration = mxl_pitch.get_alteration ()
2480 p.step = musicxml_step_to_lily (mxl_pitch.get_step ())
2481 p.octave = mxl_pitch.get_octave () - 4
2484 def musicxml_unpitched_to_lily (mxl_unpitched):
2486 step = mxl_unpitched.get_step ()
2488 p = musicexp.Pitch ()
2489 p.step = musicxml_step_to_lily (step)
2490 octave = mxl_unpitched.get_octave ()
2492 p.octave = octave - 4
2495 def musicxml_restdisplay_to_lily (mxl_rest):
2497 step = mxl_rest.get_step ()
2499 p = musicexp.Pitch ()
2500 p.step = musicxml_step_to_lily (step)
2501 octave = mxl_rest.get_octave ()
2503 p.octave = octave - 4
2506 def voices_in_part (part):
2507 """Return a Name -> Voice dictionary for PART"""
2509 part.extract_voices ()
2510 voices = part.get_voices ()
2511 part_info = part.get_staff_attributes ()
2513 return (voices, part_info)
2515 def voices_in_part_in_parts (parts):
2516 """return a Part -> Name -> Voice dictionary"""
2517 # don't crash if p doesn't have an id (that's invalid MusicXML,
2518 # but such files are out in the wild!
2521 voices = voices_in_part (p)
2522 if (hasattr (p, "id")):
2523 dictionary[p.id] = voices
2525 # TODO: extract correct part id from other sources
2526 dictionary[None] = voices
2530 def get_all_voices (parts):
2531 all_voices = voices_in_part_in_parts (parts)
2534 all_ly_staffinfo = {}
2535 for p, (name_voice, staff_info) in all_voices.items ():
2538 for n, v in name_voice.items ():
2539 ly.progress (_ ("Converting to LilyPond expressions..."), True)
2540 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
2541 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
2543 all_ly_voices[p] = part_ly_voices
2544 all_ly_staffinfo[p] = staff_info
2546 return (all_ly_voices, all_ly_staffinfo)
2549 def option_parser ():
2550 p = ly.get_option_parser (usage = _ ("musicxml2ly [OPTION]... FILE.xml"),
2552 _ ("""Convert MusicXML from FILE.xml to LilyPond input.
2553 If the given filename is -, musicxml2ly reads from the command line.
2554 """), add_help_option=False)
2556 p.add_option("-h", "--help",
2558 help=_ ("show this help and exit"))
2560 p.version = ('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
2562 _ ("""Copyright (c) 2005--2011 by
2563 Han-Wen Nienhuys <hanwen@xs4all.nl>,
2564 Jan Nieuwenhuizen <janneke@gnu.org> and
2565 Reinhold Kainhofer <reinhold@kainhofer.com>
2569 This program is free software. It is covered by the GNU General Public
2570 License and you are welcome to change it and/or distribute copies of it
2571 under certain conditions. Invoke as `%s --warranty' for more
2572 information.""") % 'lilypond')
2574 p.add_option("--version",
2576 help=_ ("show version number and exit"))
2578 p.add_option ('-v', '--verbose',
2580 callback=ly.handle_loglevel_option,
2581 callback_args=("DEBUG",),
2582 help = _ ("be verbose"))
2584 p.add_option ('', '--lxml',
2585 action = "store_true",
2588 help = _ ("use lxml.etree; uses less memory and cpu time"))
2590 p.add_option ('-z', '--compressed',
2591 action = "store_true",
2592 dest = 'compressed',
2594 help = _ ("input file is a zip-compressed MusicXML file"))
2596 p.add_option ('-r', '--relative',
2597 action = "store_true",
2600 help = _ ("convert pitches in relative mode (default)"))
2602 p.add_option ('-a', '--absolute',
2603 action = "store_false",
2605 help = _ ("convert pitches in absolute mode"))
2607 p.add_option ('-l', '--language',
2608 metavar = _ ("LANG"),
2610 help = _ ("use LANG for pitch names, e.g. 'deutsch' for note names in German"))
2612 p.add_option ("--loglevel",
2613 help=_ ("Print log messages according to LOGLEVEL "
2614 "(NONE, ERROR, WARNING, PROGRESS (default), DEBUG)"),
2615 metavar=_ ("LOGLEVEL"),
2617 callback=ly.handle_loglevel_option,
2620 p.add_option ('--nd', '--no-articulation-directions',
2621 action = "store_false",
2623 dest = "convert_directions",
2624 help = _ ("do not convert directions (^, _ or -) for articulations, dynamics, etc."))
2626 p.add_option ('--nrp', '--no-rest-positions',
2627 action = "store_false",
2629 dest = "convert_rest_positions",
2630 help = _ ("do not convert exact vertical positions of rests"))
2632 p.add_option ('--npl', '--no-page-layout',
2633 action = "store_false",
2635 dest = "convert_page_layout",
2636 help = _ ("do not convert the exact page layout and breaks"))
2638 p.add_option ('--no-beaming',
2639 action = "store_false",
2641 dest = "convert_beaming",
2642 help = _ ("do not convert beaming information, use lilypond's automatic beaming instead"))
2644 p.add_option ('-o', '--output',
2645 metavar = _ ("FILE"),
2649 dest = 'output_name',
2650 help = _ ("set output filename to FILE, stdout if -"))
2651 p.add_option_group ('',
2653 _ ("Report bugs via %s")
2654 % 'http://post.gmane.org/post.php'
2655 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
2658 def music_xml_voice_name_to_lily_name (part_id, name):
2659 str = "Part%sVoice%s" % (part_id, name)
2660 return musicxml_id_to_lily (str)
2662 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
2663 str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
2664 return musicxml_id_to_lily (str)
2666 def music_xml_figuredbass_name_to_lily_name (part_id, voicename):
2667 str = "Part%sVoice%sFiguredBass" % (part_id, voicename)
2668 return musicxml_id_to_lily (str)
2670 def music_xml_chordnames_name_to_lily_name (part_id, voicename):
2671 str = "Part%sVoice%sChords" % (part_id, voicename)
2672 return musicxml_id_to_lily (str)
2674 def print_voice_definitions (printer, part_list, voices):
2675 for part in part_list:
2677 nv_dict = voices.get (part_id, {})
2678 for (name, voice) in nv_dict.items ():
2679 k = music_xml_voice_name_to_lily_name (part_id, name)
2680 printer.dump ('%s = ' % k)
2681 voice.ly_voice.print_ly (printer)
2683 if voice.chordnames:
2684 cnname = music_xml_chordnames_name_to_lily_name (part_id, name)
2685 printer.dump ('%s = ' % cnname )
2686 voice.chordnames.print_ly (printer)
2688 for l in voice.lyrics_order:
2689 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
2690 printer.dump ('%s = ' % lname )
2691 voice.lyrics_dict[l].print_ly (printer)
2693 if voice.figured_bass:
2694 fbname = music_xml_figuredbass_name_to_lily_name (part_id, name)
2695 printer.dump ('%s = ' % fbname )
2696 voice.figured_bass.print_ly (printer)
2701 return dict ([(elt,1) for elt in l]).keys ()
2703 # format the information about the staff in the form
2706 # [voiceid1, [lyricsid11, lyricsid12,...], figuredbassid1],
2707 # [voiceid2, [lyricsid21, lyricsid22,...], figuredbassid2],
2711 # raw_voices is of the form [(voicename, lyricsids, havefiguredbass)*]
2712 def format_staff_info (part_id, staff_id, raw_voices):
2714 for (v, lyricsids, figured_bass, chordnames) in raw_voices:
2715 voice_name = music_xml_voice_name_to_lily_name (part_id, v)
2716 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
2718 figured_bass_name = ''
2720 figured_bass_name = music_xml_figuredbass_name_to_lily_name (part_id, v)
2721 chordnames_name = ''
2723 chordnames_name = music_xml_chordnames_name_to_lily_name (part_id, v)
2724 voices.append ([voice_name, voice_lyrics, figured_bass_name, chordnames_name])
2725 return [staff_id, voices]
2727 def update_score_setup (score_structure, part_list, voices):
2729 for part_definition in part_list:
2730 part_id = part_definition.id
2731 nv_dict = voices.get (part_id)
2733 ly.warning (_ ('unknown part in part-list: %s') % part_id)
2736 staves = reduce (lambda x,y: x+ y,
2737 [voice.voicedata._staves.keys ()
2738 for voice in nv_dict.values ()],
2741 if len (staves) > 1:
2743 staves = uniq_list (staves)
2746 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2747 for (voice_name, voice) in nv_dict.items ()
2748 if voice.voicedata._start_staff == s]
2749 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
2751 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2752 for (voice_name, voice) in nv_dict.items ()]
2753 staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
2754 score_structure.set_part_information (part_id, staves_info)
2756 # Set global values in the \layout block, like auto-beaming etc.
2757 def update_layout_information ():
2758 if not conversion_settings.ignore_beaming and layout_information:
2759 layout_information.set_context_item ('Score', 'autoBeaming = ##f')
2761 def print_ly_preamble (printer, filename):
2762 printer.dump_version ()
2763 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
2765 def print_ly_additional_definitions (printer, filename):
2766 if needed_additional_definitions:
2768 printer.print_verbatim ('%% additional definitions required by the score:')
2770 for a in set(needed_additional_definitions):
2771 printer.print_verbatim (additional_definitions.get (a, ''))
2775 # Read in the tree from the given I/O object (either file or string) and
2776 # demarshall it using the classes from the musicxml.py file
2777 def read_xml (io_object, use_lxml):
2780 tree = lxml.etree.parse (io_object)
2781 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
2784 from xml.dom import minidom, Node
2785 doc = minidom.parse(io_object)
2786 node = doc.documentElement
2787 return musicxml.minidom_demarshal_node (node)
2791 def read_musicxml (filename, compressed, use_lxml):
2795 ly.progress (_ ("Input is compressed, extracting raw MusicXML data from stdin"), True)
2796 # unfortunately, zipfile.ZipFile can't read directly from
2797 # stdin, so copy everything from stdin to a temp file and read
2798 # that. TemporaryFile() will remove the file when it is closed.
2799 tmp = tempfile.TemporaryFile()
2800 sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0) # Make sys.stdin binary
2801 bytes_read = sys.stdin.read (8192)
2803 for b in bytes_read:
2805 bytes_read = sys.stdin.read (8192)
2806 z = zipfile.ZipFile (tmp, "r")
2808 ly.progress (_ ("Input file %s is compressed, extracting raw MusicXML data") % filename, True)
2809 z = zipfile.ZipFile (filename, "r")
2810 container_xml = z.read ("META-INF/container.xml")
2811 if not container_xml:
2813 container = read_xml (StringIO.StringIO (container_xml), use_lxml)
2816 rootfiles = container.get_maybe_exist_named_child ('rootfiles')
2819 rootfile_list = rootfiles.get_named_children ('rootfile')
2821 if len (rootfile_list) > 0:
2822 mxml_file = getattr (rootfile_list[0], 'full-path', None)
2824 raw_string = z.read (mxml_file)
2827 io_object = StringIO.StringIO (raw_string)
2828 elif filename == "-":
2829 io_object = sys.stdin
2831 io_object = filename
2833 return read_xml (io_object, use_lxml)
2836 def convert (filename, options):
2838 ly.progress (_ ("Reading MusicXML from Standard input ..."), True)
2840 ly.progress (_ ("Reading MusicXML from %s ...") % filename, True)
2842 tree = read_musicxml (filename, options.compressed, options.use_lxml)
2843 score_information = extract_score_information (tree)
2844 paper_information = extract_paper_information (tree)
2846 parts = tree.get_typed_children (musicxml.Part)
2847 (voices, staff_info) = get_all_voices (parts)
2850 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
2852 score = extract_score_structure (mxl_pl, staff_info)
2853 part_list = mxl_pl.get_named_children ("score-part")
2855 # score information is contained in the <work>, <identification> or <movement-title> tags
2856 update_score_setup (score, part_list, voices)
2857 # After the conversion, update the list of settings for the \layout block
2858 update_layout_information ()
2860 if not options.output_name:
2861 options.output_name = os.path.basename (filename)
2862 options.output_name = os.path.splitext (options.output_name)[0]
2863 elif re.match (".*\.ly", options.output_name):
2864 options.output_name = os.path.splitext (options.output_name)[0]
2867 #defs_ly_name = options.output_name + '-defs.ly'
2868 if (options.output_name == "-"):
2869 output_ly_name = 'Standard output'
2871 output_ly_name = options.output_name + '.ly'
2873 ly.progress (_ ("Output to `%s'") % output_ly_name, True)
2874 printer = musicexp.Output_printer()
2875 #ly.progress (_ ("Output to `%s'") % defs_ly_name, True)
2876 if (options.output_name == "-"):
2877 printer.set_file (codecs.getwriter ("utf-8")(sys.stdout))
2879 printer.set_file (codecs.open (output_ly_name, 'wb', encoding='utf-8'))
2880 print_ly_preamble (printer, filename)
2881 print_ly_additional_definitions (printer, filename)
2882 if score_information:
2883 score_information.print_ly (printer)
2884 if paper_information and conversion_settings.convert_page_layout:
2885 paper_information.print_ly (printer)
2886 if layout_information:
2887 layout_information.print_ly (printer)
2888 print_voice_definitions (printer, part_list, voices)
2891 printer.dump ("% The score definition")
2893 score.print_ly (printer)
2898 def get_existing_filename_with_extension (filename, ext):
2899 if os.path.exists (filename):
2901 newfilename = filename + "." + ext
2902 if os.path.exists (newfilename):
2904 newfilename = filename + ext
2905 if os.path.exists (newfilename):
2910 opt_parser = option_parser()
2913 (options, args) = opt_parser.parse_args ()
2915 opt_parser.print_usage()
2918 if options.language:
2919 musicexp.set_pitch_language (options.language)
2920 needed_additional_definitions.append (options.language)
2921 additional_definitions[options.language] = "\\language \"%s\"\n" % options.language
2922 conversion_settings.ignore_beaming = not options.convert_beaming
2923 conversion_settings.convert_page_layout = options.convert_page_layout
2925 # Allow the user to leave out the .xml or xml on the filename
2926 basefilename = args[0].decode('utf-8')
2927 if basefilename == "-": # Read from stdin
2930 filename = get_existing_filename_with_extension (basefilename, "xml")
2932 filename = get_existing_filename_with_extension (basefilename, "mxl")
2933 options.compressed = True
2934 if filename and filename.endswith ("mxl"):
2935 options.compressed = True
2937 if filename and (filename == "-" or os.path.exists (filename)):
2938 voices = convert (filename, options)
2940 ly.error (_ ("Unable to find input file %s") % basefilename)
2942 if __name__ == '__main__':