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 work = tree.get_maybe_exist_named_child ('work')
170 set_if_exists ('worknumber', work.get_work_number ())
171 set_if_exists ('opus', work.get_opus ())
173 movement_title = tree.get_maybe_exist_named_child ('movement-title')
175 # use either work-title or movement-title as title.
176 # if both exist use movement-title as subtitle.
177 # if there is only a movement-title (or work-title is empty or missing) the movement-title should be typeset as a title
179 work_title = work.get_work_title ()
180 set_if_exists ('title', work_title)
182 set_if_exists ('title', movement_title.get_text ())
184 set_if_exists ('subtitle', movement_title.get_text ())
186 set_if_exists ('title', movement_title.get_text ())
188 identifications = tree.get_named_children ('identification')
189 for ids in identifications:
190 set_if_exists ('copyright', ids.get_rights ())
191 set_if_exists ('composer', ids.get_composer ())
192 set_if_exists ('arranger', ids.get_arranger ())
193 set_if_exists ('editor', ids.get_editor ())
194 set_if_exists ('poet', ids.get_poet ())
196 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
197 set_if_exists ('encodingdate', ids.get_encoding_date ())
198 set_if_exists ('encoder', ids.get_encoding_person ())
199 set_if_exists ('encodingdescription', ids.get_encoding_description ())
201 set_if_exists ('source', ids.get_source ())
203 # miscellaneous --> texidoc
204 set_if_exists ('texidoc', ids.get_file_description ());
206 # Finally, apply the required compatibility modes
207 # Some applications created wrong MusicXML files, so we need to
208 # apply some compatibility mode, e.g. ignoring some features/tags
210 software = ids.get_encoding_software_list ()
212 # Case 1: "Sibelius 5.1" with the "Dolet 3.4 for Sibelius" plugin
213 # is missing all beam ends => ignore all beaming information
214 ignore_beaming_software = {
215 "Dolet 4 for Sibelius, Beta 2": "Dolet 4 for Sibelius, Beta 2",
216 "Dolet 3.5 for Sibelius": "Dolet 3.5 for Sibelius",
217 "Dolet 3.4 for Sibelius": "Dolet 3.4 for Sibelius",
218 "Dolet 3.3 for Sibelius": "Dolet 3.3 for Sibelius",
219 "Dolet 3.2 for Sibelius": "Dolet 3.2 for Sibelius",
220 "Dolet 3.1 for Sibelius": "Dolet 3.1 for Sibelius",
221 "Dolet for Sibelius 1.3": "Dolet for Sibelius 1.3",
222 "Noteworthy Composer": "Noteworthy Composer's nwc2xm[",
225 app_description = ignore_beaming_software.get (s, False);
227 conversion_settings.ignore_beaming = True
228 ly.warning (_ ("Encountered file created by %s, containing "
229 "wrong beaming information. All beaming "
230 "information in the MusicXML file will be "
231 "ignored") % app_description)
233 # TODO: Check for other unsupported features
241 return len (self.start) + len (self.end) == 0
242 def add_start (self, g):
243 self.start[getattr (g, 'number', "1")] = g
244 def add_end (self, g):
245 self.end[getattr (g, 'number', "1")] = g
246 def print_ly (self, printer):
247 ly.warning (_ ("Unprocessed PartGroupInfo %s encountered") % self)
248 def ly_expression (self):
249 ly.warning (_ ("Unprocessed PartGroupInfo %s encountered") % self)
252 def musicxml_step_to_lily (step):
254 return (ord (step) - ord ('A') + 7 - 2) % 7
259 def staff_attributes_to_string_tunings (mxl_attr):
260 details = mxl_attr.get_maybe_exist_named_child ('staff-details')
264 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
266 lines = string.atoi (staff_lines.get_text ())
268 tunings = [musicexp.Pitch()]*lines
269 staff_tunings = details.get_named_children ('staff-tuning')
270 for i in staff_tunings:
274 line = string.atoi (i.line) - 1
279 step = i.get_named_child (u'tuning-step')
280 step = step.get_text ().strip ()
281 p.step = musicxml_step_to_lily (step)
283 octave = i.get_named_child (u'tuning-octave')
284 octave = octave.get_text ().strip ()
285 p.octave = int (octave) - 4
287 alter = i.get_named_child (u'tuning-alter')
289 p.alteration = int (alter.get_text ().strip ())
290 # lilypond seems to use the opposite ordering than MusicXML...
296 def staff_attributes_to_lily_staff (mxl_attr):
298 return musicexp.Staff ()
300 (staff_id, attributes) = mxl_attr.items ()[0]
302 # distinguish by clef:
303 # percussion (percussion and rhythmic), tab, and everything else
305 clef = attributes.get_maybe_exist_named_child ('clef')
307 sign = clef.get_maybe_exist_named_child ('sign')
309 clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
312 details = attributes.get_named_children ('staff-details')
314 staff_lines = d.get_maybe_exist_named_child ('staff-lines')
316 lines = string.atoi (staff_lines.get_text ())
318 # TODO: Handle other staff attributes like staff-space, etc.
321 if clef_sign == "percussion" and lines == 1:
322 staff = musicexp.RhythmicStaff ()
323 elif clef_sign == "percussion":
324 staff = musicexp.DrumStaff ()
325 # staff.drum_style_table = ???
326 elif clef_sign == "tab":
327 staff = musicexp.TabStaff ()
328 staff.string_tunings = staff_attributes_to_string_tunings (attributes)
329 # staff.tablature_format = ???
331 staff = musicexp.Staff ()
332 # TODO: Handle case with lines <> 5!
334 staff.add_context_modification ("\\override StaffSymbol #'line-count = #%s" % lines)
340 def extract_score_structure (part_list, staffinfo):
341 score = musicexp.Score ()
342 structure = musicexp.StaffGroup (None)
343 score.set_contents (structure)
348 def read_score_part (el):
349 if not isinstance (el, musicxml.Score_part):
351 # Depending on the attributes of the first measure, we create different
352 # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
353 staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
357 partname = el.get_maybe_exist_named_child ('part-name')
358 # Finale gives unnamed parts the name "MusicXML Part" automatically!
359 if partname and partname.get_text() != "MusicXML Part":
360 staff.instrument_name = partname.get_text ()
361 # part-name-display overrides part-name!
362 partname = el.get_maybe_exist_named_child ("part-name-display")
364 staff.instrument_name = extract_display_text (partname)
366 partdisplay = el.get_maybe_exist_named_child ('part-abbreviation')
368 staff.short_instrument_name = partdisplay.get_text ()
369 # part-abbreviation-display overrides part-abbreviation!
370 partdisplay = el.get_maybe_exist_named_child ("part-abbreviation-display")
372 staff.short_instrument_name = extract_display_text (partdisplay)
373 # TODO: Read in the MIDI device / instrument
377 def read_score_group (el):
378 if not isinstance (el, musicxml.Part_group):
380 group = musicexp.StaffGroup ()
381 if hasattr (el, 'number'):
384 #currentgroups_dict[id] = group
385 #currentgroups.append (id)
386 if el.get_maybe_exist_named_child ('group-name'):
387 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
388 if el.get_maybe_exist_named_child ('group-abbreviation'):
389 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
390 if el.get_maybe_exist_named_child ('group-symbol'):
391 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
392 if el.get_maybe_exist_named_child ('group-barline'):
393 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
397 parts_groups = part_list.get_all_children ()
399 # the start/end group tags are not necessarily ordered correctly and groups
400 # might even overlap, so we can't go through the children sequentially!
402 # 1) Replace all Score_part objects by their corresponding Staff objects,
403 # also collect all group start/stop points into one PartGroupInfo object
405 group_info = PartGroupInfo ()
406 for el in parts_groups:
407 if isinstance (el, musicxml.Score_part):
408 if not group_info.is_empty ():
409 staves.append (group_info)
410 group_info = PartGroupInfo ()
411 staff = read_score_part (el)
413 staves.append (staff)
414 elif isinstance (el, musicxml.Part_group):
415 if el.type == "start":
416 group_info.add_start (el)
417 elif el.type == "stop":
418 group_info.add_end (el)
419 if not group_info.is_empty ():
420 staves.append (group_info)
422 # 2) Now, detect the groups:
425 while pos < len (staves):
427 if isinstance (el, PartGroupInfo):
429 if len (group_starts) > 0:
430 prev_start = group_starts[-1]
431 elif len (el.end) > 0: # no group to end here
433 if len (el.end) > 0: # closes an existing group
434 ends = el.end.keys ()
435 prev_started = staves[prev_start].start.keys ()
437 intersection = filter(lambda x:x in ends, prev_started)
438 if len (intersection) > 0:
439 grpid = intersection[0]
441 # Close the last started group
442 grpid = staves[prev_start].start.keys () [0]
443 # Find the corresponding closing tag and remove it!
446 while j < len (staves) and not foundclosing:
447 if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
449 del staves[j].end[grpid]
450 if staves[j].is_empty ():
453 grpobj = staves[prev_start].start[grpid]
454 group = read_score_group (grpobj)
455 # remove the id from both the start and end
456 if el.end.has_key (grpid):
458 del staves[prev_start].start[grpid]
461 # replace the staves with the whole group
462 for j in staves[(prev_start + 1):pos]:
463 group.append_staff (j)
464 del staves[(prev_start + 1):pos]
465 staves.insert (prev_start + 1, group)
466 # reset pos so that we continue at the correct position
468 # remove an empty start group
469 if staves[prev_start].is_empty ():
470 del staves[prev_start]
471 group_starts.remove (prev_start)
473 elif len (el.start) > 0: # starts new part groups
474 group_starts.append (pos)
477 if len (staves) == 1:
480 structure.append_staff (i)
484 def musicxml_duration_to_lily (mxl_note):
485 # if the note has no Type child, then that method returns None. In that case,
486 # use the <duration> tag instead. If that doesn't exist, either -> Error
487 dur = mxl_note.get_duration_info ()
489 d = musicexp.Duration ()
490 d.duration_log = dur[0]
492 # Grace notes by specification have duration 0, so no time modification
493 # factor is possible. It even messes up the output with *0/1
494 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
495 d.factor = mxl_note._duration / d.get_length ()
499 if mxl_note._duration > 0:
500 return rational_to_lily_duration (mxl_note._duration)
502 mxl_note.message (_ ("Encountered note at %s without type and duration (=%s)") % (mxl_note.start, mxl_note._duration) )
506 def rational_to_lily_duration (rational_len):
507 d = musicexp.Duration ()
509 rational_len.normalize_self ()
510 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)
512 # Duration of the form 1/2^n or 3/2^n can be converted to a simple lilypond duration
513 dots = {1: 0, 3: 1, 7: 2, 15: 3, 31: 4, 63: 5, 127: 6}.get (rational_len.numerator(), -1)
514 if ( d_log >= dots >= 0 ):
515 # account for the dots!
516 d.duration_log = d_log - dots
519 d.duration_log = d_log
520 d.factor = Rational (rational_len.numerator ())
522 ly.warning (_ ("Encountered rational duration with denominator %s, "
523 "unable to convert to lilypond duration") %
524 rational_len.denominator ())
525 # TODO: Test the above error message
530 def musicxml_partial_to_lily (partial_len):
532 p = musicexp.Partial ()
533 p.partial = rational_to_lily_duration (partial_len)
538 # Detect repeats and alternative endings in the chord event list (music_list)
539 # and convert them to the corresponding musicexp objects, containing nested
541 def group_repeats (music_list):
542 repeat_replaced = True
545 # Walk through the list of expressions, looking for repeat structure
546 # (repeat start/end, corresponding endings). If we find one, try to find the
547 # last event of the repeat, replace the whole structure and start over again.
548 # For nested repeats, as soon as we encounter another starting repeat bar,
549 # treat that one first, and start over for the outer repeat.
550 while repeat_replaced and i < 100:
552 repeat_start = -1 # position of repeat start / end
553 repeat_end = -1 # position of repeat start / end
555 ending_start = -1 # position of current ending start
556 endings = [] # list of already finished endings
558 last = len (music_list) - 1
559 repeat_replaced = False
561 while pos < len (music_list) and not repeat_replaced:
563 repeat_finished = False
564 if isinstance (e, RepeatMarker):
565 if not repeat_times and e.times:
566 repeat_times = e.times
567 if e.direction == -1:
569 repeat_finished = True
575 elif e.direction == 1:
581 elif isinstance (e, EndingMarker):
582 if e.direction == -1:
588 elif e.direction == 1:
591 endings.append ([ending_start, pos])
594 elif not isinstance (e, musicexp.BarLine):
595 # As soon as we encounter an element when repeat start and end
596 # is set and we are not inside an alternative ending,
597 # this whole repeat structure is finished => replace it
598 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
599 repeat_finished = True
601 # Finish off all repeats without explicit ending bar (e.g. when
602 # we convert only one page of a multi-page score with repeats)
603 if pos == last and repeat_start >= 0:
604 repeat_finished = True
608 if ending_start >= 0:
609 endings.append ([ending_start, pos])
613 # We found the whole structure replace it!
614 r = musicexp.RepeatedMusic ()
615 if repeat_times <= 0:
617 r.repeat_count = repeat_times
618 # don't erase the first element for "implicit" repeats (i.e. no
619 # starting repeat bars at the very beginning)
620 start = repeat_start+1
621 if repeat_start == music_start:
623 r.set_music (music_list[start:repeat_end])
624 for (start, end) in endings:
625 s = musicexp.SequentialMusic ()
626 s.elements = music_list[start+1:end]
628 del music_list[repeat_start:final_marker+1]
629 music_list.insert (repeat_start, r)
630 repeat_replaced = True
632 # TODO: Implement repeats until the end without explicit ending bar
636 # Extract the settings for tuplets from the <notations><tuplet> and the
637 # <time-modification> elements of the note:
638 def musicxml_tuplet_to_lily (tuplet_elt, time_modification):
639 tsm = musicexp.TimeScaledMusic ()
641 if time_modification:
642 fraction = time_modification.get_fraction ()
643 tsm.numerator = fraction[0]
644 tsm.denominator = fraction[1]
647 normal_type = tuplet_elt.get_normal_type ()
648 if not normal_type and time_modification:
649 normal_type = time_modification.get_normal_type ()
650 if not normal_type and time_modification:
651 note = time_modification.get_parent ()
653 normal_type = note.get_duration_info ()
655 normal_note = musicexp.Duration ()
656 (normal_note.duration_log, normal_note.dots) = normal_type
657 tsm.normal_type = normal_note
659 actual_type = tuplet_elt.get_actual_type ()
661 actual_note = musicexp.Duration ()
662 (actual_note.duration_log, actual_note.dots) = actual_type
663 tsm.actual_type = actual_note
665 # Obtain non-default nrs of notes from the tuplet object!
666 tsm.display_numerator = tuplet_elt.get_normal_nr ()
667 tsm.display_denominator = tuplet_elt.get_actual_nr ()
670 if hasattr (tuplet_elt, 'bracket') and tuplet_elt.bracket == "no":
671 tsm.display_bracket = None
672 elif hasattr (tuplet_elt, 'line-shape') and getattr (tuplet_elt, 'line-shape') == "curved":
673 tsm.display_bracket = "curved"
675 tsm.display_bracket = "bracket"
677 display_values = {"none": None, "actual": "actual", "both": "both"}
678 if hasattr (tuplet_elt, "show-number"):
679 tsm.display_number = display_values.get (getattr (tuplet_elt, "show-number"), "actual")
681 if hasattr (tuplet_elt, "show-type"):
682 tsm.display_type = display_values.get (getattr (tuplet_elt, "show-type"), None)
687 def group_tuplets (music_list, events):
690 """Collect Musics from
691 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
699 for (ev_chord, tuplet_elt, time_modification) in events:
700 while (j < len (music_list)):
701 if music_list[j] == ev_chord:
705 if hasattr (tuplet_elt, 'number'):
706 nr = getattr (tuplet_elt, 'number')
707 if tuplet_elt.type == 'start':
708 tuplet_object = musicxml_tuplet_to_lily (tuplet_elt, time_modification)
709 tuplet_info = [j, None, tuplet_object]
710 indices.append (tuplet_info)
711 brackets[nr] = tuplet_info
712 elif tuplet_elt.type == 'stop':
713 bracket_info = brackets.get (nr, None)
715 bracket_info[1] = j # Set the ending position to j
720 for (i1, i2, tsm) in indices:
724 new_list.extend (music_list[last:i1])
725 seq = musicexp.SequentialMusic ()
727 seq.elements = music_list[i1:last]
731 new_list.append (tsm)
732 #TODO: Handle nested tuplets!!!!
734 new_list.extend (music_list[last:])
738 def musicxml_clef_to_lily (attributes):
739 change = musicexp.ClefChange ()
740 (change.type, change.position, change.octave) = attributes.get_clef_information ()
743 def musicxml_time_to_lily (attributes):
744 sig = attributes.get_time_signature ()
747 change = musicexp.TimeSignatureChange()
748 change.fractions = sig
750 time_elm = attributes.get_maybe_exist_named_child ('time')
751 if time_elm and hasattr (time_elm, 'symbol'):
752 change.style = { 'single-number': "'single-digit",
755 'normal': "'()"}.get (time_elm.symbol, "'()")
759 # TODO: Handle senza-misura measures
760 # TODO: Handle hidden time signatures (print-object="no")
761 # TODO: What shall we do if the symbol clashes with the sig? e.g. "cut"
762 # with 3/8 or "single-number" with (2+3)/8 or 3/8+2/4?
766 def musicxml_key_to_lily (attributes):
767 key_sig = attributes.get_key_signature ()
768 if not key_sig or not (isinstance (key_sig, list) or isinstance (key_sig, tuple)):
769 ly.warning (_ ("Unable to extract key signature!"))
772 change = musicexp.KeySignatureChange()
774 if len (key_sig) == 2 and not isinstance (key_sig[0], list):
775 # standard key signature, (fifths, mode)
776 (fifths, mode) = key_sig
779 start_pitch = musicexp.Pitch ()
780 start_pitch.octave = 0
794 start_pitch.alteration = a
796 ly.warning (_ ("unknown mode %s, expecting 'major' or 'minor' "
797 "or a church mode!") % mode)
799 fifth = musicexp.Pitch()
805 for x in range (fifths):
806 start_pitch = start_pitch.transposed (fifth)
807 change.tonic = start_pitch
810 # Non-standard key signature of the form [[step,alter<,octave>],...]
811 # MusicXML contains C,D,E,F,G,A,B as steps, lily uses 0-7, so convert
814 k[0] = musicxml_step_to_lily (k[0])
815 alterations.append (k)
816 change.non_standard_alterations = alterations
819 def musicxml_transpose_to_lily (attributes):
820 transpose = attributes.get_transposition ()
824 shift = musicexp.Pitch ()
825 octave_change = transpose.get_maybe_exist_named_child ('octave-change')
827 shift.octave = string.atoi (octave_change.get_text ())
828 chromatic_shift = string.atoi (transpose.get_named_child ('chromatic').get_text ())
829 chromatic_shift_normalized = chromatic_shift % 12;
830 (shift.step, shift.alteration) = [
831 (0,0), (0,1), (1,0), (2,-1), (2,0),
832 (3,0), (3,1), (4,0), (5,-1), (5,0),
833 (6,-1), (6,0)][chromatic_shift_normalized];
835 shift.octave += (chromatic_shift - chromatic_shift_normalized) / 12
837 diatonic = transpose.get_maybe_exist_named_child ('diatonic')
839 diatonic_step = string.atoi (diatonic.get_text ()) % 7
840 if diatonic_step != shift.step:
841 # We got the alter incorrect!
842 old_semitones = shift.semitones ()
843 shift.step = diatonic_step
844 new_semitones = shift.semitones ()
845 shift.alteration += old_semitones - new_semitones
847 transposition = musicexp.Transposition ()
848 transposition.pitch = musicexp.Pitch ().transposed (shift)
851 def musicxml_staff_details_to_lily (attributes):
852 details = attributes.get_maybe_exist_named_child ('staff-details')
856 ## TODO: Handle staff-type, staff-lines, staff-tuning, capo, staff-size
859 stafflines = details.get_maybe_exist_named_child ('staff-lines')
861 lines = string.atoi (stafflines.get_text ());
862 lines_event = musicexp.StaffLinesEvent (lines);
863 ret.append (lines_event);
868 def musicxml_attributes_to_lily (attrs):
871 'clef': musicxml_clef_to_lily,
872 'time': musicxml_time_to_lily,
873 'key': musicxml_key_to_lily,
874 'transpose': musicxml_transpose_to_lily,
875 'staff-details': musicxml_staff_details_to_lily,
877 for (k, func) in attr_dispatch.items ():
878 children = attrs.get_named_children (k)
881 if isinstance (ev, list):
889 def extract_display_text (el):
890 child = el.get_maybe_exist_named_child ("display-text")
892 return child.get_text ()
897 def musicxml_print_to_lily (el):
898 # TODO: Implement other print attributes
899 # <!ELEMENT print (page-layout?, system-layout?, staff-layout*,
900 # measure-layout?, measure-numbering?, part-name-display?,
901 # part-abbreviation-display?)>
903 # staff-spacing %tenths; #IMPLIED
904 # new-system %yes-no; #IMPLIED
905 # new-page %yes-no-number; #IMPLIED
906 # blank-page NMTOKEN #IMPLIED
907 # page-number CDATA #IMPLIED
910 if (hasattr (el, "new-system") and conversion_settings.convert_page_layout):
911 val = getattr (el, "new-system")
913 elts.append (musicexp.Break ("break"))
914 if (hasattr (el, "new-page") and conversion_settings.convert_page_layout):
915 val = getattr (el, "new-page")
917 elts.append (musicexp.Break ("pageBreak"))
918 child = el.get_maybe_exist_named_child ("part-name-display")
920 elts.append (musicexp.SetEvent ("Staff.instrumentName",
921 "\"%s\"" % extract_display_text (child)))
922 child = el.get_maybe_exist_named_child ("part-abbreviation-display")
924 elts.append (musicexp.SetEvent ("Staff.shortInstrumentName",
925 "\"%s\"" % extract_display_text (child)))
929 class Marker (musicexp.Music):
933 def print_ly (self, printer):
934 ly.warning (_ ("Encountered unprocessed marker %s\n") % self)
936 def ly_expression (self):
938 class RepeatMarker (Marker):
940 Marker.__init__ (self)
942 class EndingMarker (Marker):
945 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
946 # and to RepeatMarker and EndingMarker objects for repeat and
947 # alternatives start/stops
948 def musicxml_barline_to_lily (barline):
949 # retval contains all possible markers in the order:
950 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
952 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
953 repeat_element = barline.get_maybe_exist_named_child ("repeat")
954 ending_element = barline.get_maybe_exist_named_child ("ending")
958 bartype = bartype_element.get_text ()
960 if repeat_element and hasattr (repeat_element, 'direction'):
961 repeat = RepeatMarker ()
962 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
964 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
965 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
967 if hasattr (repeat_element, 'times'):
969 repeat.times = int (repeat_element.times)
972 repeat.event = barline
973 if repeat.direction == -1:
978 if ending_element and hasattr (ending_element, 'type'):
979 ending = EndingMarker ()
980 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
981 ending.event = barline
982 if ending.direction == -1:
988 b = musicexp.BarLine ()
992 return retval.values ()
994 spanner_event_dict = {
995 'beam' : musicexp.BeamEvent,
996 'dashes' : musicexp.TextSpannerEvent,
997 'bracket' : musicexp.BracketSpannerEvent,
998 'glissando' : musicexp.GlissandoEvent,
999 'octave-shift' : musicexp.OctaveShiftEvent,
1000 'pedal' : musicexp.PedalEvent,
1001 'slide' : musicexp.GlissandoEvent,
1002 'slur' : musicexp.SlurEvent,
1003 'wavy-line' : musicexp.TrillSpanEvent,
1004 'wedge' : musicexp.HairpinEvent
1006 spanner_type_dict = {
1020 def musicxml_spanner_to_lily_event (mxl_event):
1023 name = mxl_event.get_name()
1024 func = spanner_event_dict.get (name)
1028 ly.warning (_ ('unknown span event %s') % mxl_event)
1031 type = mxl_event.get_type ()
1032 span_direction = spanner_type_dict.get (type)
1033 # really check for None, because some types will be translated to 0, which
1034 # would otherwise also lead to the unknown span warning
1035 if span_direction != None:
1036 ev.span_direction = span_direction
1038 ly.warning (_ ('unknown span type %s for %s') % (type, name))
1040 ev.set_span_type (type)
1041 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
1043 # assign the size, which is used for octave-shift, etc.
1044 ev.size = mxl_event.get_size ()
1048 def musicxml_direction_to_indicator (direction):
1049 return { "above": 1, "upright": 1, "up": 1, "below": -1, "downright": -1, "down": -1, "inverted": -1 }.get (direction, 0)
1051 def musicxml_fermata_to_lily_event (mxl_event):
1052 ev = musicexp.ArticulationEvent ()
1053 txt = mxl_event.get_text ()
1054 # The contents of the element defined the shape, possible are normal, angled and square
1055 ev.type = { "angled": "shortfermata", "square": "longfermata" }.get (txt, "fermata")
1056 if hasattr (mxl_event, 'type'):
1057 dir = musicxml_direction_to_indicator (mxl_event.type)
1058 if dir and options.convert_directions:
1059 ev.force_direction = dir
1062 def musicxml_arpeggiate_to_lily_event (mxl_event):
1063 ev = musicexp.ArpeggioEvent ()
1064 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1067 def musicxml_nonarpeggiate_to_lily_event (mxl_event):
1068 ev = musicexp.ArpeggioEvent ()
1069 ev.non_arpeggiate = True
1070 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1073 def musicxml_tremolo_to_lily_event (mxl_event):
1074 ev = musicexp.TremoloEvent ()
1075 txt = mxl_event.get_text ()
1082 def musicxml_falloff_to_lily_event (mxl_event):
1083 ev = musicexp.BendEvent ()
1087 def musicxml_doit_to_lily_event (mxl_event):
1088 ev = musicexp.BendEvent ()
1092 def musicxml_bend_to_lily_event (mxl_event):
1093 ev = musicexp.BendEvent ()
1094 ev.alter = mxl_event.bend_alter ()
1097 def musicxml_caesura_to_lily_event (mxl_event):
1098 ev = musicexp.MarkupEvent ()
1099 # FIXME: default to straight or curved caesura?
1100 ev.contents = "\\musicglyph #\"scripts.caesura.straight\""
1101 ev.force_direction = 1
1104 def musicxml_fingering_event (mxl_event):
1105 ev = musicexp.ShortArticulationEvent ()
1106 ev.type = mxl_event.get_text ()
1109 def musicxml_string_event (mxl_event):
1110 ev = musicexp.NoDirectionArticulationEvent ()
1111 ev.type = mxl_event.get_text ()
1114 def musicxml_accidental_mark (mxl_event):
1115 ev = musicexp.MarkupEvent ()
1116 contents = { "sharp": "\\sharp",
1117 "natural": "\\natural",
1119 "double-sharp": "\\doublesharp",
1120 "sharp-sharp": "\\sharp\\sharp",
1121 "flat-flat": "\\flat\\flat",
1122 "flat-flat": "\\doubleflat",
1123 "natural-sharp": "\\natural\\sharp",
1124 "natural-flat": "\\natural\\flat",
1125 "quarter-flat": "\\semiflat",
1126 "quarter-sharp": "\\semisharp",
1127 "three-quarters-flat": "\\sesquiflat",
1128 "three-quarters-sharp": "\\sesquisharp",
1129 }.get (mxl_event.get_text ())
1131 ev.contents = contents
1136 # translate articulations, ornaments and other notations into ArticulationEvents
1138 # -) string (ArticulationEvent with that name)
1139 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
1140 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
1141 # TODO: Some translations are missing!
1142 articulations_dict = {
1143 "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
1144 "accidental-mark": musicxml_accidental_mark,
1145 "bend": musicxml_bend_to_lily_event,
1146 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
1147 "caesura": musicxml_caesura_to_lily_event,
1148 #"delayed-turn": "?",
1149 "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
1150 "doit": musicxml_doit_to_lily_event,
1151 #"double-tongue": "?",
1152 "down-bow": "downbow",
1153 "falloff": musicxml_falloff_to_lily_event,
1154 "fingering": musicxml_fingering_event,
1155 #"fingernails": "?",
1158 "harmonic": "flageolet",
1160 "inverted-mordent": "prall",
1161 "inverted-turn": "reverseturn",
1162 "mordent": "mordent",
1163 "open-string": "open",
1170 "snap-pizzicato": "snappizzicato",
1172 "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
1173 "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
1174 "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
1176 "string": musicxml_string_event,
1177 "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
1179 "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
1180 "thumb-position": "thumb",
1183 "tremolo": musicxml_tremolo_to_lily_event,
1184 "trill-mark": "trill",
1185 #"triple-tongue": "?",
1190 articulation_spanners = [ "wavy-line" ]
1192 def musicxml_articulation_to_lily_event (mxl_event):
1193 # wavy-line elements are treated as trill spanners, not as articulation ornaments
1194 if mxl_event.get_name () in articulation_spanners:
1195 return musicxml_spanner_to_lily_event (mxl_event)
1197 tmp_tp = articulations_dict.get (mxl_event.get_name ())
1201 if isinstance (tmp_tp, str):
1202 ev = musicexp.ArticulationEvent ()
1204 elif isinstance (tmp_tp, tuple):
1208 ev = tmp_tp (mxl_event)
1210 # Some articulations use the type attribute, other the placement...
1212 if hasattr (mxl_event, 'type') and options.convert_directions:
1213 dir = musicxml_direction_to_indicator (mxl_event.type)
1214 if hasattr (mxl_event, 'placement') and options.convert_directions:
1215 dir = musicxml_direction_to_indicator (mxl_event.placement)
1217 ev.force_direction = dir
1222 def musicxml_dynamics_to_lily_event (dynentry):
1223 dynamics_available = (
1224 "ppppp", "pppp", "ppp", "pp", "p", "mp", "mf",
1225 "f", "ff", "fff", "ffff", "fp", "sf", "sff", "sp", "spp", "sfz", "rfz" )
1226 dynamicsname = dynentry.get_name ()
1227 if dynamicsname == "other-dynamics":
1228 dynamicsname = dynentry.get_text ()
1229 if not dynamicsname or dynamicsname=="#text":
1232 if not dynamicsname in dynamics_available:
1233 # Get rid of - in tag names (illegal in ly tags!)
1234 dynamicstext = dynamicsname
1235 dynamicsname = string.replace (dynamicsname, "-", "")
1236 additional_definitions[dynamicsname] = dynamicsname + \
1237 " = #(make-dynamic-script \"" + dynamicstext + "\")"
1238 needed_additional_definitions.append (dynamicsname)
1239 event = musicexp.DynamicsEvent ()
1240 event.type = dynamicsname
1243 # Convert single-color two-byte strings to numbers 0.0 - 1.0
1244 def hexcolorval_to_nr (hex_val):
1246 v = int (hex_val, 16)
1253 def hex_to_color (hex_val):
1254 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)
1256 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
1260 def musicxml_words_to_lily_event (words):
1261 event = musicexp.TextEvent ()
1262 text = words.get_text ()
1263 text = re.sub ('^ *\n? *', '', text)
1264 text = re.sub (' *\n? *$', '', text)
1267 if hasattr (words, 'default-y') and options.convert_directions:
1268 offset = getattr (words, 'default-y')
1270 off = string.atoi (offset)
1272 event.force_direction = 1
1274 event.force_direction = -1
1276 event.force_direction = 0
1278 if hasattr (words, 'font-weight'):
1279 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
1281 event.markup += font_weight
1283 if hasattr (words, 'font-size'):
1284 size = getattr (words, 'font-size')
1286 "xx-small": '\\teeny',
1287 "x-small": '\\tiny',
1291 "x-large": '\\huge',
1292 "xx-large": '\\larger\\huge'
1295 event.markup += font_size
1297 if hasattr (words, 'color'):
1298 color = getattr (words, 'color')
1299 rgb = hex_to_color (color)
1301 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
1303 if hasattr (words, 'font-style'):
1304 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
1306 event.markup += font_style
1308 # TODO: How should I best convert the font-family attribute?
1310 # TODO: How can I represent the underline, overline and line-through
1311 # attributes in LilyPond? Values of these attributes indicate
1312 # the number of lines
1317 # convert accordion-registration to lilypond.
1318 # Since lilypond does not have any built-in commands, we need to create
1319 # the markup commands manually and define our own variables.
1320 # Idea was taken from: http://lsr.dsi.unimi.it/LSR/Item?id=194
1321 def musicxml_accordion_to_markup (mxl_event):
1322 commandname = "accReg"
1325 high = mxl_event.get_maybe_exist_named_child ('accordion-high')
1328 command += """\\combine
1329 \\raise #2.5 \\musicglyph #\"accordion.dot\"
1331 middle = mxl_event.get_maybe_exist_named_child ('accordion-middle')
1333 # By default, use one dot (when no or invalid content is given). The
1334 # MusicXML spec is quiet about this case...
1337 txt = string.atoi (middle.get_text ())
1341 commandname += "MMM"
1342 command += """\\combine
1343 \\raise #1.5 \\musicglyph #\"accordion.dot\"
1345 \\raise #1.5 \\translate #(cons 1 0) \\musicglyph #\"accordion.dot\"
1347 \\raise #1.5 \\translate #(cons -1 0) \\musicglyph #\"accordion.dot\"
1351 command += """\\combine
1352 \\raise #1.5 \\translate #(cons 0.5 0) \\musicglyph #\"accordion.dot\"
1354 \\raise #1.5 \\translate #(cons -0.5 0) \\musicglyph #\"accordion.dot\"
1358 command += """\\combine
1359 \\raise #1.5 \\musicglyph #\"accordion.dot\"
1361 low = mxl_event.get_maybe_exist_named_child ('accordion-low')
1364 command += """\\combine
1365 \\raise #0.5 \musicglyph #\"accordion.dot\"
1368 command += "\musicglyph #\"accordion.discant\""
1369 command = "\\markup { \\normalsize %s }" % command
1370 # Define the newly built command \accReg[H][MMM][L]
1371 additional_definitions[commandname] = "%s = %s" % (commandname, command)
1372 needed_additional_definitions.append (commandname)
1373 return "\\%s" % commandname
1375 def musicxml_accordion_to_ly (mxl_event):
1376 txt = musicxml_accordion_to_markup (mxl_event)
1378 ev = musicexp.MarkEvent (txt)
1383 def musicxml_rehearsal_to_ly_mark (mxl_event):
1384 text = mxl_event.get_text ()
1387 # default is boxed rehearsal marks!
1389 if hasattr (mxl_event, 'enclosure'):
1390 encl = {"none": None, "square": "box", "circle": "circle" }.get (mxl_event.enclosure, None)
1392 text = "\\%s { %s }" % (encl, text)
1393 ev = musicexp.MarkEvent ("\\markup { %s }" % text)
1396 def musicxml_harp_pedals_to_ly (mxl_event):
1398 result = "\\harp-pedal #\""
1399 for t in mxl_event.get_named_children ('pedal-tuning'):
1400 alter = t.get_named_child ('pedal-alter')
1402 val = int (alter.get_text ().strip ())
1403 result += {1: "v", 0: "-", -1: "^"}.get (val, "")
1407 ev = musicexp.MarkupEvent ()
1408 ev.contents = result + "\""
1411 def musicxml_eyeglasses_to_ly (mxl_event):
1412 needed_additional_definitions.append ("eyeglasses")
1413 return musicexp.MarkEvent ("\\markup { \\eyeglasses }")
1415 def next_non_hash_index (lst, pos):
1417 while pos < len (lst) and isinstance (lst[pos], musicxml.Hash_text):
1421 def musicxml_metronome_to_ly (mxl_event):
1422 children = mxl_event.get_all_children ()
1427 index = next_non_hash_index (children, index)
1428 if isinstance (children[index], musicxml.BeatUnit):
1429 # first form of metronome-mark, using unit and beats/min or other unit
1430 ev = musicexp.TempoMark ()
1431 if hasattr (mxl_event, 'parentheses'):
1432 ev.set_parentheses (mxl_event.parentheses == "yes")
1434 d = musicexp.Duration ()
1435 d.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1436 index = next_non_hash_index (children, index)
1437 if isinstance (children[index], musicxml.BeatUnitDot):
1439 index = next_non_hash_index (children, index)
1440 ev.set_base_duration (d)
1441 if isinstance (children[index], musicxml.BeatUnit):
1442 # Form "note = newnote"
1443 newd = musicexp.Duration ()
1444 newd.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1445 index = next_non_hash_index (children, index)
1446 if isinstance (children[index], musicxml.BeatUnitDot):
1448 index = next_non_hash_index (children, index)
1449 ev.set_new_duration (newd)
1450 elif isinstance (children[index], musicxml.PerMinute):
1453 beats = int (children[index].get_text ())
1454 ev.set_beats_per_minute (beats)
1458 ly.warning (_ ("Unknown metronome mark, ignoring"))
1462 #TODO: Implement the other (more complex) way for tempo marks!
1463 ly.warning (_ ("Metronome marks with complex relations (<metronome-note> in MusicXML) are not yet implemented."))
1466 # translate directions into Events, possible values:
1467 # -) string (MarkEvent with that command)
1468 # -) function (function(mxl_event) needs to return a full Event-derived object
1469 # -) (class, name) (like string, only that a different class than MarkEvent is used)
1471 'accordion-registration' : musicxml_accordion_to_ly,
1472 'coda' : (musicexp.MusicGlyphMarkEvent, "coda"),
1475 'eyeglasses': musicxml_eyeglasses_to_ly,
1476 'harp-pedals' : musicxml_harp_pedals_to_ly,
1478 'metronome' : musicxml_metronome_to_ly,
1479 'rehearsal' : musicxml_rehearsal_to_ly_mark,
1480 # 'scordatura' : ???
1481 'segno' : (musicexp.MusicGlyphMarkEvent, "segno"),
1482 'words' : musicxml_words_to_lily_event,
1484 directions_spanners = [ 'octave-shift', 'pedal', 'wedge', 'dashes', 'bracket' ]
1486 def musicxml_direction_to_lily (n):
1487 # TODO: Handle the <staff> element!
1489 # placement applies to all children!
1491 if hasattr (n, 'placement') and options.convert_directions:
1492 dir = musicxml_direction_to_indicator (n.placement)
1493 dirtype_children = []
1494 # TODO: The direction-type is used for grouping (e.g. dynamics with text),
1495 # so we can't simply flatten them out!
1496 for dt in n.get_typed_children (musicxml.DirType):
1497 dirtype_children += dt.get_all_children ()
1499 for entry in dirtype_children:
1500 # backets, dashes, octave shifts. pedal marks, hairpins etc. are spanners:
1501 if entry.get_name() in directions_spanners:
1502 event = musicxml_spanner_to_lily_event (entry)
1507 # now treat all the "simple" ones, that can be translated using the dict
1509 tmp_tp = directions_dict.get (entry.get_name (), None)
1510 if isinstance (tmp_tp, str): # string means MarkEvent
1511 ev = musicexp.MarkEvent (tmp_tp)
1512 elif isinstance (tmp_tp, tuple): # tuple means (EventClass, "text")
1513 ev = tmp_tp[0] (tmp_tp[1])
1517 # TODO: set the correct direction! Unfortunately, \mark in ly does
1518 # not seem to support directions!
1519 ev.force_direction = dir
1523 if entry.get_name () == "dynamics":
1524 for dynentry in entry.get_all_children ():
1525 ev = musicxml_dynamics_to_lily_event (dynentry)
1531 def musicxml_frame_to_lily_event (frame):
1532 ev = musicexp.FretEvent ()
1533 ev.strings = frame.get_strings ()
1534 ev.frets = frame.get_frets ()
1535 #offset = frame.get_first_fret () - 1
1537 for fn in frame.get_named_children ('frame-note'):
1538 fret = fn.get_fret ()
1541 el = [ fn.get_string (), fret ]
1542 fingering = fn.get_fingering ()
1544 el.append (fingering)
1545 ev.elements.append (el)
1548 barre[0] = el[0] # start string
1549 barre[2] = el[1] # fret
1551 barre[1] = el[0] # end string
1556 def musicxml_harmony_to_lily (n):
1558 for f in n.get_named_children ('frame'):
1559 ev = musicxml_frame_to_lily_event (f)
1565 notehead_styles_dict = {
1567 'triangle': '\'triangle',
1568 'diamond': '\'diamond',
1569 'square': '\'la', # TODO: Proper squared note head
1570 'cross': None, # TODO: + shaped note head
1572 'circle-x': '\'xcircle',
1573 'inverted triangle': None, # TODO: Implement
1574 'arrow down': None, # TODO: Implement
1575 'arrow up': None, # TODO: Implement
1576 'slashed': None, # TODO: Implement
1577 'back slashed': None, # TODO: Implement
1579 'cluster': None, # TODO: Implement
1590 def musicxml_notehead_to_lily (nh):
1594 style = notehead_styles_dict.get (nh.get_text ().strip (), None)
1595 style_elm = musicexp.NotestyleEvent ()
1597 style_elm.style = style
1598 if hasattr (nh, 'filled'):
1599 style_elm.filled = (getattr (nh, 'filled') == "yes")
1600 if style_elm.style or (style_elm.filled != None):
1601 styles.append (style_elm)
1604 if hasattr (nh, 'parentheses') and (nh.parentheses == "yes"):
1605 styles.append (musicexp.ParenthesizeEvent ())
1609 def musicxml_chordpitch_to_lily (mxl_cpitch):
1610 r = musicexp.ChordPitch ()
1611 r.alteration = mxl_cpitch.get_alteration ()
1612 r.step = musicxml_step_to_lily (mxl_cpitch.get_step ())
1618 'augmented': 'aug5',
1619 'diminished': 'dim5',
1622 'dominant-seventh': '7',
1623 'major-seventh': 'maj7',
1624 'minor-seventh': 'm7',
1625 'diminished-seventh': 'dim7',
1626 'augmented-seventh': 'aug7',
1627 'half-diminished': 'dim5m7',
1628 'major-minor': 'maj7m5',
1631 'minor-sixth': 'm6',
1633 'dominant-ninth': '9',
1634 'major-ninth': 'maj9',
1635 'minor-ninth': 'm9',
1636 # 11ths (usually as the basis for alteration):
1637 'dominant-11th': '11',
1638 'major-11th': 'maj11',
1639 'minor-11th': 'm11',
1640 # 13ths (usually as the basis for alteration):
1641 'dominant-13th': '13.11',
1642 'major-13th': 'maj13.11',
1643 'minor-13th': 'm13',
1645 'suspended-second': 'sus2',
1646 'suspended-fourth': 'sus4',
1647 # Functional sixths:
1649 #'Neapolitan': '???',
1654 #'pedal': '???',(pedal-point bass)
1661 def musicxml_chordkind_to_lily (kind):
1662 res = chordkind_dict.get (kind, None)
1663 # Check for None, since a major chord is converted to ''
1665 ly.warning (_ ("Unable to convert chord type %s to lilypond.") % kind)
1668 def musicxml_harmony_to_lily_chordname (n):
1670 root = n.get_maybe_exist_named_child ('root')
1672 ev = musicexp.ChordNameEvent ()
1673 ev.root = musicxml_chordpitch_to_lily (root)
1674 kind = n.get_maybe_exist_named_child ('kind')
1676 ev.kind = musicxml_chordkind_to_lily (kind.get_text ())
1679 bass = n.get_maybe_exist_named_child ('bass')
1681 ev.bass = musicxml_chordpitch_to_lily (bass)
1682 inversion = n.get_maybe_exist_named_child ('inversion')
1684 # TODO: LilyPond does not support inversions, does it?
1686 # Mail from Carl Sorensen on lilypond-devel, June 11, 2008:
1687 # 4. LilyPond supports the first inversion in the form of added
1688 # bass notes. So the first inversion of C major would be c:/g.
1689 # To get the second inversion of C major, you would need to do
1690 # e:6-3-^5 or e:m6-^5. However, both of these techniques
1691 # require you to know the chord and calculate either the fifth
1692 # pitch (for the first inversion) or the third pitch (for the
1693 # second inversion) so they may not be helpful for musicxml2ly.
1694 inversion_count = string.atoi (inversion.get_text ())
1695 if inversion_count == 1:
1696 # TODO: Calculate the bass note for the inversion...
1699 for deg in n.get_named_children ('degree'):
1700 d = musicexp.ChordModification ()
1701 d.type = deg.get_type ()
1702 d.step = deg.get_value ()
1703 d.alteration = deg.get_alter ()
1704 ev.add_modification (d)
1705 #TODO: convert the user-symbols attribute:
1706 #major: a triangle, like Unicode 25B3
1707 #minor: -, like Unicode 002D
1708 #augmented: +, like Unicode 002B
1709 #diminished: (degree), like Unicode 00B0
1710 #half-diminished: (o with slash), like Unicode 00F8
1716 def musicxml_figured_bass_note_to_lily (n):
1717 res = musicexp.FiguredBassNote ()
1718 suffix_dict = { 'sharp' : "+",
1721 'double-sharp' : "++",
1723 'sharp-sharp' : "++",
1725 prefix = n.get_maybe_exist_named_child ('prefix')
1727 res.set_prefix (suffix_dict.get (prefix.get_text (), ""))
1728 fnumber = n.get_maybe_exist_named_child ('figure-number')
1730 res.set_number (fnumber.get_text ())
1731 suffix = n.get_maybe_exist_named_child ('suffix')
1733 res.set_suffix (suffix_dict.get (suffix.get_text (), ""))
1734 if n.get_maybe_exist_named_child ('extend'):
1735 # TODO: Implement extender lines (unfortunately, in lilypond you have
1736 # to use \set useBassFigureExtenders = ##t, which turns them on
1737 # globally, while MusicXML has a property for each note...
1738 # I'm not sure there is a proper way to implement this cleanly
1745 def musicxml_figured_bass_to_lily (n):
1746 if not isinstance (n, musicxml.FiguredBass):
1748 res = musicexp.FiguredBassEvent ()
1749 for i in n.get_named_children ('figure'):
1750 note = musicxml_figured_bass_note_to_lily (i)
1753 dur = n.get_maybe_exist_named_child ('duration')
1755 # apply the duration to res
1756 length = Rational(int(dur.get_text()), n._divisions)*Rational(1,4)
1757 res.set_real_duration (length)
1758 duration = rational_to_lily_duration (length)
1760 res.set_duration (duration)
1761 if hasattr (n, 'parentheses') and n.parentheses == "yes":
1762 res.set_parentheses (True)
1765 instrument_drumtype_dict = {
1766 'Acoustic Snare Drum': 'acousticsnare',
1767 'Side Stick': 'sidestick',
1768 'Open Triangle': 'opentriangle',
1769 'Mute Triangle': 'mutetriangle',
1770 'Tambourine': 'tambourine',
1771 'Bass Drum': 'bassdrum',
1774 def musicxml_note_to_lily_main_event (n):
1779 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1781 pitch = musicxml_pitch_to_lily (mxl_pitch)
1782 event = musicexp.NoteEvent ()
1785 acc = n.get_maybe_exist_named_child ('accidental')
1787 # let's not force accs everywhere.
1788 event.cautionary = acc.cautionary
1789 # TODO: Handle editorial accidentals
1790 # TODO: Handle the level-display setting for displaying brackets/parentheses
1792 elif n.get_maybe_exist_typed_child (musicxml.Unpitched):
1793 # Unpitched elements have display-step and can also have
1795 unpitched = n.get_maybe_exist_typed_child (musicxml.Unpitched)
1796 event = musicexp.NoteEvent ()
1797 event.pitch = musicxml_unpitched_to_lily (unpitched)
1799 elif n.get_maybe_exist_typed_child (musicxml.Rest):
1800 # rests can have display-octave and display-step, which are
1801 # treated like an ordinary note pitch
1802 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1803 event = musicexp.RestEvent ()
1804 if options.convert_rest_positions:
1805 pitch = musicxml_restdisplay_to_lily (rest)
1808 elif n.instrument_name:
1809 event = musicexp.NoteEvent ()
1810 drum_type = instrument_drumtype_dict.get (n.instrument_name)
1812 event.drum_type = drum_type
1814 n.message (_ ("drum %s type unknown, please add to instrument_drumtype_dict") % n.instrument_name)
1815 event.drum_type = 'acousticsnare'
1818 n.message (_ ("cannot find suitable event"))
1821 event.duration = musicxml_duration_to_lily (n)
1823 noteheads = n.get_named_children ('notehead')
1824 for nh in noteheads:
1825 styles = musicxml_notehead_to_lily (nh)
1827 event.add_associated_event (s)
1831 def musicxml_lyrics_to_text (lyrics):
1832 # TODO: Implement text styles for lyrics syllables
1836 for e in lyrics.get_all_children ():
1837 if isinstance (e, musicxml.Syllabic):
1838 continued = e.continued ()
1839 elif isinstance (e, musicxml.Text):
1840 # We need to convert soft hyphens to -, otherwise the ascii codec as well
1841 # as lilypond will barf on that character
1842 text += string.replace( e.get_text(), u'\xad', '-' )
1843 elif isinstance (e, musicxml.Elision):
1848 elif isinstance (e, musicxml.Extend):
1853 if text == "-" and continued:
1855 elif text == "_" and extended:
1857 elif continued and text:
1858 return musicxml.escape_ly_output_string (text) + " --"
1861 elif extended and text:
1862 return musicxml.escape_ly_output_string (text) + " __"
1866 return musicxml.escape_ly_output_string (text)
1872 def __init__ (self, here, dest):
1876 class LilyPondVoiceBuilder:
1877 def __init__ (self):
1879 self.pending_dynamics = []
1880 self.end_moment = Rational (0)
1881 self.begin_moment = Rational (0)
1882 self.pending_multibar = Rational (0)
1883 self.ignore_skips = False
1884 self.has_relevant_elements = False
1885 self.measure_length = Rational (4, 4)
1887 def _insert_multibar (self):
1888 layout_information.set_context_item ('Score', 'skipBars = ##t')
1889 r = musicexp.MultiMeasureRest ()
1890 lenfrac = self.measure_length
1891 r.duration = rational_to_lily_duration (lenfrac)
1892 r.duration.factor *= self.pending_multibar / lenfrac
1893 self.elements.append (r)
1894 self.begin_moment = self.end_moment
1895 self.end_moment = self.begin_moment + self.pending_multibar
1896 self.pending_multibar = Rational (0)
1898 def set_measure_length (self, mlen):
1899 if (mlen != self.measure_length) and self.pending_multibar:
1900 self._insert_multibar ()
1901 self.measure_length = mlen
1903 def add_multibar_rest (self, duration):
1904 self.pending_multibar += duration
1906 def set_duration (self, duration):
1907 self.end_moment = self.begin_moment + duration
1908 def current_duration (self):
1909 return self.end_moment - self.begin_moment
1911 def add_music (self, music, duration, relevant = True):
1912 assert isinstance (music, musicexp.Music)
1913 if self.pending_multibar > Rational (0):
1914 self._insert_multibar ()
1916 self.has_relevant_elements = self.has_relevant_elements or relevant
1917 self.elements.append (music)
1918 self.begin_moment = self.end_moment
1919 self.set_duration (duration)
1921 # Insert all pending dynamics right after the note/rest:
1922 if isinstance (music, musicexp.ChordEvent) and self.pending_dynamics:
1923 for d in self.pending_dynamics:
1925 self.pending_dynamics = []
1927 # Insert some music command that does not affect the position in the measure
1928 def add_command (self, command, relevant = True):
1929 assert isinstance (command, musicexp.Music)
1930 if self.pending_multibar > Rational (0):
1931 self._insert_multibar ()
1932 self.has_relevant_elements = self.has_relevant_elements or relevant
1933 self.elements.append (command)
1934 def add_barline (self, barline, relevant = False):
1935 # Insert only if we don't have a barline already
1936 # TODO: Implement proper merging of default barline and custom bar line
1937 has_relevant = self.has_relevant_elements
1938 if (not (self.elements) or
1939 not (isinstance (self.elements[-1], musicexp.BarLine)) or
1940 (self.pending_multibar > Rational (0))):
1941 self.add_music (barline, Rational (0))
1942 self.has_relevant_elements = has_relevant or relevant
1943 def add_partial (self, command):
1944 self.ignore_skips = True
1945 # insert the partial, but restore relevant_elements (partial is not relevant)
1946 relevant = self.has_relevant_elements
1947 self.add_command (command)
1948 self.has_relevant_elements = relevant
1950 def add_dynamics (self, dynamic):
1951 # store the dynamic item(s) until we encounter the next note/rest:
1952 self.pending_dynamics.append (dynamic)
1954 def add_bar_check (self, number):
1955 # re/store has_relevant_elements, so that a barline alone does not
1956 # trigger output for figured bass, chord names
1957 b = musicexp.BarLine ()
1958 b.bar_number = number
1959 self.add_barline (b)
1961 def jumpto (self, moment):
1962 current_end = self.end_moment + self.pending_multibar
1963 diff = moment - current_end
1965 if diff < Rational (0):
1966 ly.warning (_ ('Negative skip %s (from position %s to %s)') %
1967 (diff, current_end, moment))
1970 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
1971 skip = musicexp.SkipEvent()
1973 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)
1975 # TODO: Use the time signature for skips, too. Problem: The skip
1976 # might not start at a measure boundary!
1977 if duration_log > 0: # denominator is a power of 2...
1978 if diff.numerator () == 3:
1982 duration_factor = Rational (diff.numerator ())
1984 # for skips of a whole or more, simply use s1*factor
1986 duration_factor = diff
1987 skip.duration.duration_log = duration_log
1988 skip.duration.factor = duration_factor
1989 skip.duration.dots = duration_dots
1991 evc = musicexp.ChordEvent ()
1992 evc.elements.append (skip)
1993 self.add_music (evc, diff, False)
1995 if diff > Rational (0) and moment == 0:
1996 self.ignore_skips = False
1998 def last_event_chord (self, starting_at):
2002 # if the position matches, find the last ChordEvent, do not cross a bar line!
2003 at = len( self.elements ) - 1
2005 not isinstance (self.elements[at], musicexp.ChordEvent) and
2006 not isinstance (self.elements[at], musicexp.BarLine)):
2011 and isinstance (self.elements[at], musicexp.ChordEvent)
2012 and self.begin_moment == starting_at):
2013 value = self.elements[at]
2015 self.jumpto (starting_at)
2019 def correct_negative_skip (self, goto):
2020 self.end_moment = goto
2021 self.begin_moment = goto
2022 evc = musicexp.ChordEvent ()
2023 self.elements.append (evc)
2027 def __init__ (self):
2028 self.voicename = None
2029 self.voicedata = None
2030 self.ly_voice = None
2031 self.figured_bass = None
2032 self.chordnames = None
2033 self.lyrics_dict = {}
2034 self.lyrics_order = []
2036 def measure_length_from_attributes (attr, current_measure_length):
2037 len = attr.get_measure_length ()
2039 len = current_measure_length
2042 def musicxml_voice_to_lily_voice (voice):
2046 return_value = VoiceData ()
2047 return_value.voicedata = voice
2049 # First pitch needed for relative mode (if selected in command-line options)
2052 # Needed for melismata detection (ignore lyrics on those notes!):
2057 ignore_lyrics = False
2059 current_staff = None
2061 pending_figured_bass = []
2062 pending_chordnames = []
2064 # Make sure that the keys in the dict don't get reordered, since
2065 # we need the correct ordering of the lyrics stanzas! By default,
2066 # a dict will reorder its keys
2067 return_value.lyrics_order = voice.get_lyrics_numbers ()
2068 for k in return_value.lyrics_order:
2071 voice_builder = LilyPondVoiceBuilder ()
2072 figured_bass_builder = LilyPondVoiceBuilder ()
2073 chordnames_builder = LilyPondVoiceBuilder ()
2074 current_measure_length = Rational (4, 4)
2075 voice_builder.set_measure_length (current_measure_length)
2077 for n in voice._elements:
2079 if n.get_name () == 'forward':
2081 staff = n.get_maybe_exist_named_child ('staff')
2083 staff = staff.get_text ()
2084 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
2085 voice_builder.add_command (musicexp.StaffChange (staff))
2086 current_staff = staff
2088 if isinstance (n, musicxml.Partial) and n.partial > 0:
2089 a = musicxml_partial_to_lily (n.partial)
2091 voice_builder.add_partial (a)
2092 figured_bass_builder.add_partial (a)
2093 chordnames_builder.add_partial (a)
2096 is_chord = n.get_maybe_exist_named_child ('chord')
2097 is_after_grace = (isinstance (n, musicxml.Note) and n.is_after_grace ());
2098 if not is_chord and not is_after_grace:
2100 voice_builder.jumpto (n._when)
2101 figured_bass_builder.jumpto (n._when)
2102 chordnames_builder.jumpto (n._when)
2103 except NegativeSkip, neg:
2104 voice_builder.correct_negative_skip (n._when)
2105 figured_bass_builder.correct_negative_skip (n._when)
2106 chordnames_builder.correct_negative_skip (n._when)
2107 n.message (_ ("Negative skip found: from %s to %s, difference is %s") % (neg.here, neg.dest, neg.dest - neg.here))
2109 if isinstance (n, musicxml.Barline):
2110 barlines = musicxml_barline_to_lily (n)
2112 if isinstance (a, musicexp.BarLine):
2113 voice_builder.add_barline (a)
2114 figured_bass_builder.add_barline (a, False)
2115 chordnames_builder.add_barline (a, False)
2116 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
2117 voice_builder.add_command (a)
2118 figured_bass_builder.add_barline (a, False)
2119 chordnames_builder.add_barline (a, False)
2123 if isinstance (n, musicxml.Print):
2124 for a in musicxml_print_to_lily (n):
2125 voice_builder.add_command (a, False)
2128 # Continue any multimeasure-rests before trying to add bar checks!
2129 # Don't handle new MM rests yet, because for them we want bar checks!
2130 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
2131 if (rest and rest.is_whole_measure ()
2132 and voice_builder.pending_multibar > Rational (0)):
2133 voice_builder.add_multibar_rest (n._duration)
2137 # print a bar check at the beginning of each measure!
2138 if n.is_first () and n._measure_position == Rational (0) and n != voice._elements[0]:
2140 num = int (n.get_parent ().number)
2144 voice_builder.add_bar_check (num)
2145 figured_bass_builder.add_bar_check (num)
2146 chordnames_builder.add_bar_check (num)
2148 # Start any new multimeasure rests
2149 if (rest and rest.is_whole_measure ()):
2150 voice_builder.add_multibar_rest (n._duration)
2154 if isinstance (n, musicxml.Direction):
2155 for a in musicxml_direction_to_lily (n):
2156 if a.wait_for_note ():
2157 voice_builder.add_dynamics (a)
2159 voice_builder.add_command (a)
2162 if isinstance (n, musicxml.Harmony):
2163 for a in musicxml_harmony_to_lily (n):
2164 if a.wait_for_note ():
2165 voice_builder.add_dynamics (a)
2167 voice_builder.add_command (a)
2168 for a in musicxml_harmony_to_lily_chordname (n):
2169 pending_chordnames.append (a)
2172 if isinstance (n, musicxml.FiguredBass):
2173 a = musicxml_figured_bass_to_lily (n)
2175 pending_figured_bass.append (a)
2178 if isinstance (n, musicxml.Attributes):
2179 for a in musicxml_attributes_to_lily (n):
2180 voice_builder.add_command (a)
2181 measure_length = measure_length_from_attributes (n, current_measure_length)
2182 if current_measure_length != measure_length:
2183 current_measure_length = measure_length
2184 voice_builder.set_measure_length (current_measure_length)
2187 if not n.__class__.__name__ == 'Note':
2188 n.message (_ ('unexpected %s; expected %s or %s or %s') % (n, 'Note', 'Attributes', 'Barline'))
2191 main_event = musicxml_note_to_lily_main_event (n)
2192 if main_event and not first_pitch:
2193 first_pitch = main_event.pitch
2194 # ignore lyrics for notes inside a slur, tie, chord or beam
2195 ignore_lyrics = inside_slur or is_tied or is_chord or is_beamed
2197 if main_event and hasattr (main_event, 'drum_type') and main_event.drum_type:
2198 modes_found['drummode'] = True
2200 ev_chord = voice_builder.last_event_chord (n._when)
2202 ev_chord = musicexp.ChordEvent()
2203 voice_builder.add_music (ev_chord, n._duration)
2206 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
2208 is_after_grace = ev_chord.has_elements () or n.is_after_grace ();
2209 is_chord = n.get_maybe_exist_typed_child (musicxml.Chord)
2213 # after-graces and other graces use different lists; Depending on
2214 # whether we have a chord or not, obtain either a new ChordEvent or
2215 # the previous one to create a chord
2217 if ev_chord.after_grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2218 grace_chord = ev_chord.after_grace_elements.get_last_event_chord ()
2220 grace_chord = musicexp.ChordEvent ()
2221 ev_chord.append_after_grace (grace_chord)
2223 if ev_chord.grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2224 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
2226 grace_chord = musicexp.ChordEvent ()
2227 ev_chord.append_grace (grace_chord)
2229 if hasattr (grace, 'slash') and not is_after_grace:
2230 # TODO: use grace_type = "appoggiatura" for slurred grace notes
2231 if grace.slash == "yes":
2232 ev_chord.grace_type = "acciaccatura"
2233 # now that we have inserted the chord into the grace music, insert
2234 # everything into that chord instead of the ev_chord
2235 ev_chord = grace_chord
2236 ev_chord.append (main_event)
2237 ignore_lyrics = True
2239 ev_chord.append (main_event)
2240 # When a note/chord has grace notes (duration==0), the duration of the
2241 # event chord is not yet known, but the event chord was already added
2242 # with duration 0. The following correct this when we hit the real note!
2243 if voice_builder.current_duration () == 0 and n._duration > 0:
2244 voice_builder.set_duration (n._duration)
2246 # if we have a figured bass, set its voice builder to the correct position
2247 # and insert the pending figures
2248 if pending_figured_bass:
2250 figured_bass_builder.jumpto (n._when)
2251 except NegativeSkip, neg:
2253 for fb in pending_figured_bass:
2254 # if a duration is given, use that, otherwise the one of the note
2255 dur = fb.real_duration
2257 dur = ev_chord.get_length ()
2259 fb.duration = ev_chord.get_duration ()
2260 figured_bass_builder.add_music (fb, dur)
2261 pending_figured_bass = []
2263 if pending_chordnames:
2265 chordnames_builder.jumpto (n._when)
2266 except NegativeSkip, neg:
2268 for cn in pending_chordnames:
2269 # Assign the duration of the EventChord
2270 cn.duration = ev_chord.get_duration ()
2271 chordnames_builder.add_music (cn, ev_chord.get_length ())
2272 pending_chordnames = []
2274 notations_children = n.get_typed_children (musicxml.Notations)
2278 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
2279 # +tied | +slur | +tuplet | glissando | slide |
2280 # ornaments | technical | articulations | dynamics |
2281 # +fermata | arpeggiate | non-arpeggiate |
2282 # accidental-mark | other-notation
2283 for notations in notations_children:
2284 for tuplet_event in notations.get_tuplets():
2285 time_mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
2286 tuplet_events.append ((ev_chord, tuplet_event, time_mod))
2288 # First, close all open slurs, only then start any new slur
2289 # TODO: Record the number of the open slur to dtermine the correct
2291 endslurs = [s for s in notations.get_named_children ('slur')
2292 if s.get_type () in ('stop')]
2293 if endslurs and not inside_slur:
2294 endslurs[0].message (_ ('Encountered closing slur, but no slur is open'))
2296 if len (endslurs) > 1:
2297 endslurs[0].message (_ ('Cannot have two simultaneous (closing) slurs'))
2298 # record the slur status for the next note in the loop
2300 lily_ev = musicxml_spanner_to_lily_event (endslurs[0])
2301 ev_chord.append (lily_ev)
2303 startslurs = [s for s in notations.get_named_children ('slur')
2304 if s.get_type () in ('start')]
2305 if startslurs and inside_slur:
2306 startslurs[0].message (_ ('Cannot have a slur inside another slur'))
2308 if len (startslurs) > 1:
2309 startslurs[0].message (_ ('Cannot have two simultaneous slurs'))
2310 # record the slur status for the next note in the loop
2312 lily_ev = musicxml_spanner_to_lily_event (startslurs[0])
2313 ev_chord.append (lily_ev)
2317 mxl_tie = notations.get_tie ()
2318 if mxl_tie and mxl_tie.type == 'start':
2319 ev_chord.append (musicexp.TieEvent ())
2325 fermatas = notations.get_named_children ('fermata')
2327 ev = musicxml_fermata_to_lily_event (a)
2329 ev_chord.append (ev)
2331 arpeggiate = notations.get_named_children ('arpeggiate')
2332 for a in arpeggiate:
2333 ev = musicxml_arpeggiate_to_lily_event (a)
2335 ev_chord.append (ev)
2337 arpeggiate = notations.get_named_children ('non-arpeggiate')
2338 for a in arpeggiate:
2339 ev = musicxml_nonarpeggiate_to_lily_event (a)
2341 ev_chord.append (ev)
2343 glissandos = notations.get_named_children ('glissando')
2344 glissandos += notations.get_named_children ('slide')
2345 for a in glissandos:
2346 ev = musicxml_spanner_to_lily_event (a)
2348 ev_chord.append (ev)
2350 # accidental-marks are direct children of <notation>!
2351 for a in notations.get_named_children ('accidental-mark'):
2352 ev = musicxml_articulation_to_lily_event (a)
2354 ev_chord.append (ev)
2356 # Articulations can contain the following child elements:
2357 # accent | strong-accent | staccato | tenuto |
2358 # detached-legato | staccatissimo | spiccato |
2359 # scoop | plop | doit | falloff | breath-mark |
2360 # caesura | stress | unstress
2361 # Technical can contain the following child elements:
2362 # up-bow | down-bow | harmonic | open-string |
2363 # thumb-position | fingering | pluck | double-tongue |
2364 # triple-tongue | stopped | snap-pizzicato | fret |
2365 # string | hammer-on | pull-off | bend | tap | heel |
2366 # toe | fingernails | other-technical
2367 # Ornaments can contain the following child elements:
2368 # trill-mark | turn | delayed-turn | inverted-turn |
2369 # shake | wavy-line | mordent | inverted-mordent |
2370 # schleifer | tremolo | other-ornament, accidental-mark
2371 ornaments = notations.get_named_children ('ornaments')
2372 ornaments += notations.get_named_children ('articulations')
2373 ornaments += notations.get_named_children ('technical')
2376 for ch in a.get_all_children ():
2377 ev = musicxml_articulation_to_lily_event (ch)
2379 ev_chord.append (ev)
2381 dynamics = notations.get_named_children ('dynamics')
2383 for ch in a.get_all_children ():
2384 ev = musicxml_dynamics_to_lily_event (ch)
2386 ev_chord.append (ev)
2389 mxl_beams = [b for b in n.get_named_children ('beam')
2390 if (b.get_type () in ('begin', 'end')
2391 and b.is_primary ())]
2392 if mxl_beams and not conversion_settings.ignore_beaming:
2393 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
2395 ev_chord.append (beam_ev)
2396 if beam_ev.span_direction == -1: # beam and thus melisma starts here
2398 elif beam_ev.span_direction == 1: # beam and thus melisma ends here
2401 # Extract the lyrics
2402 if not rest and not ignore_lyrics:
2403 note_lyrics_processed = []
2404 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
2405 for l in note_lyrics_elements:
2406 if l.get_number () < 0:
2407 for k in lyrics.keys ():
2408 lyrics[k].append (musicxml_lyrics_to_text (l))
2409 note_lyrics_processed.append (k)
2411 lyrics[l.number].append(musicxml_lyrics_to_text (l))
2412 note_lyrics_processed.append (l.number)
2413 for lnr in lyrics.keys ():
2414 if not lnr in note_lyrics_processed:
2415 lyrics[lnr].append ("\skip4")
2417 # Assume that a <tie> element only lasts for one note.
2418 # This might not be correct MusicXML interpretation, but works for
2419 # most cases and fixes broken files, which have the end tag missing
2420 if is_tied and not tie_started:
2423 ## force trailing mm rests to be written out.
2424 voice_builder.add_music (musicexp.ChordEvent (), Rational (0))
2426 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
2427 ly_voice = group_repeats (ly_voice)
2429 seq_music = musicexp.SequentialMusic ()
2431 if 'drummode' in modes_found.keys ():
2432 ## \key <pitch> barfs in drummode.
2433 ly_voice = [e for e in ly_voice
2434 if not isinstance(e, musicexp.KeySignatureChange)]
2436 seq_music.elements = ly_voice
2437 for k in lyrics.keys ():
2438 return_value.lyrics_dict[k] = musicexp.Lyrics ()
2439 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
2442 if len (modes_found) > 1:
2443 ly.warning (_ ('cannot simultaneously have more than one mode: %s') % modes_found.keys ())
2445 if options.relative:
2446 v = musicexp.RelativeMusic ()
2447 v.element = seq_music
2448 v.basepitch = first_pitch
2451 return_value.ly_voice = seq_music
2452 for mode in modes_found.keys ():
2453 v = musicexp.ModeChangingMusicWrapper()
2454 v.element = seq_music
2456 return_value.ly_voice = v
2458 # create \figuremode { figured bass elements }
2459 if figured_bass_builder.has_relevant_elements:
2460 fbass_music = musicexp.SequentialMusic ()
2461 fbass_music.elements = group_repeats (figured_bass_builder.elements)
2462 v = musicexp.ModeChangingMusicWrapper()
2463 v.mode = 'figuremode'
2464 v.element = fbass_music
2465 return_value.figured_bass = v
2467 # create \chordmode { chords }
2468 if chordnames_builder.has_relevant_elements:
2469 cname_music = musicexp.SequentialMusic ()
2470 cname_music.elements = group_repeats (chordnames_builder.elements)
2471 v = musicexp.ModeChangingMusicWrapper()
2472 v.mode = 'chordmode'
2473 v.element = cname_music
2474 return_value.chordnames = v
2478 def musicxml_id_to_lily (id):
2479 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
2480 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
2482 for digit in digits:
2483 d = digits.index (digit)
2484 id = re.sub ('%d' % d, digit, id)
2486 id = re.sub ('[^a-zA-Z]', 'X', id)
2489 def musicxml_pitch_to_lily (mxl_pitch):
2490 p = musicexp.Pitch ()
2491 p.alteration = mxl_pitch.get_alteration ()
2492 p.step = musicxml_step_to_lily (mxl_pitch.get_step ())
2493 p.octave = mxl_pitch.get_octave () - 4
2496 def musicxml_unpitched_to_lily (mxl_unpitched):
2498 step = mxl_unpitched.get_step ()
2500 p = musicexp.Pitch ()
2501 p.step = musicxml_step_to_lily (step)
2502 octave = mxl_unpitched.get_octave ()
2504 p.octave = octave - 4
2507 def musicxml_restdisplay_to_lily (mxl_rest):
2509 step = mxl_rest.get_step ()
2511 p = musicexp.Pitch ()
2512 p.step = musicxml_step_to_lily (step)
2513 octave = mxl_rest.get_octave ()
2515 p.octave = octave - 4
2518 def voices_in_part (part):
2519 """Return a Name -> Voice dictionary for PART"""
2521 part.extract_voices ()
2522 voices = part.get_voices ()
2523 part_info = part.get_staff_attributes ()
2525 return (voices, part_info)
2527 def voices_in_part_in_parts (parts):
2528 """return a Part -> Name -> Voice dictionary"""
2529 # don't crash if p doesn't have an id (that's invalid MusicXML,
2530 # but such files are out in the wild!
2533 voices = voices_in_part (p)
2534 if (hasattr (p, "id")):
2535 dictionary[p.id] = voices
2537 # TODO: extract correct part id from other sources
2538 dictionary[None] = voices
2542 def get_all_voices (parts):
2543 all_voices = voices_in_part_in_parts (parts)
2546 all_ly_staffinfo = {}
2547 for p, (name_voice, staff_info) in all_voices.items ():
2550 for n, v in name_voice.items ():
2551 ly.progress (_ ("Converting to LilyPond expressions..."), True)
2552 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
2553 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
2555 all_ly_voices[p] = part_ly_voices
2556 all_ly_staffinfo[p] = staff_info
2558 return (all_ly_voices, all_ly_staffinfo)
2561 def option_parser ():
2562 p = ly.get_option_parser (usage = _ ("musicxml2ly [OPTION]... FILE.xml"),
2564 _ ("""Convert MusicXML from FILE.xml to LilyPond input.
2565 If the given filename is -, musicxml2ly reads from the command line.
2566 """), add_help_option=False)
2568 p.add_option("-h", "--help",
2570 help=_ ("show this help and exit"))
2572 p.version = ('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
2574 _ ("""Copyright (c) 2005--2012 by
2575 Han-Wen Nienhuys <hanwen@xs4all.nl>,
2576 Jan Nieuwenhuizen <janneke@gnu.org> and
2577 Reinhold Kainhofer <reinhold@kainhofer.com>
2581 This program is free software. It is covered by the GNU General Public
2582 License and you are welcome to change it and/or distribute copies of it
2583 under certain conditions. Invoke as `%s --warranty' for more
2584 information.""") % 'lilypond')
2586 p.add_option("--version",
2588 help=_ ("show version number and exit"))
2590 p.add_option ('-v', '--verbose',
2592 callback=ly.handle_loglevel_option,
2593 callback_args=("DEBUG",),
2594 help = _ ("be verbose"))
2596 p.add_option ('', '--lxml',
2597 action = "store_true",
2600 help = _ ("use lxml.etree; uses less memory and cpu time"))
2602 p.add_option ('-z', '--compressed',
2603 action = "store_true",
2604 dest = 'compressed',
2606 help = _ ("input file is a zip-compressed MusicXML file"))
2608 p.add_option ('-r', '--relative',
2609 action = "store_true",
2612 help = _ ("convert pitches in relative mode (default)"))
2614 p.add_option ('-a', '--absolute',
2615 action = "store_false",
2617 help = _ ("convert pitches in absolute mode"))
2619 p.add_option ('-l', '--language',
2620 metavar = _ ("LANG"),
2622 help = _ ("use LANG for pitch names, e.g. 'deutsch' for note names in German"))
2624 p.add_option ("--loglevel",
2625 help=_ ("Print log messages according to LOGLEVEL "
2626 "(NONE, ERROR, WARNING, PROGRESS (default), DEBUG)"),
2627 metavar=_ ("LOGLEVEL"),
2629 callback=ly.handle_loglevel_option,
2632 p.add_option ('--nd', '--no-articulation-directions',
2633 action = "store_false",
2635 dest = "convert_directions",
2636 help = _ ("do not convert directions (^, _ or -) for articulations, dynamics, etc."))
2638 p.add_option ('--nrp', '--no-rest-positions',
2639 action = "store_false",
2641 dest = "convert_rest_positions",
2642 help = _ ("do not convert exact vertical positions of rests"))
2644 p.add_option ('--npl', '--no-page-layout',
2645 action = "store_false",
2647 dest = "convert_page_layout",
2648 help = _ ("do not convert the exact page layout and breaks"))
2650 p.add_option ('--no-beaming',
2651 action = "store_false",
2653 dest = "convert_beaming",
2654 help = _ ("do not convert beaming information, use lilypond's automatic beaming instead"))
2656 p.add_option ('-o', '--output',
2657 metavar = _ ("FILE"),
2661 dest = 'output_name',
2662 help = _ ("set output filename to FILE, stdout if -"))
2664 p.add_option ('-m', '--midi',
2665 action = "store_true",
2668 help = _("add midi-block to .ly file"))
2670 p.add_option_group ('',
2672 _ ("Report bugs via %s")
2673 % 'http://post.gmane.org/post.php'
2674 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
2677 def music_xml_voice_name_to_lily_name (part_id, name):
2678 str = "Part%sVoice%s" % (part_id, name)
2679 return musicxml_id_to_lily (str)
2681 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
2682 str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
2683 return musicxml_id_to_lily (str)
2685 def music_xml_figuredbass_name_to_lily_name (part_id, voicename):
2686 str = "Part%sVoice%sFiguredBass" % (part_id, voicename)
2687 return musicxml_id_to_lily (str)
2689 def music_xml_chordnames_name_to_lily_name (part_id, voicename):
2690 str = "Part%sVoice%sChords" % (part_id, voicename)
2691 return musicxml_id_to_lily (str)
2693 def print_voice_definitions (printer, part_list, voices):
2694 for part in part_list:
2696 nv_dict = voices.get (part_id, {})
2697 for (name, voice) in nv_dict.items ():
2698 k = music_xml_voice_name_to_lily_name (part_id, name)
2699 printer.dump ('%s = ' % k)
2700 voice.ly_voice.print_ly (printer)
2702 if voice.chordnames:
2703 cnname = music_xml_chordnames_name_to_lily_name (part_id, name)
2704 printer.dump ('%s = ' % cnname )
2705 voice.chordnames.print_ly (printer)
2707 for l in voice.lyrics_order:
2708 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
2709 printer.dump ('%s = ' % lname )
2710 voice.lyrics_dict[l].print_ly (printer)
2712 if voice.figured_bass:
2713 fbname = music_xml_figuredbass_name_to_lily_name (part_id, name)
2714 printer.dump ('%s = ' % fbname )
2715 voice.figured_bass.print_ly (printer)
2720 return dict ([(elt,1) for elt in l]).keys ()
2722 # format the information about the staff in the form
2725 # [voiceid1, [lyricsid11, lyricsid12,...], figuredbassid1],
2726 # [voiceid2, [lyricsid21, lyricsid22,...], figuredbassid2],
2730 # raw_voices is of the form [(voicename, lyricsids, havefiguredbass)*]
2731 def format_staff_info (part_id, staff_id, raw_voices):
2733 for (v, lyricsids, figured_bass, chordnames) in raw_voices:
2734 voice_name = music_xml_voice_name_to_lily_name (part_id, v)
2735 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
2737 figured_bass_name = ''
2739 figured_bass_name = music_xml_figuredbass_name_to_lily_name (part_id, v)
2740 chordnames_name = ''
2742 chordnames_name = music_xml_chordnames_name_to_lily_name (part_id, v)
2743 voices.append ([voice_name, voice_lyrics, figured_bass_name, chordnames_name])
2744 return [staff_id, voices]
2746 def update_score_setup (score_structure, part_list, voices):
2748 for part_definition in part_list:
2749 part_id = part_definition.id
2750 nv_dict = voices.get (part_id)
2752 ly.warning (_ ('unknown part in part-list: %s') % part_id)
2755 staves = reduce (lambda x,y: x+ y,
2756 [voice.voicedata._staves.keys ()
2757 for voice in nv_dict.values ()],
2760 if len (staves) > 1:
2762 staves = uniq_list (staves)
2765 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2766 for (voice_name, voice) in nv_dict.items ()
2767 if voice.voicedata._start_staff == s]
2768 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
2770 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2771 for (voice_name, voice) in nv_dict.items ()]
2772 staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
2773 score_structure.set_part_information (part_id, staves_info)
2775 # Set global values in the \layout block, like auto-beaming etc.
2776 def update_layout_information ():
2777 if not conversion_settings.ignore_beaming and layout_information:
2778 layout_information.set_context_item ('Score', 'autoBeaming = ##f')
2780 def print_ly_preamble (printer, filename):
2781 printer.dump_version ()
2782 printer.print_verbatim ('%% automatically converted by musicxml2ly from %s\n' % filename)
2784 def print_ly_additional_definitions (printer, filename):
2785 if needed_additional_definitions:
2787 printer.print_verbatim ('%% additional definitions required by the score:')
2789 for a in set(needed_additional_definitions):
2790 printer.print_verbatim (additional_definitions.get (a, ''))
2794 # Read in the tree from the given I/O object (either file or string) and
2795 # demarshall it using the classes from the musicxml.py file
2796 def read_xml (io_object, use_lxml):
2799 tree = lxml.etree.parse (io_object)
2800 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
2803 from xml.dom import minidom, Node
2804 doc = minidom.parse(io_object)
2805 node = doc.documentElement
2806 return musicxml.minidom_demarshal_node (node)
2810 def read_musicxml (filename, compressed, use_lxml):
2814 ly.progress (_ ("Input is compressed, extracting raw MusicXML data from stdin"), True)
2815 # unfortunately, zipfile.ZipFile can't read directly from
2816 # stdin, so copy everything from stdin to a temp file and read
2817 # that. TemporaryFile() will remove the file when it is closed.
2818 tmp = tempfile.TemporaryFile()
2819 sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0) # Make sys.stdin binary
2820 bytes_read = sys.stdin.read (8192)
2822 for b in bytes_read:
2824 bytes_read = sys.stdin.read (8192)
2825 z = zipfile.ZipFile (tmp, "r")
2827 ly.progress (_ ("Input file %s is compressed, extracting raw MusicXML data") % filename, True)
2828 z = zipfile.ZipFile (filename, "r")
2829 container_xml = z.read ("META-INF/container.xml")
2830 if not container_xml:
2832 container = read_xml (StringIO.StringIO (container_xml), use_lxml)
2835 rootfiles = container.get_maybe_exist_named_child ('rootfiles')
2838 rootfile_list = rootfiles.get_named_children ('rootfile')
2840 if len (rootfile_list) > 0:
2841 mxml_file = getattr (rootfile_list[0], 'full-path', None)
2843 raw_string = z.read (mxml_file)
2846 io_object = StringIO.StringIO (raw_string)
2847 elif filename == "-":
2848 io_object = sys.stdin
2850 io_object = filename
2852 return read_xml (io_object, use_lxml)
2855 def convert (filename, options):
2857 ly.progress (_ ("Reading MusicXML from Standard input ..."), True)
2859 ly.progress (_ ("Reading MusicXML from %s ...") % filename, True)
2861 tree = read_musicxml (filename, options.compressed, options.use_lxml)
2862 score_information = extract_score_information (tree)
2863 paper_information = extract_paper_information (tree)
2865 parts = tree.get_typed_children (musicxml.Part)
2866 (voices, staff_info) = get_all_voices (parts)
2869 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
2871 score = extract_score_structure (mxl_pl, staff_info)
2872 part_list = mxl_pl.get_named_children ("score-part")
2874 # score information is contained in the <work>, <identification> or <movement-title> tags
2875 update_score_setup (score, part_list, voices)
2876 # After the conversion, update the list of settings for the \layout block
2877 update_layout_information ()
2879 if not options.output_name:
2880 options.output_name = os.path.basename (filename)
2881 options.output_name = os.path.splitext (options.output_name)[0]
2882 elif re.match (".*\.ly", options.output_name):
2883 options.output_name = os.path.splitext (options.output_name)[0]
2886 #defs_ly_name = options.output_name + '-defs.ly'
2887 if (options.output_name == "-"):
2888 output_ly_name = 'Standard output'
2890 output_ly_name = options.output_name + '.ly'
2892 ly.progress (_ ("Output to `%s'") % output_ly_name, True)
2893 printer = musicexp.Output_printer()
2894 #ly.progress (_ ("Output to `%s'") % defs_ly_name, True)
2895 if (options.output_name == "-"):
2896 printer.set_file (codecs.getwriter ("utf-8")(sys.stdout))
2898 printer.set_file (codecs.open (output_ly_name, 'wb', encoding='utf-8'))
2899 print_ly_preamble (printer, filename)
2900 print_ly_additional_definitions (printer, filename)
2901 if score_information:
2902 score_information.print_ly (printer)
2903 if paper_information and conversion_settings.convert_page_layout:
2904 paper_information.print_ly (printer)
2905 if layout_information:
2906 layout_information.print_ly (printer)
2907 print_voice_definitions (printer, part_list, voices)
2910 printer.dump ("% The score definition")
2912 score.print_ly (printer)
2917 def get_existing_filename_with_extension (filename, ext):
2918 if os.path.exists (filename):
2920 newfilename = filename + "." + ext
2921 if os.path.exists (newfilename):
2923 newfilename = filename + ext
2924 if os.path.exists (newfilename):
2929 opt_parser = option_parser()
2932 (options, args) = opt_parser.parse_args ()
2934 opt_parser.print_usage()
2938 musicexp.set_create_midi (options.midi)
2940 if options.language:
2941 musicexp.set_pitch_language (options.language)
2942 needed_additional_definitions.append (options.language)
2943 additional_definitions[options.language] = "\\language \"%s\"\n" % options.language
2944 conversion_settings.ignore_beaming = not options.convert_beaming
2945 conversion_settings.convert_page_layout = options.convert_page_layout
2947 # Allow the user to leave out the .xml or xml on the filename
2948 basefilename = args[0].decode('utf-8')
2949 if basefilename == "-": # Read from stdin
2952 filename = get_existing_filename_with_extension (basefilename, "xml")
2954 filename = get_existing_filename_with_extension (basefilename, "mxl")
2955 options.compressed = True
2956 if filename and filename.endswith ("mxl"):
2957 options.compressed = True
2959 if filename and (filename == "-" or os.path.exists (filename)):
2960 voices = convert (filename, options)
2962 ly.error (_ ("Unable to find input file %s") % basefilename)
2964 if __name__ == '__main__':