2 # -*- coding: utf-8 -*-
23 from rational import Rational
25 # Store command-line options in a global variable, so we can access them everywhere
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)
478 structure.append_staff (i)
482 def musicxml_duration_to_lily (mxl_note):
483 # if the note has no Type child, then that method returns None. In that case,
484 # use the <duration> tag instead. If that doesn't exist, either -> Error
485 dur = mxl_note.get_duration_info ()
487 d = musicexp.Duration ()
488 d.duration_log = dur[0]
490 # Grace notes by specification have duration 0, so no time modification
491 # factor is possible. It even messes up the output with *0/1
492 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
493 d.factor = mxl_note._duration / d.get_length ()
497 if mxl_note._duration > 0:
498 return rational_to_lily_duration (mxl_note._duration)
500 mxl_note.message (_ ("Encountered note at %s without type and duration (=%s)") % (mxl_note.start, mxl_note._duration) )
504 def rational_to_lily_duration (rational_len):
505 d = musicexp.Duration ()
507 rational_len.normalize_self ()
508 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)
510 # Duration of the form 1/2^n or 3/2^n can be converted to a simple lilypond duration
511 dots = {1: 0, 3: 1, 7: 2, 15: 3, 31: 4, 63: 5, 127: 6}.get (rational_len.numerator(), -1)
512 if ( d_log >= dots >= 0 ):
513 # account for the dots!
514 d.duration_log = d_log - dots
517 d.duration_log = d_log
518 d.factor = Rational (rational_len.numerator ())
520 ly.warning (_ ("Encountered rational duration with denominator %s, "
521 "unable to convert to lilypond duration") %
522 rational_len.denominator ())
523 # TODO: Test the above error message
528 def musicxml_partial_to_lily (partial_len):
530 p = musicexp.Partial ()
531 p.partial = rational_to_lily_duration (partial_len)
536 # Detect repeats and alternative endings in the chord event list (music_list)
537 # and convert them to the corresponding musicexp objects, containing nested
539 def group_repeats (music_list):
540 repeat_replaced = True
543 # Walk through the list of expressions, looking for repeat structure
544 # (repeat start/end, corresponding endings). If we find one, try to find the
545 # last event of the repeat, replace the whole structure and start over again.
546 # For nested repeats, as soon as we encounter another starting repeat bar,
547 # treat that one first, and start over for the outer repeat.
548 while repeat_replaced and i < 100:
550 repeat_start = -1 # position of repeat start / end
551 repeat_end = -1 # position of repeat start / end
553 ending_start = -1 # position of current ending start
554 endings = [] # list of already finished endings
556 last = len (music_list) - 1
557 repeat_replaced = False
559 while pos < len (music_list) and not repeat_replaced:
561 repeat_finished = False
562 if isinstance (e, RepeatMarker):
563 if not repeat_times and e.times:
564 repeat_times = e.times
565 if e.direction == -1:
567 repeat_finished = True
573 elif e.direction == 1:
579 elif isinstance (e, EndingMarker):
580 if e.direction == -1:
586 elif e.direction == 1:
589 endings.append ([ending_start, pos])
592 elif not isinstance (e, musicexp.BarLine):
593 # As soon as we encounter an element when repeat start and end
594 # is set and we are not inside an alternative ending,
595 # this whole repeat structure is finished => replace it
596 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
597 repeat_finished = True
599 # Finish off all repeats without explicit ending bar (e.g. when
600 # we convert only one page of a multi-page score with repeats)
601 if pos == last and repeat_start >= 0:
602 repeat_finished = True
606 if ending_start >= 0:
607 endings.append ([ending_start, pos])
611 # We found the whole structure replace it!
612 r = musicexp.RepeatedMusic ()
613 if repeat_times <= 0:
615 r.repeat_count = repeat_times
616 # don't erase the first element for "implicit" repeats (i.e. no
617 # starting repeat bars at the very beginning)
618 start = repeat_start + 1
619 if repeat_start == music_start:
621 r.set_music (music_list[start:repeat_end])
622 for (start, end) in endings:
623 s = musicexp.SequentialMusic ()
624 s.elements = music_list[start + 1:end]
626 del music_list[repeat_start:final_marker + 1]
627 music_list.insert (repeat_start, r)
628 repeat_replaced = True
630 # TODO: Implement repeats until the end without explicit ending bar
634 # Extract the settings for tuplets from the <notations><tuplet> and the
635 # <time-modification> elements of the note:
636 def musicxml_tuplet_to_lily (tuplet_elt, time_modification):
637 tsm = musicexp.TimeScaledMusic ()
639 if time_modification:
640 fraction = time_modification.get_fraction ()
641 tsm.numerator = fraction[0]
642 tsm.denominator = fraction[1]
645 normal_type = tuplet_elt.get_normal_type ()
646 if not normal_type and time_modification:
647 normal_type = time_modification.get_normal_type ()
648 if not normal_type and time_modification:
649 note = time_modification.get_parent ()
651 normal_type = note.get_duration_info ()
653 normal_note = musicexp.Duration ()
654 (normal_note.duration_log, normal_note.dots) = normal_type
655 tsm.normal_type = normal_note
657 actual_type = tuplet_elt.get_actual_type ()
659 actual_note = musicexp.Duration ()
660 (actual_note.duration_log, actual_note.dots) = actual_type
661 tsm.actual_type = actual_note
663 # Obtain non-default nrs of notes from the tuplet object!
664 tsm.display_numerator = tuplet_elt.get_normal_nr ()
665 tsm.display_denominator = tuplet_elt.get_actual_nr ()
668 if hasattr (tuplet_elt, 'bracket') and tuplet_elt.bracket == "no":
669 tsm.display_bracket = None
670 elif hasattr (tuplet_elt, 'line-shape') and getattr (tuplet_elt, 'line-shape') == "curved":
671 tsm.display_bracket = "curved"
673 tsm.display_bracket = "bracket"
675 display_values = {"none": None, "actual": "actual", "both": "both"}
676 if hasattr (tuplet_elt, "show-number"):
677 tsm.display_number = display_values.get (getattr (tuplet_elt, "show-number"), "actual")
679 if hasattr (tuplet_elt, "show-type"):
680 tsm.display_type = display_values.get (getattr (tuplet_elt, "show-type"), None)
685 def group_tuplets (music_list, events):
688 """Collect Musics from
689 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
697 for (ev_chord, tuplet_elt, time_modification) in events:
698 while (j < len (music_list)):
699 if music_list[j] == ev_chord:
703 if hasattr (tuplet_elt, 'number'):
704 nr = getattr (tuplet_elt, 'number')
705 if tuplet_elt.type == 'start':
706 tuplet_object = musicxml_tuplet_to_lily (tuplet_elt, time_modification)
707 tuplet_info = [j, None, tuplet_object]
708 indices.append (tuplet_info)
709 brackets[nr] = tuplet_info
710 elif tuplet_elt.type == 'stop':
711 bracket_info = brackets.get (nr, None)
713 bracket_info[1] = j # Set the ending position to j
718 for (i1, i2, tsm) in indices:
722 new_list.extend (music_list[last:i1])
723 seq = musicexp.SequentialMusic ()
725 seq.elements = music_list[i1:last]
729 new_list.append (tsm)
730 #TODO: Handle nested tuplets!!!!
732 new_list.extend (music_list[last:])
736 def musicxml_clef_to_lily (attributes):
737 change = musicexp.ClefChange ()
738 (change.type, change.position, change.octave) = attributes.get_clef_information ()
741 def musicxml_time_to_lily (attributes):
742 sig = attributes.get_time_signature ()
745 change = musicexp.TimeSignatureChange()
746 change.fractions = sig
748 time_elm = attributes.get_maybe_exist_named_child ('time')
749 if time_elm and hasattr (time_elm, 'symbol'):
750 change.style = { 'single-number': "'single-digit",
753 'normal': "'()"}.get (time_elm.symbol, "'()")
757 # TODO: Handle senza-misura measures
758 # TODO: Handle hidden time signatures (print-object="no")
759 # TODO: What shall we do if the symbol clashes with the sig? e.g. "cut"
760 # with 3/8 or "single-number" with (2+3)/8 or 3/8+2/4?
764 def musicxml_key_to_lily (attributes):
765 key_sig = attributes.get_key_signature ()
766 if not key_sig or not (isinstance (key_sig, list) or isinstance (key_sig, tuple)):
767 ly.warning (_ ("Unable to extract key signature!"))
770 change = musicexp.KeySignatureChange()
772 if len (key_sig) == 2 and not isinstance (key_sig[0], list):
773 # standard key signature, (fifths, mode)
774 (fifths, mode) = key_sig
777 start_pitch = musicexp.Pitch ()
778 start_pitch.octave = 0
787 'mixolydian': (4, 0),
792 start_pitch.alteration = a
794 ly.warning (_ ("unknown mode %s, expecting 'major' or 'minor' "
795 "or a church mode!") % mode)
797 fifth = musicexp.Pitch()
803 for x in range (fifths):
804 start_pitch = start_pitch.transposed (fifth)
805 change.tonic = start_pitch
808 # Non-standard key signature of the form [[step,alter<,octave>],...]
809 # MusicXML contains C,D,E,F,G,A,B as steps, lily uses 0-7, so convert
812 k[0] = musicxml_step_to_lily (k[0])
813 alterations.append (k)
814 change.non_standard_alterations = alterations
817 def musicxml_transpose_to_lily (attributes):
818 transpose = attributes.get_transposition ()
822 shift = musicexp.Pitch ()
823 octave_change = transpose.get_maybe_exist_named_child ('octave-change')
825 shift.octave = string.atoi (octave_change.get_text ())
826 chromatic_shift = string.atoi (transpose.get_named_child ('chromatic').get_text ())
827 chromatic_shift_normalized = chromatic_shift % 12;
828 (shift.step, shift.alteration) = [
829 (0, 0), (0, 1), (1, 0), (2, -1), (2, 0),
830 (3, 0), (3, 1), (4, 0), (5, -1), (5, 0),
831 (6, -1), (6, 0)][chromatic_shift_normalized];
833 shift.octave += (chromatic_shift - chromatic_shift_normalized) / 12
835 diatonic = transpose.get_maybe_exist_named_child ('diatonic')
837 diatonic_step = string.atoi (diatonic.get_text ()) % 7
838 if diatonic_step != shift.step:
839 # We got the alter incorrect!
840 old_semitones = shift.semitones ()
841 shift.step = diatonic_step
842 new_semitones = shift.semitones ()
843 shift.alteration += old_semitones - new_semitones
845 transposition = musicexp.Transposition ()
846 transposition.pitch = musicexp.Pitch ().transposed (shift)
849 def musicxml_staff_details_to_lily (attributes):
850 details = attributes.get_maybe_exist_named_child ('staff-details')
854 ## TODO: Handle staff-type, staff-lines, staff-tuning, capo, staff-size
857 stafflines = details.get_maybe_exist_named_child ('staff-lines')
859 lines = string.atoi (stafflines.get_text ());
860 lines_event = musicexp.StaffLinesEvent (lines);
861 ret.append (lines_event);
866 def musicxml_attributes_to_lily (attrs):
869 'clef': musicxml_clef_to_lily,
870 'time': musicxml_time_to_lily,
871 'key': musicxml_key_to_lily,
872 'transpose': musicxml_transpose_to_lily,
873 'staff-details': musicxml_staff_details_to_lily,
875 for (k, func) in attr_dispatch.items ():
876 children = attrs.get_named_children (k)
879 if isinstance (ev, list):
887 def extract_display_text (el):
888 child = el.get_maybe_exist_named_child ("display-text")
890 return child.get_text ()
895 def musicxml_print_to_lily (el):
896 # TODO: Implement other print attributes
897 # <!ELEMENT print (page-layout?, system-layout?, staff-layout*,
898 # measure-layout?, measure-numbering?, part-name-display?,
899 # part-abbreviation-display?)>
901 # staff-spacing %tenths; #IMPLIED
902 # new-system %yes-no; #IMPLIED
903 # new-page %yes-no-number; #IMPLIED
904 # blank-page NMTOKEN #IMPLIED
905 # page-number CDATA #IMPLIED
908 if (hasattr (el, "new-system") and conversion_settings.convert_page_layout):
909 val = getattr (el, "new-system")
911 elts.append (musicexp.Break ("break"))
912 if (hasattr (el, "new-page") and conversion_settings.convert_page_layout):
913 val = getattr (el, "new-page")
915 elts.append (musicexp.Break ("pageBreak"))
916 child = el.get_maybe_exist_named_child ("part-name-display")
918 elts.append (musicexp.SetEvent ("Staff.instrumentName",
919 "\"%s\"" % extract_display_text (child)))
920 child = el.get_maybe_exist_named_child ("part-abbreviation-display")
922 elts.append (musicexp.SetEvent ("Staff.shortInstrumentName",
923 "\"%s\"" % extract_display_text (child)))
927 class Marker (musicexp.Music):
931 def print_ly (self, printer):
932 ly.warning (_ ("Encountered unprocessed marker %s\n") % self)
934 def ly_expression (self):
936 class RepeatMarker (Marker):
938 Marker.__init__ (self)
940 class EndingMarker (Marker):
943 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
944 # and to RepeatMarker and EndingMarker objects for repeat and
945 # alternatives start/stops
946 def musicxml_barline_to_lily (barline):
947 # retval contains all possible markers in the order:
948 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
950 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
951 repeat_element = barline.get_maybe_exist_named_child ("repeat")
952 ending_element = barline.get_maybe_exist_named_child ("ending")
956 bartype = bartype_element.get_text ()
958 if repeat_element and hasattr (repeat_element, 'direction'):
959 repeat = RepeatMarker ()
960 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
962 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
963 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
965 if hasattr (repeat_element, 'times'):
967 repeat.times = int (repeat_element.times)
970 repeat.event = barline
971 if repeat.direction == -1:
976 if ending_element and hasattr (ending_element, 'type'):
977 ending = EndingMarker ()
978 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
979 ending.event = barline
980 if ending.direction == -1:
986 b = musicexp.BarLine ()
990 return retval.values ()
992 spanner_event_dict = {
993 'beam' : musicexp.BeamEvent,
994 'dashes' : musicexp.TextSpannerEvent,
995 'bracket' : musicexp.BracketSpannerEvent,
996 'glissando' : musicexp.GlissandoEvent,
997 'octave-shift' : musicexp.OctaveShiftEvent,
998 'pedal' : musicexp.PedalEvent,
999 'slide' : musicexp.GlissandoEvent,
1000 'slur' : musicexp.SlurEvent,
1001 'wavy-line' : musicexp.TrillSpanEvent,
1002 'wedge' : musicexp.HairpinEvent
1004 spanner_type_dict = {
1018 def musicxml_spanner_to_lily_event (mxl_event):
1021 name = mxl_event.get_name()
1022 func = spanner_event_dict.get (name)
1026 ly.warning (_ ('unknown span event %s') % mxl_event)
1029 type = mxl_event.get_type ()
1030 span_direction = spanner_type_dict.get (type)
1031 # really check for None, because some types will be translated to 0, which
1032 # would otherwise also lead to the unknown span warning
1033 if span_direction != None:
1034 ev.span_direction = span_direction
1036 ly.warning (_ ('unknown span type %s for %s') % (type, name))
1038 ev.set_span_type (type)
1039 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
1041 # assign the size, which is used for octave-shift, etc.
1042 ev.size = mxl_event.get_size ()
1046 def musicxml_direction_to_indicator (direction):
1047 return { "above": 1, "upright": 1, "up": 1, "below": -1, "downright": -1, "down": -1, "inverted": -1 }.get (direction, 0)
1049 def musicxml_fermata_to_lily_event (mxl_event):
1050 ev = musicexp.ArticulationEvent ()
1051 txt = mxl_event.get_text ()
1052 # The contents of the element defined the shape, possible are normal, angled and square
1053 ev.type = { "angled": "shortfermata", "square": "longfermata" }.get (txt, "fermata")
1054 if hasattr (mxl_event, 'type'):
1055 dir = musicxml_direction_to_indicator (mxl_event.type)
1056 if dir and options.convert_directions:
1057 ev.force_direction = dir
1060 def musicxml_arpeggiate_to_lily_event (mxl_event):
1061 ev = musicexp.ArpeggioEvent ()
1062 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1065 def musicxml_nonarpeggiate_to_lily_event (mxl_event):
1066 ev = musicexp.ArpeggioEvent ()
1067 ev.non_arpeggiate = True
1068 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1071 def musicxml_tremolo_to_lily_event (mxl_event):
1072 ev = musicexp.TremoloEvent ()
1073 txt = mxl_event.get_text ()
1080 def musicxml_falloff_to_lily_event (mxl_event):
1081 ev = musicexp.BendEvent ()
1085 def musicxml_doit_to_lily_event (mxl_event):
1086 ev = musicexp.BendEvent ()
1090 def musicxml_bend_to_lily_event (mxl_event):
1091 ev = musicexp.BendEvent ()
1092 ev.alter = mxl_event.bend_alter ()
1095 def musicxml_caesura_to_lily_event (mxl_event):
1096 ev = musicexp.MarkupEvent ()
1097 # FIXME: default to straight or curved caesura?
1098 ev.contents = "\\musicglyph #\"scripts.caesura.straight\""
1099 ev.force_direction = 1
1102 def musicxml_fingering_event (mxl_event):
1103 ev = musicexp.ShortArticulationEvent ()
1104 ev.type = mxl_event.get_text ()
1107 def musicxml_string_event (mxl_event):
1108 ev = musicexp.NoDirectionArticulationEvent ()
1109 ev.type = mxl_event.get_text ()
1112 def musicxml_accidental_mark (mxl_event):
1113 ev = musicexp.MarkupEvent ()
1114 contents = { "sharp": "\\sharp",
1115 "natural": "\\natural",
1117 "double-sharp": "\\doublesharp",
1118 "sharp-sharp": "\\sharp\\sharp",
1119 "flat-flat": "\\flat\\flat",
1120 "flat-flat": "\\doubleflat",
1121 "natural-sharp": "\\natural\\sharp",
1122 "natural-flat": "\\natural\\flat",
1123 "quarter-flat": "\\semiflat",
1124 "quarter-sharp": "\\semisharp",
1125 "three-quarters-flat": "\\sesquiflat",
1126 "three-quarters-sharp": "\\sesquisharp",
1127 }.get (mxl_event.get_text ())
1129 ev.contents = contents
1134 # translate articulations, ornaments and other notations into ArticulationEvents
1136 # -) string (ArticulationEvent with that name)
1137 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
1138 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
1139 # TODO: Some translations are missing!
1140 articulations_dict = {
1141 "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
1142 "accidental-mark": musicxml_accidental_mark,
1143 "bend": musicxml_bend_to_lily_event,
1144 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
1145 "caesura": musicxml_caesura_to_lily_event,
1146 #"delayed-turn": "?",
1147 "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
1148 "doit": musicxml_doit_to_lily_event,
1149 #"double-tongue": "?",
1150 "down-bow": "downbow",
1151 "falloff": musicxml_falloff_to_lily_event,
1152 "fingering": musicxml_fingering_event,
1153 #"fingernails": "?",
1156 "harmonic": "flageolet",
1158 "inverted-mordent": "prall",
1159 "inverted-turn": "reverseturn",
1160 "mordent": "mordent",
1161 "open-string": "open",
1168 "snap-pizzicato": "snappizzicato",
1170 "staccatissimo": (musicexp.ShortArticulationEvent, "!"), # or "staccatissimo"
1171 "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
1172 "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
1174 "string": musicxml_string_event,
1175 "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
1177 "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
1178 "thumb-position": "thumb",
1181 "tremolo": musicxml_tremolo_to_lily_event,
1182 "trill-mark": "trill",
1183 #"triple-tongue": "?",
1188 articulation_spanners = [ "wavy-line" ]
1190 def musicxml_articulation_to_lily_event (mxl_event):
1191 # wavy-line elements are treated as trill spanners, not as articulation ornaments
1192 if mxl_event.get_name () in articulation_spanners:
1193 return musicxml_spanner_to_lily_event (mxl_event)
1195 tmp_tp = articulations_dict.get (mxl_event.get_name ())
1199 if isinstance (tmp_tp, str):
1200 ev = musicexp.ArticulationEvent ()
1202 elif isinstance (tmp_tp, tuple):
1206 ev = tmp_tp (mxl_event)
1208 # Some articulations use the type attribute, other the placement...
1210 if hasattr (mxl_event, 'type') and options.convert_directions:
1211 dir = musicxml_direction_to_indicator (mxl_event.type)
1212 if hasattr (mxl_event, 'placement') and options.convert_directions:
1213 dir = musicxml_direction_to_indicator (mxl_event.placement)
1215 ev.force_direction = dir
1220 def musicxml_dynamics_to_lily_event (dynentry):
1221 dynamics_available = (
1222 "ppppp", "pppp", "ppp", "pp", "p", "mp", "mf",
1223 "f", "ff", "fff", "ffff", "fp", "sf", "sff", "sp", "spp", "sfz", "rfz" )
1224 dynamicsname = dynentry.get_name ()
1225 if dynamicsname == "other-dynamics":
1226 dynamicsname = dynentry.get_text ()
1227 if not dynamicsname or dynamicsname == "#text":
1230 if not dynamicsname in dynamics_available:
1231 # Get rid of - in tag names (illegal in ly tags!)
1232 dynamicstext = dynamicsname
1233 dynamicsname = string.replace (dynamicsname, "-", "")
1234 additional_definitions[dynamicsname] = dynamicsname + \
1235 " = #(make-dynamic-script \"" + dynamicstext + "\")"
1236 needed_additional_definitions.append (dynamicsname)
1237 event = musicexp.DynamicsEvent ()
1238 event.type = dynamicsname
1241 # Convert single-color two-byte strings to numbers 0.0 - 1.0
1242 def hexcolorval_to_nr (hex_val):
1244 v = int (hex_val, 16)
1251 def hex_to_color (hex_val):
1252 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)
1254 return map (lambda x: hexcolorval_to_nr (x), res.group (2, 3, 4))
1258 def musicxml_words_to_lily_event (words):
1259 event = musicexp.TextEvent ()
1260 text = words.get_text ()
1261 text = re.sub ('^ *\n? *', '', text)
1262 text = re.sub (' *\n? *$', '', text)
1265 if hasattr (words, 'default-y') and options.convert_directions:
1266 offset = getattr (words, 'default-y')
1268 off = string.atoi (offset)
1270 event.force_direction = 1
1272 event.force_direction = -1
1274 event.force_direction = 0
1276 if hasattr (words, 'font-weight'):
1277 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
1279 event.markup += font_weight
1281 if hasattr (words, 'font-size'):
1282 size = getattr (words, 'font-size')
1284 "xx-small": '\\teeny',
1285 "x-small": '\\tiny',
1289 "x-large": '\\huge',
1290 "xx-large": '\\larger\\huge'
1293 event.markup += font_size
1295 if hasattr (words, 'color'):
1296 color = getattr (words, 'color')
1297 rgb = hex_to_color (color)
1299 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
1301 if hasattr (words, 'font-style'):
1302 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
1304 event.markup += font_style
1306 # TODO: How should I best convert the font-family attribute?
1308 # TODO: How can I represent the underline, overline and line-through
1309 # attributes in LilyPond? Values of these attributes indicate
1310 # the number of lines
1315 # convert accordion-registration to lilypond.
1316 # Since lilypond does not have any built-in commands, we need to create
1317 # the markup commands manually and define our own variables.
1318 # Idea was taken from: http://lsr.dsi.unimi.it/LSR/Item?id=194
1319 def musicxml_accordion_to_markup (mxl_event):
1320 commandname = "accReg"
1323 high = mxl_event.get_maybe_exist_named_child ('accordion-high')
1326 command += """\\combine
1327 \\raise #2.5 \\musicglyph #\"accordion.dot\"
1329 middle = mxl_event.get_maybe_exist_named_child ('accordion-middle')
1331 # By default, use one dot (when no or invalid content is given). The
1332 # MusicXML spec is quiet about this case...
1335 txt = string.atoi (middle.get_text ())
1339 commandname += "MMM"
1340 command += """\\combine
1341 \\raise #1.5 \\musicglyph #\"accordion.dot\"
1343 \\raise #1.5 \\translate #(cons 1 0) \\musicglyph #\"accordion.dot\"
1345 \\raise #1.5 \\translate #(cons -1 0) \\musicglyph #\"accordion.dot\"
1349 command += """\\combine
1350 \\raise #1.5 \\translate #(cons 0.5 0) \\musicglyph #\"accordion.dot\"
1352 \\raise #1.5 \\translate #(cons -0.5 0) \\musicglyph #\"accordion.dot\"
1356 command += """\\combine
1357 \\raise #1.5 \\musicglyph #\"accordion.dot\"
1359 low = mxl_event.get_maybe_exist_named_child ('accordion-low')
1362 command += """\\combine
1363 \\raise #0.5 \musicglyph #\"accordion.dot\"
1366 command += "\musicglyph #\"accordion.discant\""
1367 command = "\\markup { \\normalsize %s }" % command
1368 # Define the newly built command \accReg[H][MMM][L]
1369 additional_definitions[commandname] = "%s = %s" % (commandname, command)
1370 needed_additional_definitions.append (commandname)
1371 return "\\%s" % commandname
1373 def musicxml_accordion_to_ly (mxl_event):
1374 txt = musicxml_accordion_to_markup (mxl_event)
1376 ev = musicexp.MarkEvent (txt)
1381 def musicxml_rehearsal_to_ly_mark (mxl_event):
1382 text = mxl_event.get_text ()
1385 # default is boxed rehearsal marks!
1387 if hasattr (mxl_event, 'enclosure'):
1388 encl = {"none": None, "square": "box", "circle": "circle" }.get (mxl_event.enclosure, None)
1390 text = "\\%s { %s }" % (encl, text)
1391 ev = musicexp.MarkEvent ("\\markup { %s }" % text)
1394 def musicxml_harp_pedals_to_ly (mxl_event):
1396 result = "\\harp-pedal #\""
1397 for t in mxl_event.get_named_children ('pedal-tuning'):
1398 alter = t.get_named_child ('pedal-alter')
1400 val = int (alter.get_text ().strip ())
1401 result += {1: "v", 0: "-", -1: "^"}.get (val, "")
1405 ev = musicexp.MarkupEvent ()
1406 ev.contents = result + "\""
1409 def musicxml_eyeglasses_to_ly (mxl_event):
1410 needed_additional_definitions.append ("eyeglasses")
1411 return musicexp.MarkEvent ("\\markup { \\eyeglasses }")
1413 def next_non_hash_index (lst, pos):
1415 while pos < len (lst) and isinstance (lst[pos], musicxml.Hash_text):
1419 def musicxml_metronome_to_ly (mxl_event):
1420 children = mxl_event.get_all_children ()
1425 index = next_non_hash_index (children, index)
1426 if isinstance (children[index], musicxml.BeatUnit):
1427 # first form of metronome-mark, using unit and beats/min or other unit
1428 ev = musicexp.TempoMark ()
1429 if hasattr (mxl_event, 'parentheses'):
1430 ev.set_parentheses (mxl_event.parentheses == "yes")
1432 d = musicexp.Duration ()
1433 d.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1434 index = next_non_hash_index (children, index)
1435 if isinstance (children[index], musicxml.BeatUnitDot):
1437 index = next_non_hash_index (children, index)
1438 ev.set_base_duration (d)
1439 if isinstance (children[index], musicxml.BeatUnit):
1440 # Form "note = newnote"
1441 newd = musicexp.Duration ()
1442 newd.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1443 index = next_non_hash_index (children, index)
1444 if isinstance (children[index], musicxml.BeatUnitDot):
1446 index = next_non_hash_index (children, index)
1447 ev.set_new_duration (newd)
1448 elif isinstance (children[index], musicxml.PerMinute):
1451 beats = int (children[index].get_text ())
1452 ev.set_beats_per_minute (beats)
1456 ly.warning (_ ("Unknown metronome mark, ignoring"))
1460 #TODO: Implement the other (more complex) way for tempo marks!
1461 ly.warning (_ ("Metronome marks with complex relations (<metronome-note> in MusicXML) are not yet implemented."))
1464 # translate directions into Events, possible values:
1465 # -) string (MarkEvent with that command)
1466 # -) function (function(mxl_event) needs to return a full Event-derived object
1467 # -) (class, name) (like string, only that a different class than MarkEvent is used)
1469 'accordion-registration' : musicxml_accordion_to_ly,
1470 'coda' : (musicexp.MusicGlyphMarkEvent, "coda"),
1473 'eyeglasses': musicxml_eyeglasses_to_ly,
1474 'harp-pedals' : musicxml_harp_pedals_to_ly,
1476 'metronome' : musicxml_metronome_to_ly,
1477 'rehearsal' : musicxml_rehearsal_to_ly_mark,
1478 # 'scordatura' : ???
1479 'segno' : (musicexp.MusicGlyphMarkEvent, "segno"),
1480 'words' : musicxml_words_to_lily_event,
1482 directions_spanners = [ 'octave-shift', 'pedal', 'wedge', 'dashes', 'bracket' ]
1484 def musicxml_direction_to_lily (n):
1485 # TODO: Handle the <staff> element!
1487 # placement applies to all children!
1489 if hasattr (n, 'placement') and options.convert_directions:
1490 dir = musicxml_direction_to_indicator (n.placement)
1491 dirtype_children = []
1492 # TODO: The direction-type is used for grouping (e.g. dynamics with text),
1493 # so we can't simply flatten them out!
1494 for dt in n.get_typed_children (musicxml.DirType):
1495 dirtype_children += dt.get_all_children ()
1497 for entry in dirtype_children:
1498 # backets, dashes, octave shifts. pedal marks, hairpins etc. are spanners:
1499 if entry.get_name() in directions_spanners:
1500 event = musicxml_spanner_to_lily_event (entry)
1505 # now treat all the "simple" ones, that can be translated using the dict
1507 tmp_tp = directions_dict.get (entry.get_name (), None)
1508 if isinstance (tmp_tp, str): # string means MarkEvent
1509 ev = musicexp.MarkEvent (tmp_tp)
1510 elif isinstance (tmp_tp, tuple): # tuple means (EventClass, "text")
1511 ev = tmp_tp[0] (tmp_tp[1])
1515 # TODO: set the correct direction! Unfortunately, \mark in ly does
1516 # not seem to support directions!
1517 ev.force_direction = dir
1521 if entry.get_name () == "dynamics":
1522 for dynentry in entry.get_all_children ():
1523 ev = musicxml_dynamics_to_lily_event (dynentry)
1529 def musicxml_frame_to_lily_event (frame):
1530 ev = musicexp.FretEvent ()
1531 ev.strings = frame.get_strings ()
1532 ev.frets = frame.get_frets ()
1533 #offset = frame.get_first_fret () - 1
1535 for fn in frame.get_named_children ('frame-note'):
1536 fret = fn.get_fret ()
1539 el = [ fn.get_string (), fret ]
1540 fingering = fn.get_fingering ()
1542 el.append (fingering)
1543 ev.elements.append (el)
1546 barre[0] = el[0] # start string
1547 barre[2] = el[1] # fret
1549 barre[1] = el[0] # end string
1554 def musicxml_harmony_to_lily (n):
1556 for f in n.get_named_children ('frame'):
1557 ev = musicxml_frame_to_lily_event (f)
1563 notehead_styles_dict = {
1565 'triangle': '\'triangle',
1566 'diamond': '\'diamond',
1567 'square': '\'la', # TODO: Proper squared note head
1568 'cross': None, # TODO: + shaped note head
1570 'circle-x': '\'xcircle',
1571 'inverted triangle': None, # TODO: Implement
1572 'arrow down': None, # TODO: Implement
1573 'arrow up': None, # TODO: Implement
1574 'slashed': None, # TODO: Implement
1575 'back slashed': None, # TODO: Implement
1577 'cluster': None, # TODO: Implement
1588 def musicxml_notehead_to_lily (nh):
1592 style = notehead_styles_dict.get (nh.get_text ().strip (), None)
1593 style_elm = musicexp.NotestyleEvent ()
1595 style_elm.style = style
1596 if hasattr (nh, 'filled'):
1597 style_elm.filled = (getattr (nh, 'filled') == "yes")
1598 if style_elm.style or (style_elm.filled != None):
1599 styles.append (style_elm)
1602 if hasattr (nh, 'parentheses') and (nh.parentheses == "yes"):
1603 styles.append (musicexp.ParenthesizeEvent ())
1607 def musicxml_chordpitch_to_lily (mxl_cpitch):
1608 r = musicexp.ChordPitch ()
1609 r.alteration = mxl_cpitch.get_alteration ()
1610 r.step = musicxml_step_to_lily (mxl_cpitch.get_step ())
1616 'augmented': 'aug5',
1617 'diminished': 'dim5',
1620 'dominant-seventh': '7',
1621 'major-seventh': 'maj7',
1622 'minor-seventh': 'm7',
1623 'diminished-seventh': 'dim7',
1624 'augmented-seventh': 'aug7',
1625 'half-diminished': 'dim5m7',
1626 'major-minor': 'maj7m5',
1629 'minor-sixth': 'm6',
1631 'dominant-ninth': '9',
1632 'major-ninth': 'maj9',
1633 'minor-ninth': 'm9',
1634 # 11ths (usually as the basis for alteration):
1635 'dominant-11th': '11',
1636 'major-11th': 'maj11',
1637 'minor-11th': 'm11',
1638 # 13ths (usually as the basis for alteration):
1639 'dominant-13th': '13.11',
1640 'major-13th': 'maj13.11',
1641 'minor-13th': 'm13',
1643 'suspended-second': 'sus2',
1644 'suspended-fourth': 'sus4',
1645 # Functional sixths:
1647 #'Neapolitan': '???',
1652 #'pedal': '???',(pedal-point bass)
1659 def musicxml_chordkind_to_lily (kind):
1660 res = chordkind_dict.get (kind, None)
1661 # Check for None, since a major chord is converted to ''
1663 ly.warning (_ ("Unable to convert chord type %s to lilypond.") % kind)
1666 def musicxml_harmony_to_lily_chordname (n):
1668 root = n.get_maybe_exist_named_child ('root')
1670 ev = musicexp.ChordNameEvent ()
1671 ev.root = musicxml_chordpitch_to_lily (root)
1672 kind = n.get_maybe_exist_named_child ('kind')
1674 ev.kind = musicxml_chordkind_to_lily (kind.get_text ())
1677 bass = n.get_maybe_exist_named_child ('bass')
1679 ev.bass = musicxml_chordpitch_to_lily (bass)
1680 inversion = n.get_maybe_exist_named_child ('inversion')
1682 # TODO: LilyPond does not support inversions, does it?
1684 # Mail from Carl Sorensen on lilypond-devel, June 11, 2008:
1685 # 4. LilyPond supports the first inversion in the form of added
1686 # bass notes. So the first inversion of C major would be c:/g.
1687 # To get the second inversion of C major, you would need to do
1688 # e:6-3-^5 or e:m6-^5. However, both of these techniques
1689 # require you to know the chord and calculate either the fifth
1690 # pitch (for the first inversion) or the third pitch (for the
1691 # second inversion) so they may not be helpful for musicxml2ly.
1692 inversion_count = string.atoi (inversion.get_text ())
1693 if inversion_count == 1:
1694 # TODO: Calculate the bass note for the inversion...
1697 for deg in n.get_named_children ('degree'):
1698 d = musicexp.ChordModification ()
1699 d.type = deg.get_type ()
1700 d.step = deg.get_value ()
1701 d.alteration = deg.get_alter ()
1702 ev.add_modification (d)
1703 #TODO: convert the user-symbols attribute:
1704 #major: a triangle, like Unicode 25B3
1705 #minor: -, like Unicode 002D
1706 #augmented: +, like Unicode 002B
1707 #diminished: (degree), like Unicode 00B0
1708 #half-diminished: (o with slash), like Unicode 00F8
1714 def musicxml_figured_bass_note_to_lily (n):
1715 res = musicexp.FiguredBassNote ()
1716 suffix_dict = { 'sharp' : "+",
1719 'double-sharp' : "++",
1721 'sharp-sharp' : "++",
1723 prefix = n.get_maybe_exist_named_child ('prefix')
1725 res.set_prefix (suffix_dict.get (prefix.get_text (), ""))
1726 fnumber = n.get_maybe_exist_named_child ('figure-number')
1728 res.set_number (fnumber.get_text ())
1729 suffix = n.get_maybe_exist_named_child ('suffix')
1731 res.set_suffix (suffix_dict.get (suffix.get_text (), ""))
1732 if n.get_maybe_exist_named_child ('extend'):
1733 # TODO: Implement extender lines (unfortunately, in lilypond you have
1734 # to use \set useBassFigureExtenders = ##t, which turns them on
1735 # globally, while MusicXML has a property for each note...
1736 # I'm not sure there is a proper way to implement this cleanly
1743 def musicxml_figured_bass_to_lily (n):
1744 if not isinstance (n, musicxml.FiguredBass):
1746 res = musicexp.FiguredBassEvent ()
1747 for i in n.get_named_children ('figure'):
1748 note = musicxml_figured_bass_note_to_lily (i)
1751 dur = n.get_maybe_exist_named_child ('duration')
1753 # apply the duration to res
1754 length = Rational(int(dur.get_text()), n._divisions) * Rational(1, 4)
1755 res.set_real_duration (length)
1756 duration = rational_to_lily_duration (length)
1758 res.set_duration (duration)
1759 if hasattr (n, 'parentheses') and n.parentheses == "yes":
1760 res.set_parentheses (True)
1763 instrument_drumtype_dict = {
1764 'Acoustic Snare Drum': 'acousticsnare',
1765 'Side Stick': 'sidestick',
1766 'Open Triangle': 'opentriangle',
1767 'Mute Triangle': 'mutetriangle',
1768 'Tambourine': 'tambourine',
1769 'Bass Drum': 'bassdrum',
1772 def musicxml_note_to_lily_main_event (n):
1777 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1779 pitch = musicxml_pitch_to_lily (mxl_pitch)
1780 event = musicexp.NoteEvent ()
1783 acc = n.get_maybe_exist_named_child ('accidental')
1785 # AccidentalCautionary in lily has parentheses
1786 # so treat accidental explicitly in parentheses as cautionary
1787 if hasattr(acc, 'parentheses') and acc.parentheses == "yes":
1788 event.cautionary = True
1790 event.cautionary = acc.cautionary
1791 # TODO: Handle editorial accidentals
1792 # TODO: Handle the level-display setting for displaying brackets/parentheses
1794 elif n.get_maybe_exist_typed_child (musicxml.Unpitched):
1795 # Unpitched elements have display-step and can also have
1797 unpitched = n.get_maybe_exist_typed_child (musicxml.Unpitched)
1798 event = musicexp.NoteEvent ()
1799 event.pitch = musicxml_unpitched_to_lily (unpitched)
1801 elif n.get_maybe_exist_typed_child (musicxml.Rest):
1802 # rests can have display-octave and display-step, which are
1803 # treated like an ordinary note pitch
1804 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1805 event = musicexp.RestEvent ()
1806 if options.convert_rest_positions:
1807 pitch = musicxml_restdisplay_to_lily (rest)
1810 elif n.instrument_name:
1811 event = musicexp.NoteEvent ()
1812 drum_type = instrument_drumtype_dict.get (n.instrument_name)
1814 event.drum_type = drum_type
1816 n.message (_ ("drum %s type unknown, please add to instrument_drumtype_dict") % n.instrument_name)
1817 event.drum_type = 'acousticsnare'
1820 n.message (_ ("cannot find suitable event"))
1823 event.duration = musicxml_duration_to_lily (n)
1825 noteheads = n.get_named_children ('notehead')
1826 for nh in noteheads:
1827 styles = musicxml_notehead_to_lily (nh)
1829 event.add_associated_event (s)
1833 def musicxml_lyrics_to_text (lyrics):
1834 # TODO: Implement text styles for lyrics syllables
1838 for e in lyrics.get_all_children ():
1839 if isinstance (e, musicxml.Syllabic):
1840 continued = e.continued ()
1841 elif isinstance (e, musicxml.Text):
1842 # We need to convert soft hyphens to -, otherwise the ascii codec as well
1843 # as lilypond will barf on that character
1844 text += string.replace( e.get_text(), u'\xad', '-' )
1845 elif isinstance (e, musicxml.Elision):
1850 elif isinstance (e, musicxml.Extend):
1855 if text == "-" and continued:
1857 elif text == "_" and extended:
1859 elif continued and text:
1860 return musicxml.escape_ly_output_string (text) + " --"
1863 elif extended and text:
1864 return musicxml.escape_ly_output_string (text) + " __"
1868 return musicxml.escape_ly_output_string (text)
1874 def __init__ (self, here, dest):
1878 class LilyPondVoiceBuilder:
1879 def __init__ (self):
1881 self.pending_dynamics = []
1882 self.end_moment = Rational (0)
1883 self.begin_moment = Rational (0)
1884 self.pending_multibar = Rational (0)
1885 self.ignore_skips = False
1886 self.has_relevant_elements = False
1887 self.measure_length = Rational (4, 4)
1889 def _insert_multibar (self):
1890 layout_information.set_context_item ('Score', 'skipBars = ##t')
1891 r = musicexp.MultiMeasureRest ()
1892 lenfrac = self.measure_length
1893 r.duration = rational_to_lily_duration (lenfrac)
1894 r.duration.factor *= self.pending_multibar / lenfrac
1895 self.elements.append (r)
1896 self.begin_moment = self.end_moment
1897 self.end_moment = self.begin_moment + self.pending_multibar
1898 self.pending_multibar = Rational (0)
1900 def set_measure_length (self, mlen):
1901 if (mlen != self.measure_length) and self.pending_multibar:
1902 self._insert_multibar ()
1903 self.measure_length = mlen
1905 def add_multibar_rest (self, duration):
1906 self.pending_multibar += duration
1908 def set_duration (self, duration):
1909 self.end_moment = self.begin_moment + duration
1910 def current_duration (self):
1911 return self.end_moment - self.begin_moment
1913 def add_music (self, music, duration, relevant=True):
1914 assert isinstance (music, musicexp.Music)
1915 if self.pending_multibar > Rational (0):
1916 self._insert_multibar ()
1918 self.has_relevant_elements = self.has_relevant_elements or relevant
1919 self.elements.append (music)
1920 self.begin_moment = self.end_moment
1921 self.set_duration (duration)
1923 # Insert all pending dynamics right after the note/rest:
1924 if isinstance (music, musicexp.ChordEvent) and self.pending_dynamics:
1925 for d in self.pending_dynamics:
1927 self.pending_dynamics = []
1929 # Insert some music command that does not affect the position in the measure
1930 def add_command (self, command, relevant=True):
1931 assert isinstance (command, musicexp.Music)
1932 if self.pending_multibar > Rational (0):
1933 self._insert_multibar ()
1934 self.has_relevant_elements = self.has_relevant_elements or relevant
1935 self.elements.append (command)
1936 def add_barline (self, barline, relevant=False):
1937 # Insert only if we don't have a barline already
1938 # TODO: Implement proper merging of default barline and custom bar line
1939 has_relevant = self.has_relevant_elements
1940 if (not (self.elements) or
1941 not (isinstance (self.elements[-1], musicexp.BarLine)) or
1942 (self.pending_multibar > Rational (0))):
1943 self.add_music (barline, Rational (0))
1944 self.has_relevant_elements = has_relevant or relevant
1945 def add_partial (self, command):
1946 self.ignore_skips = True
1947 # insert the partial, but restore relevant_elements (partial is not relevant)
1948 relevant = self.has_relevant_elements
1949 self.add_command (command)
1950 self.has_relevant_elements = relevant
1952 def add_dynamics (self, dynamic):
1953 # store the dynamic item(s) until we encounter the next note/rest:
1954 self.pending_dynamics.append (dynamic)
1956 def add_bar_check (self, number):
1957 # re/store has_relevant_elements, so that a barline alone does not
1958 # trigger output for figured bass, chord names
1959 b = musicexp.BarLine ()
1960 b.bar_number = number
1961 self.add_barline (b)
1963 def jumpto (self, moment):
1964 current_end = self.end_moment + self.pending_multibar
1965 diff = moment - current_end
1967 if diff < Rational (0):
1968 ly.warning (_ ('Negative skip %s (from position %s to %s)')
1969 % (diff, current_end, moment))
1972 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
1973 skip = musicexp.SkipEvent()
1975 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)
1977 # TODO: Use the time signature for skips, too. Problem: The skip
1978 # might not start at a measure boundary!
1979 if duration_log > 0: # denominator is a power of 2...
1980 if diff.numerator () == 3:
1984 duration_factor = Rational (diff.numerator ())
1986 # for skips of a whole or more, simply use s1*factor
1988 duration_factor = diff
1989 skip.duration.duration_log = duration_log
1990 skip.duration.factor = duration_factor
1991 skip.duration.dots = duration_dots
1993 evc = musicexp.ChordEvent ()
1994 evc.elements.append (skip)
1995 self.add_music (evc, diff, False)
1997 if diff > Rational (0) and moment == 0:
1998 self.ignore_skips = False
2000 def last_event_chord (self, starting_at):
2004 # if the position matches, find the last ChordEvent, do not cross a bar line!
2005 at = len(self.elements) - 1
2007 not isinstance (self.elements[at], musicexp.ChordEvent) and
2008 not isinstance (self.elements[at], musicexp.BarLine)):
2013 and isinstance (self.elements[at], musicexp.ChordEvent)
2014 and self.begin_moment == starting_at):
2015 value = self.elements[at]
2017 self.jumpto (starting_at)
2021 def correct_negative_skip (self, goto):
2022 self.end_moment = goto
2023 self.begin_moment = goto
2024 evc = musicexp.ChordEvent ()
2025 self.elements.append (evc)
2029 def __init__ (self):
2030 self.voicename = None
2031 self.voicedata = None
2032 self.ly_voice = None
2033 self.figured_bass = None
2034 self.chordnames = None
2035 self.lyrics_dict = {}
2036 self.lyrics_order = []
2038 def measure_length_from_attributes (attr, current_measure_length):
2039 len = attr.get_measure_length ()
2041 len = current_measure_length
2044 def musicxml_voice_to_lily_voice (voice):
2048 return_value = VoiceData ()
2049 return_value.voicedata = voice
2051 # First pitch needed for relative mode (if selected in command-line options)
2054 # Needed for melismata detection (ignore lyrics on those notes!):
2059 ignore_lyrics = False
2061 current_staff = None
2063 pending_figured_bass = []
2064 pending_chordnames = []
2066 # Make sure that the keys in the dict don't get reordered, since
2067 # we need the correct ordering of the lyrics stanzas! By default,
2068 # a dict will reorder its keys
2069 return_value.lyrics_order = voice.get_lyrics_numbers ()
2070 for k in return_value.lyrics_order:
2073 voice_builder = LilyPondVoiceBuilder ()
2074 figured_bass_builder = LilyPondVoiceBuilder ()
2075 chordnames_builder = LilyPondVoiceBuilder ()
2076 current_measure_length = Rational (4, 4)
2077 voice_builder.set_measure_length (current_measure_length)
2079 for n in voice._elements:
2081 if n.get_name () == 'forward':
2083 staff = n.get_maybe_exist_named_child ('staff')
2085 staff = staff.get_text ()
2086 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
2087 voice_builder.add_command (musicexp.StaffChange (staff))
2088 current_staff = staff
2090 if isinstance (n, musicxml.Partial) and n.partial > 0:
2091 a = musicxml_partial_to_lily (n.partial)
2093 voice_builder.add_partial (a)
2094 figured_bass_builder.add_partial (a)
2095 chordnames_builder.add_partial (a)
2098 is_chord = n.get_maybe_exist_named_child ('chord')
2099 is_after_grace = (isinstance (n, musicxml.Note) and n.is_after_grace ());
2100 if not is_chord and not is_after_grace:
2102 voice_builder.jumpto (n._when)
2103 figured_bass_builder.jumpto (n._when)
2104 chordnames_builder.jumpto (n._when)
2105 except NegativeSkip, neg:
2106 voice_builder.correct_negative_skip (n._when)
2107 figured_bass_builder.correct_negative_skip (n._when)
2108 chordnames_builder.correct_negative_skip (n._when)
2109 n.message (_ ("Negative skip found: from %s to %s, difference is %s") % (neg.here, neg.dest, neg.dest - neg.here))
2111 if isinstance (n, musicxml.Barline):
2112 barlines = musicxml_barline_to_lily (n)
2114 if isinstance (a, musicexp.BarLine):
2115 voice_builder.add_barline (a)
2116 figured_bass_builder.add_barline (a, False)
2117 chordnames_builder.add_barline (a, False)
2118 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
2119 voice_builder.add_command (a)
2120 figured_bass_builder.add_barline (a, False)
2121 chordnames_builder.add_barline (a, False)
2125 if isinstance (n, musicxml.Print):
2126 for a in musicxml_print_to_lily (n):
2127 voice_builder.add_command (a, False)
2130 # Continue any multimeasure-rests before trying to add bar checks!
2131 # Don't handle new MM rests yet, because for them we want bar checks!
2132 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
2133 if (rest and rest.is_whole_measure ()
2134 and voice_builder.pending_multibar > Rational (0)):
2135 voice_builder.add_multibar_rest (n._duration)
2139 # print a bar check at the beginning of each measure!
2140 if n.is_first () and n._measure_position == Rational (0) and n != voice._elements[0]:
2142 num = int (n.get_parent ().number)
2146 voice_builder.add_bar_check (num)
2147 figured_bass_builder.add_bar_check (num)
2148 chordnames_builder.add_bar_check (num)
2150 # Start any new multimeasure rests
2151 if (rest and rest.is_whole_measure ()):
2152 voice_builder.add_multibar_rest (n._duration)
2156 if isinstance (n, musicxml.Direction):
2157 for a in musicxml_direction_to_lily (n):
2158 if a.wait_for_note ():
2159 voice_builder.add_dynamics (a)
2161 voice_builder.add_command (a)
2164 if isinstance (n, musicxml.Harmony):
2165 for a in musicxml_harmony_to_lily (n):
2166 if a.wait_for_note ():
2167 voice_builder.add_dynamics (a)
2169 voice_builder.add_command (a)
2170 for a in musicxml_harmony_to_lily_chordname (n):
2171 pending_chordnames.append (a)
2174 if isinstance (n, musicxml.FiguredBass):
2175 a = musicxml_figured_bass_to_lily (n)
2177 pending_figured_bass.append (a)
2180 if isinstance (n, musicxml.Attributes):
2181 for a in musicxml_attributes_to_lily (n):
2182 voice_builder.add_command (a)
2183 measure_length = measure_length_from_attributes (n, current_measure_length)
2184 if current_measure_length != measure_length:
2185 current_measure_length = measure_length
2186 voice_builder.set_measure_length (current_measure_length)
2189 if not n.__class__.__name__ == 'Note':
2190 n.message (_ ('unexpected %s; expected %s or %s or %s') % (n, 'Note', 'Attributes', 'Barline'))
2193 main_event = musicxml_note_to_lily_main_event (n)
2194 if main_event and not first_pitch:
2195 first_pitch = main_event.pitch
2196 # ignore lyrics for notes inside a slur, tie, chord or beam
2197 ignore_lyrics = inside_slur or is_tied or is_chord or is_beamed
2199 if main_event and hasattr (main_event, 'drum_type') and main_event.drum_type:
2200 modes_found['drummode'] = True
2202 ev_chord = voice_builder.last_event_chord (n._when)
2204 ev_chord = musicexp.ChordEvent()
2205 voice_builder.add_music (ev_chord, n._duration)
2208 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
2210 is_after_grace = ev_chord.has_elements () or n.is_after_grace ();
2211 is_chord = n.get_maybe_exist_typed_child (musicxml.Chord)
2215 # after-graces and other graces use different lists; Depending on
2216 # whether we have a chord or not, obtain either a new ChordEvent or
2217 # the previous one to create a chord
2219 if ev_chord.after_grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2220 grace_chord = ev_chord.after_grace_elements.get_last_event_chord ()
2222 grace_chord = musicexp.ChordEvent ()
2223 ev_chord.append_after_grace (grace_chord)
2225 if ev_chord.grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2226 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
2228 grace_chord = musicexp.ChordEvent ()
2229 ev_chord.append_grace (grace_chord)
2231 if hasattr (grace, 'slash') and not is_after_grace:
2232 # TODO: use grace_type = "appoggiatura" for slurred grace notes
2233 if grace.slash == "yes":
2234 ev_chord.grace_type = "acciaccatura"
2235 # now that we have inserted the chord into the grace music, insert
2236 # everything into that chord instead of the ev_chord
2237 ev_chord = grace_chord
2238 ev_chord.append (main_event)
2239 ignore_lyrics = True
2241 ev_chord.append (main_event)
2242 # When a note/chord has grace notes (duration==0), the duration of the
2243 # event chord is not yet known, but the event chord was already added
2244 # with duration 0. The following correct this when we hit the real note!
2245 if voice_builder.current_duration () == 0 and n._duration > 0:
2246 voice_builder.set_duration (n._duration)
2248 # if we have a figured bass, set its voice builder to the correct position
2249 # and insert the pending figures
2250 if pending_figured_bass:
2252 figured_bass_builder.jumpto (n._when)
2253 except NegativeSkip, neg:
2255 for fb in pending_figured_bass:
2256 # if a duration is given, use that, otherwise the one of the note
2257 dur = fb.real_duration
2259 dur = ev_chord.get_length ()
2261 fb.duration = ev_chord.get_duration ()
2262 figured_bass_builder.add_music (fb, dur)
2263 pending_figured_bass = []
2265 if pending_chordnames:
2267 chordnames_builder.jumpto (n._when)
2268 except NegativeSkip, neg:
2270 for cn in pending_chordnames:
2271 # Assign the duration of the EventChord
2272 cn.duration = ev_chord.get_duration ()
2273 chordnames_builder.add_music (cn, ev_chord.get_length ())
2274 pending_chordnames = []
2276 notations_children = n.get_typed_children (musicxml.Notations)
2280 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
2281 # +tied | +slur | +tuplet | glissando | slide |
2282 # ornaments | technical | articulations | dynamics |
2283 # +fermata | arpeggiate | non-arpeggiate |
2284 # accidental-mark | other-notation
2285 for notations in notations_children:
2286 for tuplet_event in notations.get_tuplets():
2287 time_mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
2288 tuplet_events.append ((ev_chord, tuplet_event, time_mod))
2290 # First, close all open slurs, only then start any new slur
2291 # TODO: Record the number of the open slur to dtermine the correct
2293 endslurs = [s for s in notations.get_named_children ('slur')
2294 if s.get_type () in ('stop')]
2295 if endslurs and not inside_slur:
2296 endslurs[0].message (_ ('Encountered closing slur, but no slur is open'))
2298 if len (endslurs) > 1:
2299 endslurs[0].message (_ ('Cannot have two simultaneous (closing) slurs'))
2300 # record the slur status for the next note in the loop
2302 lily_ev = musicxml_spanner_to_lily_event (endslurs[0])
2303 ev_chord.append (lily_ev)
2305 startslurs = [s for s in notations.get_named_children ('slur')
2306 if s.get_type () in ('start')]
2307 if startslurs and inside_slur:
2308 startslurs[0].message (_ ('Cannot have a slur inside another slur'))
2310 if len (startslurs) > 1:
2311 startslurs[0].message (_ ('Cannot have two simultaneous slurs'))
2312 # record the slur status for the next note in the loop
2314 lily_ev = musicxml_spanner_to_lily_event (startslurs[0])
2315 ev_chord.append (lily_ev)
2319 mxl_tie = notations.get_tie ()
2320 if mxl_tie and mxl_tie.type == 'start':
2321 ev_chord.append (musicexp.TieEvent ())
2327 fermatas = notations.get_named_children ('fermata')
2329 ev = musicxml_fermata_to_lily_event (a)
2331 ev_chord.append (ev)
2333 arpeggiate = notations.get_named_children ('arpeggiate')
2334 for a in arpeggiate:
2335 ev = musicxml_arpeggiate_to_lily_event (a)
2337 ev_chord.append (ev)
2339 arpeggiate = notations.get_named_children ('non-arpeggiate')
2340 for a in arpeggiate:
2341 ev = musicxml_nonarpeggiate_to_lily_event (a)
2343 ev_chord.append (ev)
2345 glissandos = notations.get_named_children ('glissando')
2346 glissandos += notations.get_named_children ('slide')
2347 for a in glissandos:
2348 ev = musicxml_spanner_to_lily_event (a)
2350 ev_chord.append (ev)
2352 # accidental-marks are direct children of <notation>!
2353 for a in notations.get_named_children ('accidental-mark'):
2354 ev = musicxml_articulation_to_lily_event (a)
2356 ev_chord.append (ev)
2358 # Articulations can contain the following child elements:
2359 # accent | strong-accent | staccato | tenuto |
2360 # detached-legato | staccatissimo | spiccato |
2361 # scoop | plop | doit | falloff | breath-mark |
2362 # caesura | stress | unstress
2363 # Technical can contain the following child elements:
2364 # up-bow | down-bow | harmonic | open-string |
2365 # thumb-position | fingering | pluck | double-tongue |
2366 # triple-tongue | stopped | snap-pizzicato | fret |
2367 # string | hammer-on | pull-off | bend | tap | heel |
2368 # toe | fingernails | other-technical
2369 # Ornaments can contain the following child elements:
2370 # trill-mark | turn | delayed-turn | inverted-turn |
2371 # shake | wavy-line | mordent | inverted-mordent |
2372 # schleifer | tremolo | other-ornament, accidental-mark
2373 ornaments = notations.get_named_children ('ornaments')
2374 ornaments += notations.get_named_children ('articulations')
2375 ornaments += notations.get_named_children ('technical')
2378 for ch in a.get_all_children ():
2379 ev = musicxml_articulation_to_lily_event (ch)
2381 ev_chord.append (ev)
2383 dynamics = notations.get_named_children ('dynamics')
2385 for ch in a.get_all_children ():
2386 ev = musicxml_dynamics_to_lily_event (ch)
2388 ev_chord.append (ev)
2391 mxl_beams = [b for b in n.get_named_children ('beam')
2392 if (b.get_type () in ('begin', 'end')
2393 and b.is_primary ())]
2394 if mxl_beams and not conversion_settings.ignore_beaming:
2395 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
2397 ev_chord.append (beam_ev)
2398 if beam_ev.span_direction == -1: # beam and thus melisma starts here
2400 elif beam_ev.span_direction == 1: # beam and thus melisma ends here
2403 # Extract the lyrics
2404 if not rest and not ignore_lyrics:
2405 note_lyrics_processed = []
2406 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
2407 for l in note_lyrics_elements:
2408 if l.get_number () < 0:
2409 for k in lyrics.keys ():
2410 lyrics[k].append (musicxml_lyrics_to_text (l))
2411 note_lyrics_processed.append (k)
2413 lyrics[l.number].append(musicxml_lyrics_to_text (l))
2414 note_lyrics_processed.append (l.number)
2415 for lnr in lyrics.keys ():
2416 if not lnr in note_lyrics_processed:
2417 lyrics[lnr].append ("\skip4")
2419 # Assume that a <tie> element only lasts for one note.
2420 # This might not be correct MusicXML interpretation, but works for
2421 # most cases and fixes broken files, which have the end tag missing
2422 if is_tied and not tie_started:
2425 ## force trailing mm rests to be written out.
2426 voice_builder.add_music (musicexp.ChordEvent (), Rational (0))
2428 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
2429 ly_voice = group_repeats (ly_voice)
2431 seq_music = musicexp.SequentialMusic ()
2433 if 'drummode' in modes_found.keys ():
2434 ## \key <pitch> barfs in drummode.
2435 ly_voice = [e for e in ly_voice
2436 if not isinstance(e, musicexp.KeySignatureChange)]
2438 seq_music.elements = ly_voice
2439 for k in lyrics.keys ():
2440 return_value.lyrics_dict[k] = musicexp.Lyrics ()
2441 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
2444 if len (modes_found) > 1:
2445 ly.warning (_ ('cannot simultaneously have more than one mode: %s') % modes_found.keys ())
2447 if options.relative:
2448 v = musicexp.RelativeMusic ()
2449 v.element = seq_music
2450 v.basepitch = first_pitch
2453 return_value.ly_voice = seq_music
2454 for mode in modes_found.keys ():
2455 v = musicexp.ModeChangingMusicWrapper()
2456 v.element = seq_music
2458 return_value.ly_voice = v
2460 # create \figuremode { figured bass elements }
2461 if figured_bass_builder.has_relevant_elements:
2462 fbass_music = musicexp.SequentialMusic ()
2463 fbass_music.elements = group_repeats (figured_bass_builder.elements)
2464 v = musicexp.ModeChangingMusicWrapper()
2465 v.mode = 'figuremode'
2466 v.element = fbass_music
2467 return_value.figured_bass = v
2469 # create \chordmode { chords }
2470 if chordnames_builder.has_relevant_elements:
2471 cname_music = musicexp.SequentialMusic ()
2472 cname_music.elements = group_repeats (chordnames_builder.elements)
2473 v = musicexp.ModeChangingMusicWrapper()
2474 v.mode = 'chordmode'
2475 v.element = cname_music
2476 return_value.chordnames = v
2480 def musicxml_id_to_lily (id):
2481 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
2482 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
2484 for digit in digits:
2485 d = digits.index (digit)
2486 id = re.sub ('%d' % d, digit, id)
2488 id = re.sub ('[^a-zA-Z]', 'X', id)
2491 def musicxml_pitch_to_lily (mxl_pitch):
2492 p = musicexp.Pitch ()
2493 p.alteration = mxl_pitch.get_alteration ()
2494 p.step = musicxml_step_to_lily (mxl_pitch.get_step ())
2495 p.octave = mxl_pitch.get_octave () - 4
2498 def musicxml_unpitched_to_lily (mxl_unpitched):
2500 step = mxl_unpitched.get_step ()
2502 p = musicexp.Pitch ()
2503 p.step = musicxml_step_to_lily (step)
2504 octave = mxl_unpitched.get_octave ()
2506 p.octave = octave - 4
2509 def musicxml_restdisplay_to_lily (mxl_rest):
2511 step = mxl_rest.get_step ()
2513 p = musicexp.Pitch ()
2514 p.step = musicxml_step_to_lily (step)
2515 octave = mxl_rest.get_octave ()
2517 p.octave = octave - 4
2520 def voices_in_part (part):
2521 """Return a Name -> Voice dictionary for PART"""
2523 part.extract_voices ()
2524 voices = part.get_voices ()
2525 part_info = part.get_staff_attributes ()
2527 return (voices, part_info)
2529 def voices_in_part_in_parts (parts):
2530 """return a Part -> Name -> Voice dictionary"""
2531 # don't crash if p doesn't have an id (that's invalid MusicXML,
2532 # but such files are out in the wild!
2535 voices = voices_in_part (p)
2536 if (hasattr (p, "id")):
2537 dictionary[p.id] = voices
2539 # TODO: extract correct part id from other sources
2540 dictionary[None] = voices
2544 def get_all_voices (parts):
2545 all_voices = voices_in_part_in_parts (parts)
2548 all_ly_staffinfo = {}
2549 for p, (name_voice, staff_info) in all_voices.items ():
2552 for n, v in name_voice.items ():
2553 ly.progress (_ ("Converting to LilyPond expressions..."), True)
2554 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
2555 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
2557 all_ly_voices[p] = part_ly_voices
2558 all_ly_staffinfo[p] = staff_info
2560 return (all_ly_voices, all_ly_staffinfo)
2563 def option_parser ():
2564 p = ly.get_option_parser (usage = _ ("musicxml2ly [OPTION]... FILE.xml"),
2566 _ ("""Convert MusicXML from FILE.xml to LilyPond input.
2567 If the given filename is -, musicxml2ly reads from the command line.
2568 """), add_help_option=False)
2570 p.add_option("-h", "--help",
2572 help=_ ("show this help and exit"))
2574 p.version = ('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
2576 _ ("""Copyright (c) 2005--2012 by
2577 Han-Wen Nienhuys <hanwen@xs4all.nl>,
2578 Jan Nieuwenhuizen <janneke@gnu.org> and
2579 Reinhold Kainhofer <reinhold@kainhofer.com>
2583 This program is free software. It is covered by the GNU General Public
2584 License and you are welcome to change it and/or distribute copies of it
2585 under certain conditions. Invoke as `%s --warranty' for more
2586 information.""") % 'lilypond')
2588 p.add_option("--version",
2590 help=_ ("show version number and exit"))
2592 p.add_option ('-v', '--verbose',
2594 callback=ly.handle_loglevel_option,
2595 callback_args=("DEBUG",),
2596 help = _ ("be verbose"))
2598 p.add_option ('', '--lxml',
2599 action = "store_true",
2602 help = _ ("use lxml.etree; uses less memory and cpu time"))
2604 p.add_option ('-z', '--compressed',
2605 action = "store_true",
2606 dest = 'compressed',
2608 help = _ ("input file is a zip-compressed MusicXML file"))
2610 p.add_option ('-r', '--relative',
2611 action = "store_true",
2614 help = _ ("convert pitches in relative mode (default)"))
2616 p.add_option ('-a', '--absolute',
2617 action = "store_false",
2619 help = _ ("convert pitches in absolute mode"))
2621 p.add_option ('-l', '--language',
2622 metavar = _ ("LANG"),
2624 help = _ ("use LANG for pitch names, e.g. 'deutsch' for note names in German"))
2626 p.add_option ("--loglevel",
2627 help=_ ("Print log messages according to LOGLEVEL "
2628 "(NONE, ERROR, WARNING, PROGRESS (default), DEBUG)"),
2629 metavar=_ ("LOGLEVEL"),
2631 callback=ly.handle_loglevel_option,
2634 p.add_option ('--nd', '--no-articulation-directions',
2635 action = "store_false",
2637 dest = "convert_directions",
2638 help = _ ("do not convert directions (^, _ or -) for articulations, dynamics, etc."))
2640 p.add_option ('--nrp', '--no-rest-positions',
2641 action = "store_false",
2643 dest = "convert_rest_positions",
2644 help = _ ("do not convert exact vertical positions of rests"))
2646 p.add_option ('--npl', '--no-page-layout',
2647 action = "store_false",
2649 dest = "convert_page_layout",
2650 help = _ ("do not convert the exact page layout and breaks"))
2652 p.add_option ('--no-beaming',
2653 action = "store_false",
2655 dest = "convert_beaming",
2656 help = _ ("do not convert beaming information, use lilypond's automatic beaming instead"))
2658 p.add_option ('-o', '--output',
2659 metavar = _ ("FILE"),
2663 dest = 'output_name',
2664 help = _ ("set output filename to FILE, stdout if -"))
2666 p.add_option ('-m', '--midi',
2667 action = "store_true",
2670 help = _("activate midi-block"))
2672 p.add_option_group ('',
2674 _ ("Report bugs via %s")
2675 % 'http://post.gmane.org/post.php'
2676 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
2679 def music_xml_voice_name_to_lily_name (part_id, name):
2680 str = "Part%sVoice%s" % (part_id, name)
2681 return musicxml_id_to_lily (str)
2683 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
2684 str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
2685 return musicxml_id_to_lily (str)
2687 def music_xml_figuredbass_name_to_lily_name (part_id, voicename):
2688 str = "Part%sVoice%sFiguredBass" % (part_id, voicename)
2689 return musicxml_id_to_lily (str)
2691 def music_xml_chordnames_name_to_lily_name (part_id, voicename):
2692 str = "Part%sVoice%sChords" % (part_id, voicename)
2693 return musicxml_id_to_lily (str)
2695 def print_voice_definitions (printer, part_list, voices):
2696 for part in part_list:
2698 nv_dict = voices.get (part_id, {})
2699 for (name, voice) in nv_dict.items ():
2700 k = music_xml_voice_name_to_lily_name (part_id, name)
2701 printer.dump ('%s = ' % k)
2702 voice.ly_voice.print_ly (printer)
2704 if voice.chordnames:
2705 cnname = music_xml_chordnames_name_to_lily_name (part_id, name)
2706 printer.dump ('%s = ' % cnname )
2707 voice.chordnames.print_ly (printer)
2709 for l in voice.lyrics_order:
2710 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
2711 printer.dump ('%s = ' % lname )
2712 voice.lyrics_dict[l].print_ly (printer)
2714 if voice.figured_bass:
2715 fbname = music_xml_figuredbass_name_to_lily_name (part_id, name)
2716 printer.dump ('%s = ' % fbname )
2717 voice.figured_bass.print_ly (printer)
2722 return dict ([(elt, 1) for elt in l]).keys ()
2724 # format the information about the staff in the form
2727 # [voiceid1, [lyricsid11, lyricsid12,...], figuredbassid1],
2728 # [voiceid2, [lyricsid21, lyricsid22,...], figuredbassid2],
2732 # raw_voices is of the form [(voicename, lyricsids, havefiguredbass)*]
2733 def format_staff_info (part_id, staff_id, raw_voices):
2735 for (v, lyricsids, figured_bass, chordnames) in raw_voices:
2736 voice_name = music_xml_voice_name_to_lily_name (part_id, v)
2737 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
2739 figured_bass_name = ''
2741 figured_bass_name = music_xml_figuredbass_name_to_lily_name (part_id, v)
2742 chordnames_name = ''
2744 chordnames_name = music_xml_chordnames_name_to_lily_name (part_id, v)
2745 voices.append ([voice_name, voice_lyrics, figured_bass_name, chordnames_name])
2746 return [staff_id, voices]
2748 def update_score_setup (score_structure, part_list, voices):
2750 for part_definition in part_list:
2751 part_id = part_definition.id
2752 nv_dict = voices.get (part_id)
2754 ly.warning (_ ('unknown part in part-list: %s') % part_id)
2757 staves = reduce (lambda x,y: x+ y,
2758 [voice.voicedata._staves.keys ()
2759 for voice in nv_dict.values ()],
2762 if len (staves) > 1:
2764 staves = uniq_list (staves)
2767 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2768 for (voice_name, voice) in nv_dict.items ()
2769 if voice.voicedata._start_staff == s]
2770 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
2772 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2773 for (voice_name, voice) in nv_dict.items ()]
2774 staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
2775 score_structure.set_part_information (part_id, staves_info)
2777 # Set global values in the \layout block, like auto-beaming etc.
2778 def update_layout_information ():
2779 if not conversion_settings.ignore_beaming and layout_information:
2780 layout_information.set_context_item ('Score', 'autoBeaming = ##f')
2782 def print_ly_preamble (printer, filename):
2783 printer.dump_version ()
2784 printer.print_verbatim ('%% automatically converted by musicxml2ly from %s\n' % filename)
2786 def print_ly_additional_definitions (printer, filename):
2787 if needed_additional_definitions:
2789 printer.print_verbatim ('%% additional definitions required by the score:')
2791 for a in set(needed_additional_definitions):
2792 printer.print_verbatim (additional_definitions.get (a, ''))
2796 # Read in the tree from the given I/O object (either file or string) and
2797 # demarshall it using the classes from the musicxml.py file
2798 def read_xml (io_object, use_lxml):
2801 tree = lxml.etree.parse (io_object)
2802 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
2805 from xml.dom import minidom, Node
2806 doc = minidom.parse(io_object)
2807 node = doc.documentElement
2808 return musicxml.minidom_demarshal_node (node)
2812 def read_musicxml (filename, compressed, use_lxml):
2816 ly.progress (_ ("Input is compressed, extracting raw MusicXML data from stdin"), True)
2817 # unfortunately, zipfile.ZipFile can't read directly from
2818 # stdin, so copy everything from stdin to a temp file and read
2819 # that. TemporaryFile() will remove the file when it is closed.
2820 tmp = tempfile.TemporaryFile()
2821 sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0) # Make sys.stdin binary
2822 bytes_read = sys.stdin.read (8192)
2824 for b in bytes_read:
2826 bytes_read = sys.stdin.read (8192)
2827 z = zipfile.ZipFile (tmp, "r")
2829 ly.progress (_ ("Input file %s is compressed, extracting raw MusicXML data") % filename, True)
2830 z = zipfile.ZipFile (filename, "r")
2831 container_xml = z.read ("META-INF/container.xml")
2832 if not container_xml:
2834 container = read_xml (StringIO.StringIO (container_xml), use_lxml)
2837 rootfiles = container.get_maybe_exist_named_child ('rootfiles')
2840 rootfile_list = rootfiles.get_named_children ('rootfile')
2842 if len (rootfile_list) > 0:
2843 mxml_file = getattr (rootfile_list[0], 'full-path', None)
2845 raw_string = z.read (mxml_file)
2848 io_object = StringIO.StringIO (raw_string)
2849 elif filename == "-":
2850 io_object = sys.stdin
2852 io_object = filename
2854 return read_xml (io_object, use_lxml)
2857 def convert (filename, options):
2859 ly.progress (_ ("Reading MusicXML from Standard input ..."), True)
2861 ly.progress (_ ("Reading MusicXML from %s ...") % filename, True)
2863 tree = read_musicxml (filename, options.compressed, options.use_lxml)
2864 score_information = extract_score_information (tree)
2865 paper_information = extract_paper_information (tree)
2867 parts = tree.get_typed_children (musicxml.Part)
2868 (voices, staff_info) = get_all_voices (parts)
2871 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
2873 score = extract_score_structure (mxl_pl, staff_info)
2874 part_list = mxl_pl.get_named_children ("score-part")
2876 # score information is contained in the <work>, <identification> or <movement-title> tags
2877 update_score_setup (score, part_list, voices)
2878 # After the conversion, update the list of settings for the \layout block
2879 update_layout_information ()
2881 if not options.output_name:
2882 options.output_name = os.path.basename (filename)
2883 options.output_name = os.path.splitext (options.output_name)[0]
2884 elif re.match (".*\.ly", options.output_name):
2885 options.output_name = os.path.splitext (options.output_name)[0]
2888 #defs_ly_name = options.output_name + '-defs.ly'
2889 if (options.output_name == "-"):
2890 output_ly_name = 'Standard output'
2892 output_ly_name = options.output_name + '.ly'
2894 ly.progress (_ ("Output to `%s'") % output_ly_name, True)
2895 printer = musicexp.Output_printer()
2896 #ly.progress (_ ("Output to `%s'") % defs_ly_name, True)
2897 if (options.output_name == "-"):
2898 printer.set_file (codecs.getwriter ("utf-8")(sys.stdout))
2900 printer.set_file (codecs.open (output_ly_name, 'wb', encoding='utf-8'))
2901 print_ly_preamble (printer, filename)
2902 print_ly_additional_definitions (printer, filename)
2903 if score_information:
2904 score_information.print_ly (printer)
2905 if paper_information and conversion_settings.convert_page_layout:
2906 paper_information.print_ly (printer)
2907 if layout_information:
2908 layout_information.print_ly (printer)
2909 print_voice_definitions (printer, part_list, voices)
2912 printer.dump ("% The score definition")
2914 score.print_ly (printer)
2919 def get_existing_filename_with_extension (filename, ext):
2920 if os.path.exists (filename):
2922 newfilename = filename + "." + ext
2923 if os.path.exists (newfilename):
2925 newfilename = filename + ext
2926 if os.path.exists (newfilename):
2931 opt_parser = option_parser()
2934 (options, args) = opt_parser.parse_args ()
2936 opt_parser.print_usage()
2940 musicexp.set_create_midi (options.midi)
2942 if options.language:
2943 musicexp.set_pitch_language (options.language)
2944 needed_additional_definitions.append (options.language)
2945 additional_definitions[options.language] = "\\language \"%s\"\n" % options.language
2946 conversion_settings.ignore_beaming = not options.convert_beaming
2947 conversion_settings.convert_page_layout = options.convert_page_layout
2949 # Allow the user to leave out the .xml or xml on the filename
2950 basefilename = args[0].decode('utf-8')
2951 if basefilename == "-": # Read from stdin
2954 filename = get_existing_filename_with_extension (basefilename, "xml")
2956 filename = get_existing_filename_with_extension (basefilename, "mxl")
2957 options.compressed = True
2958 if filename and filename.endswith ("mxl"):
2959 options.compressed = True
2961 if filename and (filename == "-" or os.path.exists (filename)):
2962 voices = convert (filename, options)
2964 ly.error (_ ("Unable to find input file %s") % basefilename)
2966 if __name__ == '__main__':