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 ()
39 ly.stderr_write (str + '\n')
42 def error_message (str):
43 ly.stderr_write (str + '\n')
46 needed_additional_definitions = []
47 additional_definitions = {
49 "tuplet-note-wrapper": """ % a formatter function, which is simply a wrapper around an existing
50 % tuplet formatter function. It takes the value returned by the given
51 % function and appends a note of given length.
52 #(define-public ((tuplet-number::append-note-wrapper function note) grob)
53 (let* ((txt (if function (function grob) #f)))
55 (markup txt #:fontsize -5 #:note note UP)
56 (markup #:fontsize -5 #:note note UP)
61 "tuplet-non-default-denominator": """#(define ((tuplet-number::non-default-tuplet-denominator-text denominator) grob)
62 (number->string (if denominator
64 (ly:event-property (event-cause grob) 'denominator))))
67 "tuplet-non-default-fraction": """#(define ((tuplet-number::non-default-tuplet-fraction-text denominator numerator) grob)
68 (let* ((ev (event-cause grob))
69 (den (if denominator denominator (ly:event-property ev 'denominator)))
70 (num (if numerator numerator (ly:event-property ev 'numerator))))
71 (format #f "~a:~a" den num)))
75 def round_to_two_digits (val):
76 return round (val * 100) / 100
78 def extract_paper_information (tree):
79 paper = musicexp.Paper ()
80 defaults = tree.get_maybe_exist_named_child ('defaults')
84 scaling = defaults.get_maybe_exist_named_child ('scaling')
86 mm = scaling.get_named_child ('millimeters')
87 mm = string.atof (mm.get_text ())
88 tn = scaling.get_maybe_exist_named_child ('tenths')
89 tn = string.atof (tn.get_text ())
91 paper.global_staff_size = mm * 72.27 / 25.4
92 # We need the scaling (i.e. the size of staff tenths for everything!
96 def from_tenths (txt):
97 return round_to_two_digits (string.atof (txt) * tenths / 10)
98 def set_paper_variable (varname, parent, element_name):
99 el = parent.get_maybe_exist_named_child (element_name)
100 if el: # Convert to cm from tenths
101 setattr (paper, varname, from_tenths (el.get_text ()))
103 pagelayout = defaults.get_maybe_exist_named_child ('page-layout')
105 # TODO: How can one have different margins for even and odd pages???
106 set_paper_variable ("page_height", pagelayout, 'page-height')
107 set_paper_variable ("page_width", pagelayout, 'page-width')
109 pmargins = pagelayout.get_named_children ('page-margins')
111 set_paper_variable ("left_margin", pm, 'left-margin')
112 set_paper_variable ("right_margin", pm, 'right-margin')
113 set_paper_variable ("bottom_margin", pm, 'bottom-margin')
114 set_paper_variable ("top_margin", pm, 'top-margin')
116 systemlayout = defaults.get_maybe_exist_named_child ('system-layout')
118 sl = systemlayout.get_maybe_exist_named_child ('system-margins')
120 set_paper_variable ("system_left_margin", sl, 'left-margin')
121 set_paper_variable ("system_right_margin", sl, 'right-margin')
122 set_paper_variable ("system_distance", systemlayout, 'system-distance')
123 set_paper_variable ("top_system_distance", systemlayout, 'top-system-distance')
125 stafflayout = defaults.get_named_children ('staff-layout')
126 for sl in stafflayout:
127 nr = getattr (sl, 'number', 1)
128 dist = sl.get_named_child ('staff-distance')
129 #TODO: the staff distance needs to be set in the Staff context!!!
131 # TODO: Finish appearance?, music-font?, word-font?, lyric-font*, lyric-language*
132 appearance = defaults.get_named_child ('appearance')
134 lws = appearance.get_named_children ('line-width')
136 # Possible types are: beam, bracket, dashes,
137 # enclosure, ending, extend, heavy barline, leger,
138 # light barline, octave shift, pedal, slur middle, slur tip,
139 # staff, stem, tie middle, tie tip, tuplet bracket, and wedge
141 w = from_tenths (lw.get_text ())
142 # TODO: Do something with these values!
143 nss = appearance.get_named_children ('note-size')
145 # Possible types are: cue, grace and large
147 sz = from_tenths (ns.get_text ())
148 # TODO: Do something with these values!
149 # <other-appearance> elements have no specified meaning
151 rawmusicfont = defaults.get_named_child ('music-font')
153 # TODO: Convert the font
155 rawwordfont = defaults.get_named_child ('word-font')
157 # TODO: Convert the font
159 rawlyricsfonts = defaults.get_named_children ('lyric-font')
160 for lyricsfont in rawlyricsfonts:
161 # TODO: Convert the font
168 # score information is contained in the <work>, <identification> or <movement-title> tags
169 # extract those into a hash, indexed by proper lilypond header attributes
170 def extract_score_information (tree):
171 header = musicexp.Header ()
172 def set_if_exists (field, value):
174 header.set_field (field, musicxml.escape_ly_output_string (value))
176 movement_title = tree.get_maybe_exist_named_child ('movement-title')
178 set_if_exists ('title', movement_title.get_text ())
179 work = tree.get_maybe_exist_named_child ('work')
181 # Overwrite the title from movement-title with work->title
182 set_if_exists ('title', work.get_work_title ())
183 set_if_exists ('worknumber', work.get_work_number ())
184 set_if_exists ('opus', work.get_opus ())
186 identifications = tree.get_named_children ('identification')
187 for ids in identifications:
188 set_if_exists ('copyright', ids.get_rights ())
189 set_if_exists ('composer', ids.get_composer ())
190 set_if_exists ('arranger', ids.get_arranger ())
191 set_if_exists ('editor', ids.get_editor ())
192 set_if_exists ('poet', ids.get_poet ())
194 set_if_exists ('tagline', ids.get_encoding_software ())
195 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
196 set_if_exists ('encodingdate', ids.get_encoding_date ())
197 set_if_exists ('encoder', ids.get_encoding_person ())
198 set_if_exists ('encodingdescription', ids.get_encoding_description ())
200 set_if_exists ('texidoc', ids.get_file_description ());
202 # Finally, apply the required compatibility modes
203 # Some applications created wrong MusicXML files, so we need to
204 # apply some compatibility mode, e.g. ignoring some features/tags
206 software = ids.get_encoding_software_list ()
208 # Case 1: "Sibelius 5.1" with the "Dolet 3.4 for Sibelius" plugin
209 # is missing all beam ends => ignore all beaming information
210 ignore_beaming_software = {
211 "Dolet 4 for Sibelius, Beta 2": "Dolet 4 for Sibelius, Beta 2",
212 "Dolet 3.5 for Sibelius": "Dolet 3.5 for Sibelius",
213 "Dolet 3.4 for Sibelius": "Dolet 3.4 for Sibelius",
214 "Dolet 3.3 for Sibelius": "Dolet 3.3 for Sibelius",
215 "Dolet 3.2 for Sibelius": "Dolet 3.2 for Sibelius",
216 "Dolet 3.1 for Sibelius": "Dolet 3.1 for Sibelius",
217 "Dolet for Sibelius 1.3": "Dolet for Sibelius 1.3",
218 "Noteworthy Composer": "Noteworthy Composer's nwc2xm[",
221 app_description = ignore_beaming_software.get (s, False);
223 conversion_settings.ignore_beaming = True
224 progress (_ ("Encountered file created by %s, containing wrong beaming information. All beaming information in the MusicXML file will be ignored") % app_description)
226 # TODO: Check for other unsupported features
234 return len (self.start) + len (self.end) == 0
235 def add_start (self, g):
236 self.start[getattr (g, 'number', "1")] = g
237 def add_end (self, g):
238 self.end[getattr (g, 'number', "1")] = g
239 def print_ly (self, printer):
240 error_message (_ ("Unprocessed PartGroupInfo %s encountered") % self)
241 def ly_expression (self):
242 error_message (_ ("Unprocessed PartGroupInfo %s encountered") % self)
245 def musicxml_step_to_lily (step):
247 return (ord (step) - ord ('A') + 7 - 2) % 7
252 def staff_attributes_to_string_tunings (mxl_attr):
253 details = mxl_attr.get_maybe_exist_named_child ('staff-details')
257 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
259 lines = string.atoi (staff_lines.get_text ())
261 tunings = [musicexp.Pitch()]*lines
262 staff_tunings = details.get_named_children ('staff-tuning')
263 for i in staff_tunings:
267 line = string.atoi (i.line) - 1
272 step = i.get_named_child (u'tuning-step')
273 step = step.get_text ().strip ()
274 p.step = musicxml_step_to_lily (step)
276 octave = i.get_named_child (u'tuning-octave')
277 octave = octave.get_text ().strip ()
278 p.octave = int (octave) - 4
280 alter = i.get_named_child (u'tuning-alter')
282 p.alteration = int (alter.get_text ().strip ())
283 # lilypond seems to use the opposite ordering than MusicXML...
289 def staff_attributes_to_lily_staff (mxl_attr):
291 return musicexp.Staff ()
293 (staff_id, attributes) = mxl_attr.items ()[0]
295 # distinguish by clef:
296 # percussion (percussion and rhythmic), tab, and everything else
298 clef = attributes.get_maybe_exist_named_child ('clef')
300 sign = clef.get_maybe_exist_named_child ('sign')
302 clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
305 details = attributes.get_named_children ('staff-details')
307 staff_lines = d.get_maybe_exist_named_child ('staff-lines')
309 lines = string.atoi (staff_lines.get_text ())
311 # TODO: Handle other staff attributes like staff-space, etc.
314 if clef_sign == "percussion" and lines == 1:
315 staff = musicexp.RhythmicStaff ()
316 elif clef_sign == "percussion":
317 staff = musicexp.DrumStaff ()
318 # staff.drum_style_table = ???
319 elif clef_sign == "tab":
320 staff = musicexp.TabStaff ()
321 staff.string_tunings = staff_attributes_to_string_tunings (attributes)
322 # staff.tablature_format = ???
324 staff = musicexp.Staff ()
325 # TODO: Handle case with lines <> 5!
327 staff.add_context_modification ("\\override StaffSymbol #'line-count = #%s" % lines)
333 def extract_score_structure (part_list, staffinfo):
334 score = musicexp.Score ()
335 structure = musicexp.StaffGroup (None)
336 score.set_contents (structure)
341 def read_score_part (el):
342 if not isinstance (el, musicxml.Score_part):
344 # Depending on the attributes of the first measure, we create different
345 # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
346 staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
350 partname = el.get_maybe_exist_named_child ('part-name')
351 # Finale gives unnamed parts the name "MusicXML Part" automatically!
352 if partname and partname.get_text() != "MusicXML Part":
353 staff.instrument_name = partname.get_text ()
354 # part-name-display overrides part-name!
355 partname = el.get_maybe_exist_named_child ("part-name-display")
357 staff.instrument_name = extract_display_text (partname)
359 partdisplay = el.get_maybe_exist_named_child ('part-abbreviation')
361 staff.short_instrument_name = partdisplay.get_text ()
362 # part-abbreviation-display overrides part-abbreviation!
363 partdisplay = el.get_maybe_exist_named_child ("part-abbreviation-display")
365 staff.short_instrument_name = extract_display_text (partdisplay)
366 # TODO: Read in the MIDI device / instrument
370 def read_score_group (el):
371 if not isinstance (el, musicxml.Part_group):
373 group = musicexp.StaffGroup ()
374 if hasattr (el, 'number'):
377 #currentgroups_dict[id] = group
378 #currentgroups.append (id)
379 if el.get_maybe_exist_named_child ('group-name'):
380 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
381 if el.get_maybe_exist_named_child ('group-abbreviation'):
382 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
383 if el.get_maybe_exist_named_child ('group-symbol'):
384 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
385 if el.get_maybe_exist_named_child ('group-barline'):
386 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
390 parts_groups = part_list.get_all_children ()
392 # the start/end group tags are not necessarily ordered correctly and groups
393 # might even overlap, so we can't go through the children sequentially!
395 # 1) Replace all Score_part objects by their corresponding Staff objects,
396 # also collect all group start/stop points into one PartGroupInfo object
398 group_info = PartGroupInfo ()
399 for el in parts_groups:
400 if isinstance (el, musicxml.Score_part):
401 if not group_info.is_empty ():
402 staves.append (group_info)
403 group_info = PartGroupInfo ()
404 staff = read_score_part (el)
406 staves.append (staff)
407 elif isinstance (el, musicxml.Part_group):
408 if el.type == "start":
409 group_info.add_start (el)
410 elif el.type == "stop":
411 group_info.add_end (el)
412 if not group_info.is_empty ():
413 staves.append (group_info)
415 # 2) Now, detect the groups:
418 while pos < len (staves):
420 if isinstance (el, PartGroupInfo):
422 if len (group_starts) > 0:
423 prev_start = group_starts[-1]
424 elif len (el.end) > 0: # no group to end here
426 if len (el.end) > 0: # closes an existing group
427 ends = el.end.keys ()
428 prev_started = staves[prev_start].start.keys ()
430 intersection = filter(lambda x:x in ends, prev_started)
431 if len (intersection) > 0:
432 grpid = intersection[0]
434 # Close the last started group
435 grpid = staves[prev_start].start.keys () [0]
436 # Find the corresponding closing tag and remove it!
439 while j < len (staves) and not foundclosing:
440 if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
442 del staves[j].end[grpid]
443 if staves[j].is_empty ():
446 grpobj = staves[prev_start].start[grpid]
447 group = read_score_group (grpobj)
448 # remove the id from both the start and end
449 if el.end.has_key (grpid):
451 del staves[prev_start].start[grpid]
454 # replace the staves with the whole group
455 for j in staves[(prev_start + 1):pos]:
456 group.append_staff (j)
457 del staves[(prev_start + 1):pos]
458 staves.insert (prev_start + 1, group)
459 # reset pos so that we continue at the correct position
461 # remove an empty start group
462 if staves[prev_start].is_empty ():
463 del staves[prev_start]
464 group_starts.remove (prev_start)
466 elif len (el.start) > 0: # starts new part groups
467 group_starts.append (pos)
470 if len (staves) == 1:
473 structure.append_staff (i)
477 def musicxml_duration_to_lily (mxl_note):
478 # if the note has no Type child, then that method returns None. In that case,
479 # use the <duration> tag instead. If that doesn't exist, either -> Error
480 dur = mxl_note.get_duration_info ()
482 d = musicexp.Duration ()
483 d.duration_log = dur[0]
485 # Grace notes by specification have duration 0, so no time modification
486 # factor is possible. It even messes up the output with *0/1
487 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
488 d.factor = mxl_note._duration / d.get_length ()
492 if mxl_note._duration > 0:
493 return rational_to_lily_duration (mxl_note._duration)
495 mxl_note.message (_ ("Encountered note at %s without type and duration (=%s)") % (mxl_note.start, mxl_note._duration) )
499 def rational_to_lily_duration (rational_len):
500 d = musicexp.Duration ()
502 rational_len.normalize_self ()
503 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)
505 # Duration of the form 1/2^n or 3/2^n can be converted to a simple lilypond duration
506 dots = {1: 0, 3: 1, 7: 2, 15: 3, 31: 4, 63: 5, 127: 6}.get (rational_len.numerator(), -1)
507 if ( d_log >= dots >= 0 ):
508 # account for the dots!
509 d.duration_log = d_log - dots
512 d.duration_log = d_log
513 d.factor = Rational (rational_len.numerator ())
515 error_message (_ ("Encountered rational duration with denominator %s, "
516 "unable to convert to lilypond duration") %
517 rational_len.denominator ())
518 # TODO: Test the above error message
523 def musicxml_partial_to_lily (partial_len):
525 p = musicexp.Partial ()
526 p.partial = rational_to_lily_duration (partial_len)
531 # Detect repeats and alternative endings in the chord event list (music_list)
532 # and convert them to the corresponding musicexp objects, containing nested
534 def group_repeats (music_list):
535 repeat_replaced = True
538 # Walk through the list of expressions, looking for repeat structure
539 # (repeat start/end, corresponding endings). If we find one, try to find the
540 # last event of the repeat, replace the whole structure and start over again.
541 # For nested repeats, as soon as we encounter another starting repeat bar,
542 # treat that one first, and start over for the outer repeat.
543 while repeat_replaced and i < 100:
545 repeat_start = -1 # position of repeat start / end
546 repeat_end = -1 # position of repeat start / end
548 ending_start = -1 # position of current ending start
549 endings = [] # list of already finished endings
551 last = len (music_list) - 1
552 repeat_replaced = False
554 while pos < len (music_list) and not repeat_replaced:
556 repeat_finished = False
557 if isinstance (e, RepeatMarker):
558 if not repeat_times and e.times:
559 repeat_times = e.times
560 if e.direction == -1:
562 repeat_finished = True
568 elif e.direction == 1:
574 elif isinstance (e, EndingMarker):
575 if e.direction == -1:
581 elif e.direction == 1:
584 endings.append ([ending_start, pos])
587 elif not isinstance (e, musicexp.BarLine):
588 # As soon as we encounter an element when repeat start and end
589 # is set and we are not inside an alternative ending,
590 # this whole repeat structure is finished => replace it
591 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
592 repeat_finished = True
594 # Finish off all repeats without explicit ending bar (e.g. when
595 # we convert only one page of a multi-page score with repeats)
596 if pos == last and repeat_start >= 0:
597 repeat_finished = True
601 if ending_start >= 0:
602 endings.append ([ending_start, pos])
606 # We found the whole structure replace it!
607 r = musicexp.RepeatedMusic ()
608 if repeat_times <= 0:
610 r.repeat_count = repeat_times
611 # don't erase the first element for "implicit" repeats (i.e. no
612 # starting repeat bars at the very beginning)
613 start = repeat_start+1
614 if repeat_start == music_start:
616 r.set_music (music_list[start:repeat_end])
617 for (start, end) in endings:
618 s = musicexp.SequentialMusic ()
619 s.elements = music_list[start+1:end]
621 del music_list[repeat_start:final_marker+1]
622 music_list.insert (repeat_start, r)
623 repeat_replaced = True
625 # TODO: Implement repeats until the end without explicit ending bar
629 # Extract the settings for tuplets from the <notations><tuplet> and the
630 # <time-modification> elements of the note:
631 def musicxml_tuplet_to_lily (tuplet_elt, time_modification):
632 tsm = musicexp.TimeScaledMusic ()
634 if time_modification:
635 fraction = time_modification.get_fraction ()
636 tsm.numerator = fraction[0]
637 tsm.denominator = fraction[1]
640 normal_type = tuplet_elt.get_normal_type ()
641 if not normal_type and time_modification:
642 normal_type = time_modification.get_normal_type ()
643 if not normal_type and time_modification:
644 note = time_modification.get_parent ()
646 normal_type = note.get_duration_info ()
648 normal_note = musicexp.Duration ()
649 (normal_note.duration_log, normal_note.dots) = normal_type
650 tsm.normal_type = normal_note
652 actual_type = tuplet_elt.get_actual_type ()
654 actual_note = musicexp.Duration ()
655 (actual_note.duration_log, actual_note.dots) = actual_type
656 tsm.actual_type = actual_note
658 # Obtain non-default nrs of notes from the tuplet object!
659 tsm.display_numerator = tuplet_elt.get_normal_nr ()
660 tsm.display_denominator = tuplet_elt.get_actual_nr ()
663 if hasattr (tuplet_elt, 'bracket') and tuplet_elt.bracket == "no":
664 tsm.display_bracket = None
665 elif hasattr (tuplet_elt, 'line-shape') and getattr (tuplet_elt, 'line-shape') == "curved":
666 tsm.display_bracket = "curved"
668 tsm.display_bracket = "bracket"
670 display_values = {"none": None, "actual": "actual", "both": "both"}
671 if hasattr (tuplet_elt, "show-number"):
672 tsm.display_number = display_values.get (getattr (tuplet_elt, "show-number"), "actual")
674 if hasattr (tuplet_elt, "show-type"):
675 tsm.display_type = display_values.get (getattr (tuplet_elt, "show-type"), None)
680 def group_tuplets (music_list, events):
683 """Collect Musics from
684 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
692 for (ev_chord, tuplet_elt, time_modification) in events:
693 while (j < len (music_list)):
694 if music_list[j] == ev_chord:
698 if hasattr (tuplet_elt, 'number'):
699 nr = getattr (tuplet_elt, 'number')
700 if tuplet_elt.type == 'start':
701 tuplet_object = musicxml_tuplet_to_lily (tuplet_elt, time_modification)
702 tuplet_info = [j, None, tuplet_object]
703 indices.append (tuplet_info)
704 brackets[nr] = tuplet_info
705 elif tuplet_elt.type == 'stop':
706 bracket_info = brackets.get (nr, None)
708 bracket_info[1] = j # Set the ending position to j
713 for (i1, i2, tsm) in indices:
717 new_list.extend (music_list[last:i1])
718 seq = musicexp.SequentialMusic ()
720 seq.elements = music_list[i1:last]
724 new_list.append (tsm)
725 #TODO: Handle nested tuplets!!!!
727 new_list.extend (music_list[last:])
731 def musicxml_clef_to_lily (attributes):
732 change = musicexp.ClefChange ()
733 (change.type, change.position, change.octave) = attributes.get_clef_information ()
736 def musicxml_time_to_lily (attributes):
737 sig = attributes.get_time_signature ()
740 change = musicexp.TimeSignatureChange()
741 change.fractions = sig
743 time_elm = attributes.get_maybe_exist_named_child ('time')
744 if time_elm and hasattr (time_elm, 'symbol'):
745 change.style = { 'single-number': "'single-digit",
748 'normal': "'()"}.get (time_elm.symbol, "'()")
752 # TODO: Handle senza-misura measures
753 # TODO: Handle hidden time signatures (print-object="no")
754 # TODO: What shall we do if the symbol clashes with the sig? e.g. "cut"
755 # with 3/8 or "single-number" with (2+3)/8 or 3/8+2/4?
759 def musicxml_key_to_lily (attributes):
760 key_sig = attributes.get_key_signature ()
761 if not key_sig or not (isinstance (key_sig, list) or isinstance (key_sig, tuple)):
762 error_message (_ ("Unable to extract key signature!"))
765 change = musicexp.KeySignatureChange()
767 if len (key_sig) == 2 and not isinstance (key_sig[0], list):
768 # standard key signature, (fifths, mode)
769 (fifths, mode) = key_sig
772 start_pitch = musicexp.Pitch ()
773 start_pitch.octave = 0
787 start_pitch.alteration = a
789 error_message (_ ("unknown mode %s, expecting 'major' or 'minor' "
790 "or a church mode!") % mode)
792 fifth = musicexp.Pitch()
798 for x in range (fifths):
799 start_pitch = start_pitch.transposed (fifth)
800 change.tonic = start_pitch
803 # Non-standard key signature of the form [[step,alter<,octave>],...]
804 # MusicXML contains C,D,E,F,G,A,B as steps, lily uses 0-7, so convert
807 k[0] = musicxml_step_to_lily (k[0])
808 alterations.append (k)
809 change.non_standard_alterations = alterations
812 def musicxml_transpose_to_lily (attributes):
813 transpose = attributes.get_transposition ()
817 shift = musicexp.Pitch ()
818 octave_change = transpose.get_maybe_exist_named_child ('octave-change')
820 shift.octave = string.atoi (octave_change.get_text ())
821 chromatic_shift = string.atoi (transpose.get_named_child ('chromatic').get_text ())
822 chromatic_shift_normalized = chromatic_shift % 12;
823 (shift.step, shift.alteration) = [
824 (0,0), (0,1), (1,0), (2,-1), (2,0),
825 (3,0), (3,1), (4,0), (5,-1), (5,0),
826 (6,-1), (6,0)][chromatic_shift_normalized];
828 shift.octave += (chromatic_shift - chromatic_shift_normalized) / 12
830 diatonic = transpose.get_maybe_exist_named_child ('diatonic')
832 diatonic_step = string.atoi (diatonic.get_text ()) % 7
833 if diatonic_step != shift.step:
834 # We got the alter incorrect!
835 old_semitones = shift.semitones ()
836 shift.step = diatonic_step
837 new_semitones = shift.semitones ()
838 shift.alteration += old_semitones - new_semitones
840 transposition = musicexp.Transposition ()
841 transposition.pitch = musicexp.Pitch ().transposed (shift)
844 def musicxml_staff_details_to_lily (attributes):
845 details = attributes.get_maybe_exist_named_child ('staff-details')
849 ## TODO: Handle staff-type, staff-lines, staff-tuning, capo, staff-size
852 stafflines = details.get_maybe_exist_named_child ('staff-lines')
854 lines = string.atoi (stafflines.get_text ());
855 lines_event = musicexp.StaffLinesEvent (lines);
856 ret.append (lines_event);
861 def musicxml_attributes_to_lily (attrs):
864 'clef': musicxml_clef_to_lily,
865 'time': musicxml_time_to_lily,
866 'key': musicxml_key_to_lily,
867 'transpose': musicxml_transpose_to_lily,
868 'staff-details': musicxml_staff_details_to_lily,
870 for (k, func) in attr_dispatch.items ():
871 children = attrs.get_named_children (k)
874 if isinstance (ev, list):
882 def extract_display_text (el):
883 child = el.get_maybe_exist_named_child ("display-text")
885 return child.get_text ()
890 def musicxml_print_to_lily (el):
891 # TODO: Implement other print attributes
892 # <!ELEMENT print (page-layout?, system-layout?, staff-layout*,
893 # measure-layout?, measure-numbering?, part-name-display?,
894 # part-abbreviation-display?)>
896 # staff-spacing %tenths; #IMPLIED
897 # new-system %yes-no; #IMPLIED
898 # new-page %yes-no-number; #IMPLIED
899 # blank-page NMTOKEN #IMPLIED
900 # page-number CDATA #IMPLIED
903 if (hasattr (el, "new-system") and conversion_settings.convert_page_layout):
904 val = getattr (el, "new-system")
906 elts.append (musicexp.Break ("break"))
907 if (hasattr (el, "new-page") and conversion_settings.convert_page_layout):
908 val = getattr (el, "new-page")
910 elts.append (musicexp.Break ("pageBreak"))
911 child = el.get_maybe_exist_named_child ("part-name-display")
913 elts.append (musicexp.SetEvent ("Staff.instrumentName",
914 "\"%s\"" % extract_display_text (child)))
915 child = el.get_maybe_exist_named_child ("part-abbreviation-display")
917 elts.append (musicexp.SetEvent ("Staff.shortInstrumentName",
918 "\"%s\"" % extract_display_text (child)))
922 class Marker (musicexp.Music):
926 def print_ly (self, printer):
927 ly.stderr_write (_ ("Encountered unprocessed marker %s\n") % self)
929 def ly_expression (self):
931 class RepeatMarker (Marker):
933 Marker.__init__ (self)
935 class EndingMarker (Marker):
938 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
939 # and to RepeatMarker and EndingMarker objects for repeat and
940 # alternatives start/stops
941 def musicxml_barline_to_lily (barline):
942 # retval contains all possible markers in the order:
943 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
945 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
946 repeat_element = barline.get_maybe_exist_named_child ("repeat")
947 ending_element = barline.get_maybe_exist_named_child ("ending")
951 bartype = bartype_element.get_text ()
953 if repeat_element and hasattr (repeat_element, 'direction'):
954 repeat = RepeatMarker ()
955 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
957 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
958 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
960 if hasattr (repeat_element, 'times'):
962 repeat.times = int (repeat_element.times)
965 repeat.event = barline
966 if repeat.direction == -1:
971 if ending_element and hasattr (ending_element, 'type'):
972 ending = EndingMarker ()
973 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
974 ending.event = barline
975 if ending.direction == -1:
981 b = musicexp.BarLine ()
985 return retval.values ()
987 spanner_event_dict = {
988 'beam' : musicexp.BeamEvent,
989 'dashes' : musicexp.TextSpannerEvent,
990 'bracket' : musicexp.BracketSpannerEvent,
991 'glissando' : musicexp.GlissandoEvent,
992 'octave-shift' : musicexp.OctaveShiftEvent,
993 'pedal' : musicexp.PedalEvent,
994 'slide' : musicexp.GlissandoEvent,
995 'slur' : musicexp.SlurEvent,
996 'wavy-line' : musicexp.TrillSpanEvent,
997 'wedge' : musicexp.HairpinEvent
999 spanner_type_dict = {
1013 def musicxml_spanner_to_lily_event (mxl_event):
1016 name = mxl_event.get_name()
1017 func = spanner_event_dict.get (name)
1021 error_message (_ ('unknown span event %s') % mxl_event)
1024 type = mxl_event.get_type ()
1025 span_direction = spanner_type_dict.get (type)
1026 # really check for None, because some types will be translated to 0, which
1027 # would otherwise also lead to the unknown span warning
1028 if span_direction != None:
1029 ev.span_direction = span_direction
1031 error_message (_ ('unknown span type %s for %s') % (type, name))
1033 ev.set_span_type (type)
1034 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
1036 # assign the size, which is used for octave-shift, etc.
1037 ev.size = mxl_event.get_size ()
1041 def musicxml_direction_to_indicator (direction):
1042 return { "above": 1, "upright": 1, "up": 1, "below": -1, "downright": -1, "down": -1, "inverted": -1 }.get (direction, 0)
1044 def musicxml_fermata_to_lily_event (mxl_event):
1045 ev = musicexp.ArticulationEvent ()
1046 txt = mxl_event.get_text ()
1047 # The contents of the element defined the shape, possible are normal, angled and square
1048 ev.type = { "angled": "shortfermata", "square": "longfermata" }.get (txt, "fermata")
1049 if hasattr (mxl_event, 'type'):
1050 dir = musicxml_direction_to_indicator (mxl_event.type)
1051 if dir and options.convert_directions:
1052 ev.force_direction = dir
1055 def musicxml_arpeggiate_to_lily_event (mxl_event):
1056 ev = musicexp.ArpeggioEvent ()
1057 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1060 def musicxml_nonarpeggiate_to_lily_event (mxl_event):
1061 ev = musicexp.ArpeggioEvent ()
1062 ev.non_arpeggiate = True
1063 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1066 def musicxml_tremolo_to_lily_event (mxl_event):
1067 ev = musicexp.TremoloEvent ()
1068 txt = mxl_event.get_text ()
1075 def musicxml_falloff_to_lily_event (mxl_event):
1076 ev = musicexp.BendEvent ()
1080 def musicxml_doit_to_lily_event (mxl_event):
1081 ev = musicexp.BendEvent ()
1085 def musicxml_bend_to_lily_event (mxl_event):
1086 ev = musicexp.BendEvent ()
1087 ev.alter = mxl_event.bend_alter ()
1090 def musicxml_caesura_to_lily_event (mxl_event):
1091 ev = musicexp.MarkupEvent ()
1092 # FIXME: default to straight or curved caesura?
1093 ev.contents = "\\musicglyph #\"scripts.caesura.straight\""
1094 ev.force_direction = 1
1097 def musicxml_fingering_event (mxl_event):
1098 ev = musicexp.ShortArticulationEvent ()
1099 ev.type = mxl_event.get_text ()
1102 def musicxml_string_event (mxl_event):
1103 ev = musicexp.NoDirectionArticulationEvent ()
1104 ev.type = mxl_event.get_text ()
1107 def musicxml_accidental_mark (mxl_event):
1108 ev = musicexp.MarkupEvent ()
1109 contents = { "sharp": "\\sharp",
1110 "natural": "\\natural",
1112 "double-sharp": "\\doublesharp",
1113 "sharp-sharp": "\\sharp\\sharp",
1114 "flat-flat": "\\flat\\flat",
1115 "flat-flat": "\\doubleflat",
1116 "natural-sharp": "\\natural\\sharp",
1117 "natural-flat": "\\natural\\flat",
1118 "quarter-flat": "\\semiflat",
1119 "quarter-sharp": "\\semisharp",
1120 "three-quarters-flat": "\\sesquiflat",
1121 "three-quarters-sharp": "\\sesquisharp",
1122 }.get (mxl_event.get_text ())
1124 ev.contents = contents
1129 # translate articulations, ornaments and other notations into ArticulationEvents
1131 # -) string (ArticulationEvent with that name)
1132 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
1133 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
1134 # TODO: Some translations are missing!
1135 articulations_dict = {
1136 "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
1137 "accidental-mark": musicxml_accidental_mark,
1138 "bend": musicxml_bend_to_lily_event,
1139 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
1140 "caesura": musicxml_caesura_to_lily_event,
1141 #"delayed-turn": "?",
1142 "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
1143 "doit": musicxml_doit_to_lily_event,
1144 #"double-tongue": "?",
1145 "down-bow": "downbow",
1146 "falloff": musicxml_falloff_to_lily_event,
1147 "fingering": musicxml_fingering_event,
1148 #"fingernails": "?",
1151 "harmonic": "flageolet",
1153 "inverted-mordent": "prall",
1154 "inverted-turn": "reverseturn",
1155 "mordent": "mordent",
1156 "open-string": "open",
1163 "snap-pizzicato": "snappizzicato",
1165 "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
1166 "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
1167 "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
1169 "string": musicxml_string_event,
1170 "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
1172 "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
1173 "thumb-position": "thumb",
1176 "tremolo": musicxml_tremolo_to_lily_event,
1177 "trill-mark": "trill",
1178 #"triple-tongue": "?",
1183 articulation_spanners = [ "wavy-line" ]
1185 def musicxml_articulation_to_lily_event (mxl_event):
1186 # wavy-line elements are treated as trill spanners, not as articulation ornaments
1187 if mxl_event.get_name () in articulation_spanners:
1188 return musicxml_spanner_to_lily_event (mxl_event)
1190 tmp_tp = articulations_dict.get (mxl_event.get_name ())
1194 if isinstance (tmp_tp, str):
1195 ev = musicexp.ArticulationEvent ()
1197 elif isinstance (tmp_tp, tuple):
1201 ev = tmp_tp (mxl_event)
1203 # Some articulations use the type attribute, other the placement...
1205 if hasattr (mxl_event, 'type') and options.convert_directions:
1206 dir = musicxml_direction_to_indicator (mxl_event.type)
1207 if hasattr (mxl_event, 'placement') and options.convert_directions:
1208 dir = musicxml_direction_to_indicator (mxl_event.placement)
1210 ev.force_direction = dir
1215 def musicxml_dynamics_to_lily_event (dynentry):
1216 dynamics_available = (
1217 "ppppp", "pppp", "ppp", "pp", "p", "mp", "mf",
1218 "f", "ff", "fff", "ffff", "fp", "sf", "sff", "sp", "spp", "sfz", "rfz" )
1219 dynamicsname = dynentry.get_name ()
1220 if dynamicsname == "other-dynamics":
1221 dynamicsname = dynentry.get_text ()
1222 if not dynamicsname or dynamicsname=="#text":
1225 if not dynamicsname in dynamics_available:
1226 # Get rid of - in tag names (illegal in ly tags!)
1227 dynamicstext = dynamicsname
1228 dynamicsname = string.replace (dynamicsname, "-", "")
1229 additional_definitions[dynamicsname] = dynamicsname + \
1230 " = #(make-dynamic-script \"" + dynamicstext + "\")"
1231 needed_additional_definitions.append (dynamicsname)
1232 event = musicexp.DynamicsEvent ()
1233 event.type = dynamicsname
1236 # Convert single-color two-byte strings to numbers 0.0 - 1.0
1237 def hexcolorval_to_nr (hex_val):
1239 v = int (hex_val, 16)
1246 def hex_to_color (hex_val):
1247 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)
1249 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
1253 def musicxml_words_to_lily_event (words):
1254 event = musicexp.TextEvent ()
1255 text = words.get_text ()
1256 text = re.sub ('^ *\n? *', '', text)
1257 text = re.sub (' *\n? *$', '', text)
1260 if hasattr (words, 'default-y') and options.convert_directions:
1261 offset = getattr (words, 'default-y')
1263 off = string.atoi (offset)
1265 event.force_direction = 1
1267 event.force_direction = -1
1269 event.force_direction = 0
1271 if hasattr (words, 'font-weight'):
1272 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
1274 event.markup += font_weight
1276 if hasattr (words, 'font-size'):
1277 size = getattr (words, 'font-size')
1279 "xx-small": '\\teeny',
1280 "x-small": '\\tiny',
1284 "x-large": '\\huge',
1285 "xx-large": '\\larger\\huge'
1288 event.markup += font_size
1290 if hasattr (words, 'color'):
1291 color = getattr (words, 'color')
1292 rgb = hex_to_color (color)
1294 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
1296 if hasattr (words, 'font-style'):
1297 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
1299 event.markup += font_style
1301 # TODO: How should I best convert the font-family attribute?
1303 # TODO: How can I represent the underline, overline and line-through
1304 # attributes in LilyPond? Values of these attributes indicate
1305 # the number of lines
1310 # convert accordion-registration to lilypond.
1311 # Since lilypond does not have any built-in commands, we need to create
1312 # the markup commands manually and define our own variables.
1313 # Idea was taken from: http://lsr.dsi.unimi.it/LSR/Item?id=194
1314 def musicxml_accordion_to_markup (mxl_event):
1315 commandname = "accReg"
1318 high = mxl_event.get_maybe_exist_named_child ('accordion-high')
1321 command += """\\combine
1322 \\raise #2.5 \\musicglyph #\"accordion.dot\"
1324 middle = mxl_event.get_maybe_exist_named_child ('accordion-middle')
1326 # By default, use one dot (when no or invalid content is given). The
1327 # MusicXML spec is quiet about this case...
1330 txt = string.atoi (middle.get_text ())
1334 commandname += "MMM"
1335 command += """\\combine
1336 \\raise #1.5 \\musicglyph #\"accordion.dot\"
1338 \\raise #1.5 \\translate #(cons 1 0) \\musicglyph #\"accordion.dot\"
1340 \\raise #1.5 \\translate #(cons -1 0) \\musicglyph #\"accordion.dot\"
1344 command += """\\combine
1345 \\raise #1.5 \\translate #(cons 0.5 0) \\musicglyph #\"accordion.dot\"
1347 \\raise #1.5 \\translate #(cons -0.5 0) \\musicglyph #\"accordion.dot\"
1351 command += """\\combine
1352 \\raise #1.5 \\musicglyph #\"accordion.dot\"
1354 low = mxl_event.get_maybe_exist_named_child ('accordion-low')
1357 command += """\\combine
1358 \\raise #0.5 \musicglyph #\"accordion.dot\"
1361 command += "\musicglyph #\"accordion.discant\""
1362 command = "\\markup { \\normalsize %s }" % command
1363 # Define the newly built command \accReg[H][MMM][L]
1364 additional_definitions[commandname] = "%s = %s" % (commandname, command)
1365 needed_additional_definitions.append (commandname)
1366 return "\\%s" % commandname
1368 def musicxml_accordion_to_ly (mxl_event):
1369 txt = musicxml_accordion_to_markup (mxl_event)
1371 ev = musicexp.MarkEvent (txt)
1376 def musicxml_rehearsal_to_ly_mark (mxl_event):
1377 text = mxl_event.get_text ()
1380 # default is boxed rehearsal marks!
1382 if hasattr (mxl_event, 'enclosure'):
1383 encl = {"none": None, "square": "box", "circle": "circle" }.get (mxl_event.enclosure, None)
1385 text = "\\%s { %s }" % (encl, text)
1386 ev = musicexp.MarkEvent ("\\markup { %s }" % text)
1389 def musicxml_harp_pedals_to_ly (mxl_event):
1391 result = "\\harp-pedal #\""
1392 for t in mxl_event.get_named_children ('pedal-tuning'):
1393 alter = t.get_named_child ('pedal-alter')
1395 val = int (alter.get_text ().strip ())
1396 result += {1: "v", 0: "-", -1: "^"}.get (val, "")
1400 ev = musicexp.MarkupEvent ()
1401 ev.contents = result + "\""
1404 def musicxml_eyeglasses_to_ly (mxl_event):
1405 needed_additional_definitions.append ("eyeglasses")
1406 return musicexp.MarkEvent ("\\markup { \\eyeglasses }")
1408 def next_non_hash_index (lst, pos):
1410 while pos < len (lst) and isinstance (lst[pos], musicxml.Hash_text):
1414 def musicxml_metronome_to_ly (mxl_event):
1415 children = mxl_event.get_all_children ()
1420 index = next_non_hash_index (children, index)
1421 if isinstance (children[index], musicxml.BeatUnit):
1422 # first form of metronome-mark, using unit and beats/min or other unit
1423 ev = musicexp.TempoMark ()
1424 if hasattr (mxl_event, 'parentheses'):
1425 ev.set_parentheses (mxl_event.parentheses == "yes")
1427 d = musicexp.Duration ()
1428 d.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1429 index = next_non_hash_index (children, index)
1430 if isinstance (children[index], musicxml.BeatUnitDot):
1432 index = next_non_hash_index (children, index)
1433 ev.set_base_duration (d)
1434 if isinstance (children[index], musicxml.BeatUnit):
1435 # Form "note = newnote"
1436 newd = musicexp.Duration ()
1437 newd.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1438 index = next_non_hash_index (children, index)
1439 if isinstance (children[index], musicxml.BeatUnitDot):
1441 index = next_non_hash_index (children, index)
1442 ev.set_new_duration (newd)
1443 elif isinstance (children[index], musicxml.PerMinute):
1446 beats = int (children[index].get_text ())
1447 ev.set_beats_per_minute (beats)
1451 error_message (_ ("Unknown metronome mark, ignoring"))
1455 #TODO: Implement the other (more complex) way for tempo marks!
1456 error_message (_ ("Metronome marks with complex relations (<metronome-note> in MusicXML) are not yet implemented."))
1459 # translate directions into Events, possible values:
1460 # -) string (MarkEvent with that command)
1461 # -) function (function(mxl_event) needs to return a full Event-derived object
1462 # -) (class, name) (like string, only that a different class than MarkEvent is used)
1464 'accordion-registration' : musicxml_accordion_to_ly,
1465 'coda' : (musicexp.MusicGlyphMarkEvent, "coda"),
1468 'eyeglasses': musicxml_eyeglasses_to_ly,
1469 'harp-pedals' : musicxml_harp_pedals_to_ly,
1471 'metronome' : musicxml_metronome_to_ly,
1472 'rehearsal' : musicxml_rehearsal_to_ly_mark,
1473 # 'scordatura' : ???
1474 'segno' : (musicexp.MusicGlyphMarkEvent, "segno"),
1475 'words' : musicxml_words_to_lily_event,
1477 directions_spanners = [ 'octave-shift', 'pedal', 'wedge', 'dashes', 'bracket' ]
1479 def musicxml_direction_to_lily (n):
1480 # TODO: Handle the <staff> element!
1482 # placement applies to all children!
1484 if hasattr (n, 'placement') and options.convert_directions:
1485 dir = musicxml_direction_to_indicator (n.placement)
1486 dirtype_children = []
1487 # TODO: The direction-type is used for grouping (e.g. dynamics with text),
1488 # so we can't simply flatten them out!
1489 for dt in n.get_typed_children (musicxml.DirType):
1490 dirtype_children += dt.get_all_children ()
1492 for entry in dirtype_children:
1493 # backets, dashes, octave shifts. pedal marks, hairpins etc. are spanners:
1494 if entry.get_name() in directions_spanners:
1495 event = musicxml_spanner_to_lily_event (entry)
1500 # now treat all the "simple" ones, that can be translated using the dict
1502 tmp_tp = directions_dict.get (entry.get_name (), None)
1503 if isinstance (tmp_tp, str): # string means MarkEvent
1504 ev = musicexp.MarkEvent (tmp_tp)
1505 elif isinstance (tmp_tp, tuple): # tuple means (EventClass, "text")
1506 ev = tmp_tp[0] (tmp_tp[1])
1510 # TODO: set the correct direction! Unfortunately, \mark in ly does
1511 # not seem to support directions!
1512 ev.force_direction = dir
1516 if entry.get_name () == "dynamics":
1517 for dynentry in entry.get_all_children ():
1518 ev = musicxml_dynamics_to_lily_event (dynentry)
1524 def musicxml_frame_to_lily_event (frame):
1525 ev = musicexp.FretEvent ()
1526 ev.strings = frame.get_strings ()
1527 ev.frets = frame.get_frets ()
1528 #offset = frame.get_first_fret () - 1
1530 for fn in frame.get_named_children ('frame-note'):
1531 fret = fn.get_fret ()
1534 el = [ fn.get_string (), fret ]
1535 fingering = fn.get_fingering ()
1537 el.append (fingering)
1538 ev.elements.append (el)
1541 barre[0] = el[0] # start string
1542 barre[2] = el[1] # fret
1544 barre[1] = el[0] # end string
1549 def musicxml_harmony_to_lily (n):
1551 for f in n.get_named_children ('frame'):
1552 ev = musicxml_frame_to_lily_event (f)
1558 notehead_styles_dict = {
1560 'triangle': '\'triangle',
1561 'diamond': '\'diamond',
1562 'square': '\'la', # TODO: Proper squared note head
1563 'cross': None, # TODO: + shaped note head
1565 'circle-x': '\'xcircle',
1566 'inverted triangle': None, # TODO: Implement
1567 'arrow down': None, # TODO: Implement
1568 'arrow up': None, # TODO: Implement
1569 'slashed': None, # TODO: Implement
1570 'back slashed': None, # TODO: Implement
1572 'cluster': None, # TODO: Implement
1583 def musicxml_notehead_to_lily (nh):
1587 style = notehead_styles_dict.get (nh.get_text ().strip (), None)
1588 style_elm = musicexp.NotestyleEvent ()
1590 style_elm.style = style
1591 if hasattr (nh, 'filled'):
1592 style_elm.filled = (getattr (nh, 'filled') == "yes")
1593 if style_elm.style or (style_elm.filled != None):
1594 styles.append (style_elm)
1597 if hasattr (nh, 'parentheses') and (nh.parentheses == "yes"):
1598 styles.append (musicexp.ParenthesizeEvent ())
1602 def musicxml_chordpitch_to_lily (mxl_cpitch):
1603 r = musicexp.ChordPitch ()
1604 r.alteration = mxl_cpitch.get_alteration ()
1605 r.step = musicxml_step_to_lily (mxl_cpitch.get_step ())
1611 'augmented': 'aug5',
1612 'diminished': 'dim5',
1615 'dominant-seventh': '7',
1616 'major-seventh': 'maj7',
1617 'minor-seventh': 'm7',
1618 'diminished-seventh': 'dim7',
1619 'augmented-seventh': 'aug7',
1620 'half-diminished': 'dim5m7',
1621 'major-minor': 'maj7m5',
1624 'minor-sixth': 'm6',
1626 'dominant-ninth': '9',
1627 'major-ninth': 'maj9',
1628 'minor-ninth': 'm9',
1629 # 11ths (usually as the basis for alteration):
1630 'dominant-11th': '11',
1631 'major-11th': 'maj11',
1632 'minor-11th': 'm11',
1633 # 13ths (usually as the basis for alteration):
1634 'dominant-13th': '13.11',
1635 'major-13th': 'maj13.11',
1636 'minor-13th': 'm13',
1638 'suspended-second': 'sus2',
1639 'suspended-fourth': 'sus4',
1640 # Functional sixths:
1642 #'Neapolitan': '???',
1647 #'pedal': '???',(pedal-point bass)
1654 def musicxml_chordkind_to_lily (kind):
1655 res = chordkind_dict.get (kind, None)
1656 # Check for None, since a major chord is converted to ''
1658 error_message (_ ("Unable to convert chord type %s to lilypond.") % kind)
1661 def musicxml_harmony_to_lily_chordname (n):
1663 root = n.get_maybe_exist_named_child ('root')
1665 ev = musicexp.ChordNameEvent ()
1666 ev.root = musicxml_chordpitch_to_lily (root)
1667 kind = n.get_maybe_exist_named_child ('kind')
1669 ev.kind = musicxml_chordkind_to_lily (kind.get_text ())
1672 bass = n.get_maybe_exist_named_child ('bass')
1674 ev.bass = musicxml_chordpitch_to_lily (bass)
1675 inversion = n.get_maybe_exist_named_child ('inversion')
1677 # TODO: LilyPond does not support inversions, does it?
1679 # Mail from Carl Sorensen on lilypond-devel, June 11, 2008:
1680 # 4. LilyPond supports the first inversion in the form of added
1681 # bass notes. So the first inversion of C major would be c:/g.
1682 # To get the second inversion of C major, you would need to do
1683 # e:6-3-^5 or e:m6-^5. However, both of these techniques
1684 # require you to know the chord and calculate either the fifth
1685 # pitch (for the first inversion) or the third pitch (for the
1686 # second inversion) so they may not be helpful for musicxml2ly.
1687 inversion_count = string.atoi (inversion.get_text ())
1688 if inversion_count == 1:
1689 # TODO: Calculate the bass note for the inversion...
1692 for deg in n.get_named_children ('degree'):
1693 d = musicexp.ChordModification ()
1694 d.type = deg.get_type ()
1695 d.step = deg.get_value ()
1696 d.alteration = deg.get_alter ()
1697 ev.add_modification (d)
1698 #TODO: convert the user-symbols attribute:
1699 #major: a triangle, like Unicode 25B3
1700 #minor: -, like Unicode 002D
1701 #augmented: +, like Unicode 002B
1702 #diminished: (degree), like Unicode 00B0
1703 #half-diminished: (o with slash), like Unicode 00F8
1709 def musicxml_figured_bass_note_to_lily (n):
1710 res = musicexp.FiguredBassNote ()
1711 suffix_dict = { 'sharp' : "+",
1714 'double-sharp' : "++",
1716 'sharp-sharp' : "++",
1718 prefix = n.get_maybe_exist_named_child ('prefix')
1720 res.set_prefix (suffix_dict.get (prefix.get_text (), ""))
1721 fnumber = n.get_maybe_exist_named_child ('figure-number')
1723 res.set_number (fnumber.get_text ())
1724 suffix = n.get_maybe_exist_named_child ('suffix')
1726 res.set_suffix (suffix_dict.get (suffix.get_text (), ""))
1727 if n.get_maybe_exist_named_child ('extend'):
1728 # TODO: Implement extender lines (unfortunately, in lilypond you have
1729 # to use \set useBassFigureExtenders = ##t, which turns them on
1730 # globally, while MusicXML has a property for each note...
1731 # I'm not sure there is a proper way to implement this cleanly
1738 def musicxml_figured_bass_to_lily (n):
1739 if not isinstance (n, musicxml.FiguredBass):
1741 res = musicexp.FiguredBassEvent ()
1742 for i in n.get_named_children ('figure'):
1743 note = musicxml_figured_bass_note_to_lily (i)
1746 dur = n.get_maybe_exist_named_child ('duration')
1748 # apply the duration to res
1749 length = Rational(int(dur.get_text()), n._divisions)*Rational(1,4)
1750 res.set_real_duration (length)
1751 duration = rational_to_lily_duration (length)
1753 res.set_duration (duration)
1754 if hasattr (n, 'parentheses') and n.parentheses == "yes":
1755 res.set_parentheses (True)
1758 instrument_drumtype_dict = {
1759 'Acoustic Snare Drum': 'acousticsnare',
1760 'Side Stick': 'sidestick',
1761 'Open Triangle': 'opentriangle',
1762 'Mute Triangle': 'mutetriangle',
1763 'Tambourine': 'tambourine',
1764 'Bass Drum': 'bassdrum',
1767 def musicxml_note_to_lily_main_event (n):
1772 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1774 pitch = musicxml_pitch_to_lily (mxl_pitch)
1775 event = musicexp.NoteEvent ()
1778 acc = n.get_maybe_exist_named_child ('accidental')
1780 # let's not force accs everywhere.
1781 event.cautionary = acc.cautionary
1782 # TODO: Handle editorial accidentals
1783 # TODO: Handle the level-display setting for displaying brackets/parentheses
1785 elif n.get_maybe_exist_typed_child (musicxml.Unpitched):
1786 # Unpitched elements have display-step and can also have
1788 unpitched = n.get_maybe_exist_typed_child (musicxml.Unpitched)
1789 event = musicexp.NoteEvent ()
1790 event.pitch = musicxml_unpitched_to_lily (unpitched)
1792 elif n.get_maybe_exist_typed_child (musicxml.Rest):
1793 # rests can have display-octave and display-step, which are
1794 # treated like an ordinary note pitch
1795 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1796 event = musicexp.RestEvent ()
1797 if options.convert_rest_positions:
1798 pitch = musicxml_restdisplay_to_lily (rest)
1801 elif n.instrument_name:
1802 event = musicexp.NoteEvent ()
1803 drum_type = instrument_drumtype_dict.get (n.instrument_name)
1805 event.drum_type = drum_type
1807 n.message (_ ("drum %s type unknown, please add to instrument_drumtype_dict") % n.instrument_name)
1808 event.drum_type = 'acousticsnare'
1811 n.message (_ ("cannot find suitable event"))
1814 event.duration = musicxml_duration_to_lily (n)
1816 noteheads = n.get_named_children ('notehead')
1817 for nh in noteheads:
1818 styles = musicxml_notehead_to_lily (nh)
1820 event.add_associated_event (s)
1824 def musicxml_lyrics_to_text (lyrics):
1825 # TODO: Implement text styles for lyrics syllables
1829 for e in lyrics.get_all_children ():
1830 if isinstance (e, musicxml.Syllabic):
1831 continued = e.continued ()
1832 elif isinstance (e, musicxml.Text):
1833 # We need to convert soft hyphens to -, otherwise the ascii codec as well
1834 # as lilypond will barf on that character
1835 text += string.replace( e.get_text(), u'\xad', '-' )
1836 elif isinstance (e, musicxml.Elision):
1841 elif isinstance (e, musicxml.Extend):
1846 if text == "-" and continued:
1848 elif text == "_" and extended:
1850 elif continued and text:
1851 return musicxml.escape_ly_output_string (text) + " --"
1854 elif extended and text:
1855 return musicxml.escape_ly_output_string (text) + " __"
1859 return musicxml.escape_ly_output_string (text)
1865 def __init__ (self, here, dest):
1869 class LilyPondVoiceBuilder:
1870 def __init__ (self):
1872 self.pending_dynamics = []
1873 self.end_moment = Rational (0)
1874 self.begin_moment = Rational (0)
1875 self.pending_multibar = Rational (0)
1876 self.ignore_skips = False
1877 self.has_relevant_elements = False
1878 self.measure_length = Rational (4, 4)
1880 def _insert_multibar (self):
1881 layout_information.set_context_item ('Score', 'skipBars = ##t')
1882 r = musicexp.MultiMeasureRest ()
1883 lenfrac = self.measure_length
1884 r.duration = rational_to_lily_duration (lenfrac)
1885 r.duration.factor *= self.pending_multibar / lenfrac
1886 self.elements.append (r)
1887 self.begin_moment = self.end_moment
1888 self.end_moment = self.begin_moment + self.pending_multibar
1889 self.pending_multibar = Rational (0)
1891 def set_measure_length (self, mlen):
1892 if (mlen != self.measure_length) and self.pending_multibar:
1893 self._insert_multibar ()
1894 self.measure_length = mlen
1896 def add_multibar_rest (self, duration):
1897 self.pending_multibar += duration
1899 def set_duration (self, duration):
1900 self.end_moment = self.begin_moment + duration
1901 def current_duration (self):
1902 return self.end_moment - self.begin_moment
1904 def add_music (self, music, duration, relevant = True):
1905 assert isinstance (music, musicexp.Music)
1906 if self.pending_multibar > Rational (0):
1907 self._insert_multibar ()
1909 self.has_relevant_elements = self.has_relevant_elements or relevant
1910 self.elements.append (music)
1911 self.begin_moment = self.end_moment
1912 self.set_duration (duration)
1914 # Insert all pending dynamics right after the note/rest:
1915 if isinstance (music, musicexp.ChordEvent) and self.pending_dynamics:
1916 for d in self.pending_dynamics:
1918 self.pending_dynamics = []
1920 # Insert some music command that does not affect the position in the measure
1921 def add_command (self, command, relevant = True):
1922 assert isinstance (command, musicexp.Music)
1923 if self.pending_multibar > Rational (0):
1924 self._insert_multibar ()
1925 self.has_relevant_elements = self.has_relevant_elements or relevant
1926 self.elements.append (command)
1927 def add_barline (self, barline, relevant = False):
1928 # Insert only if we don't have a barline already
1929 # TODO: Implement proper merging of default barline and custom bar line
1930 has_relevant = self.has_relevant_elements
1931 if (not (self.elements) or
1932 not (isinstance (self.elements[-1], musicexp.BarLine)) or
1933 (self.pending_multibar > Rational (0))):
1934 self.add_music (barline, Rational (0))
1935 self.has_relevant_elements = has_relevant or relevant
1936 def add_partial (self, command):
1937 self.ignore_skips = True
1938 # insert the partial, but restore relevant_elements (partial is not relevant)
1939 relevant = self.has_relevant_elements
1940 self.add_command (command)
1941 self.has_relevant_elements = relevant
1943 def add_dynamics (self, dynamic):
1944 # store the dynamic item(s) until we encounter the next note/rest:
1945 self.pending_dynamics.append (dynamic)
1947 def add_bar_check (self, number):
1948 # re/store has_relevant_elements, so that a barline alone does not
1949 # trigger output for figured bass, chord names
1950 b = musicexp.BarLine ()
1951 b.bar_number = number
1952 self.add_barline (b)
1954 def jumpto (self, moment):
1955 current_end = self.end_moment + self.pending_multibar
1956 diff = moment - current_end
1958 if diff < Rational (0):
1959 error_message (_ ('Negative skip %s (from position %s to %s)') %
1960 (diff, current_end, moment))
1963 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
1964 skip = musicexp.SkipEvent()
1966 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)
1968 # TODO: Use the time signature for skips, too. Problem: The skip
1969 # might not start at a measure boundary!
1970 if duration_log > 0: # denominator is a power of 2...
1971 if diff.numerator () == 3:
1975 duration_factor = Rational (diff.numerator ())
1977 # for skips of a whole or more, simply use s1*factor
1979 duration_factor = diff
1980 skip.duration.duration_log = duration_log
1981 skip.duration.factor = duration_factor
1982 skip.duration.dots = duration_dots
1984 evc = musicexp.ChordEvent ()
1985 evc.elements.append (skip)
1986 self.add_music (evc, diff, False)
1988 if diff > Rational (0) and moment == 0:
1989 self.ignore_skips = False
1991 def last_event_chord (self, starting_at):
1995 # if the position matches, find the last ChordEvent, do not cross a bar line!
1996 at = len( self.elements ) - 1
1998 not isinstance (self.elements[at], musicexp.ChordEvent) and
1999 not isinstance (self.elements[at], musicexp.BarLine)):
2004 and isinstance (self.elements[at], musicexp.ChordEvent)
2005 and self.begin_moment == starting_at):
2006 value = self.elements[at]
2008 self.jumpto (starting_at)
2012 def correct_negative_skip (self, goto):
2013 self.end_moment = goto
2014 self.begin_moment = goto
2015 evc = musicexp.ChordEvent ()
2016 self.elements.append (evc)
2020 def __init__ (self):
2021 self.voicename = None
2022 self.voicedata = None
2023 self.ly_voice = None
2024 self.figured_bass = None
2025 self.chordnames = None
2026 self.lyrics_dict = {}
2027 self.lyrics_order = []
2029 def measure_length_from_attributes (attr, current_measure_length):
2030 len = attr.get_measure_length ()
2032 len = current_measure_length
2035 def musicxml_voice_to_lily_voice (voice):
2039 return_value = VoiceData ()
2040 return_value.voicedata = voice
2042 # First pitch needed for relative mode (if selected in command-line options)
2045 # Needed for melismata detection (ignore lyrics on those notes!):
2050 ignore_lyrics = False
2052 current_staff = None
2054 pending_figured_bass = []
2055 pending_chordnames = []
2057 # Make sure that the keys in the dict don't get reordered, since
2058 # we need the correct ordering of the lyrics stanzas! By default,
2059 # a dict will reorder its keys
2060 return_value.lyrics_order = voice.get_lyrics_numbers ()
2061 for k in return_value.lyrics_order:
2064 voice_builder = LilyPondVoiceBuilder ()
2065 figured_bass_builder = LilyPondVoiceBuilder ()
2066 chordnames_builder = LilyPondVoiceBuilder ()
2067 current_measure_length = Rational (4, 4)
2068 voice_builder.set_measure_length (current_measure_length)
2070 for n in voice._elements:
2072 if n.get_name () == 'forward':
2074 staff = n.get_maybe_exist_named_child ('staff')
2076 staff = staff.get_text ()
2077 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
2078 voice_builder.add_command (musicexp.StaffChange (staff))
2079 current_staff = staff
2081 if isinstance (n, musicxml.Partial) and n.partial > 0:
2082 a = musicxml_partial_to_lily (n.partial)
2084 voice_builder.add_partial (a)
2085 figured_bass_builder.add_partial (a)
2086 chordnames_builder.add_partial (a)
2089 is_chord = n.get_maybe_exist_named_child ('chord')
2090 is_after_grace = (isinstance (n, musicxml.Note) and n.is_after_grace ());
2091 if not is_chord and not is_after_grace:
2093 voice_builder.jumpto (n._when)
2094 figured_bass_builder.jumpto (n._when)
2095 chordnames_builder.jumpto (n._when)
2096 except NegativeSkip, neg:
2097 voice_builder.correct_negative_skip (n._when)
2098 figured_bass_builder.correct_negative_skip (n._when)
2099 chordnames_builder.correct_negative_skip (n._when)
2100 n.message (_ ("Negative skip found: from %s to %s, difference is %s") % (neg.here, neg.dest, neg.dest - neg.here))
2102 if isinstance (n, musicxml.Barline):
2103 barlines = musicxml_barline_to_lily (n)
2105 if isinstance (a, musicexp.BarLine):
2106 voice_builder.add_barline (a)
2107 figured_bass_builder.add_barline (a, False)
2108 chordnames_builder.add_barline (a, False)
2109 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
2110 voice_builder.add_command (a)
2111 figured_bass_builder.add_barline (a, False)
2112 chordnames_builder.add_barline (a, False)
2116 if isinstance (n, musicxml.Print):
2117 for a in musicxml_print_to_lily (n):
2118 voice_builder.add_command (a, False)
2121 # Continue any multimeasure-rests before trying to add bar checks!
2122 # Don't handle new MM rests yet, because for them we want bar checks!
2123 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
2124 if (rest and rest.is_whole_measure ()
2125 and voice_builder.pending_multibar > Rational (0)):
2126 voice_builder.add_multibar_rest (n._duration)
2130 # print a bar check at the beginning of each measure!
2131 if n.is_first () and n._measure_position == Rational (0) and n != voice._elements[0]:
2133 num = int (n.get_parent ().number)
2137 voice_builder.add_bar_check (num)
2138 figured_bass_builder.add_bar_check (num)
2139 chordnames_builder.add_bar_check (num)
2141 # Start any new multimeasure rests
2142 if (rest and rest.is_whole_measure ()):
2143 voice_builder.add_multibar_rest (n._duration)
2147 if isinstance (n, musicxml.Direction):
2148 for a in musicxml_direction_to_lily (n):
2149 if a.wait_for_note ():
2150 voice_builder.add_dynamics (a)
2152 voice_builder.add_command (a)
2155 if isinstance (n, musicxml.Harmony):
2156 for a in musicxml_harmony_to_lily (n):
2157 if a.wait_for_note ():
2158 voice_builder.add_dynamics (a)
2160 voice_builder.add_command (a)
2161 for a in musicxml_harmony_to_lily_chordname (n):
2162 pending_chordnames.append (a)
2165 if isinstance (n, musicxml.FiguredBass):
2166 a = musicxml_figured_bass_to_lily (n)
2168 pending_figured_bass.append (a)
2171 if isinstance (n, musicxml.Attributes):
2172 for a in musicxml_attributes_to_lily (n):
2173 voice_builder.add_command (a)
2174 measure_length = measure_length_from_attributes (n, current_measure_length)
2175 if current_measure_length != measure_length:
2176 current_measure_length = measure_length
2177 voice_builder.set_measure_length (current_measure_length)
2180 if not n.__class__.__name__ == 'Note':
2181 n.message (_ ('unexpected %s; expected %s or %s or %s') % (n, 'Note', 'Attributes', 'Barline'))
2184 main_event = musicxml_note_to_lily_main_event (n)
2185 if main_event and not first_pitch:
2186 first_pitch = main_event.pitch
2187 # ignore lyrics for notes inside a slur, tie, chord or beam
2188 ignore_lyrics = inside_slur or is_tied or is_chord or is_beamed
2190 if main_event and hasattr (main_event, 'drum_type') and main_event.drum_type:
2191 modes_found['drummode'] = True
2193 ev_chord = voice_builder.last_event_chord (n._when)
2195 ev_chord = musicexp.ChordEvent()
2196 voice_builder.add_music (ev_chord, n._duration)
2199 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
2201 is_after_grace = ev_chord.has_elements () or n.is_after_grace ();
2202 is_chord = n.get_maybe_exist_typed_child (musicxml.Chord)
2206 # after-graces and other graces use different lists; Depending on
2207 # whether we have a chord or not, obtain either a new ChordEvent or
2208 # the previous one to create a chord
2210 if ev_chord.after_grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2211 grace_chord = ev_chord.after_grace_elements.get_last_event_chord ()
2213 grace_chord = musicexp.ChordEvent ()
2214 ev_chord.append_after_grace (grace_chord)
2216 if ev_chord.grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2217 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
2219 grace_chord = musicexp.ChordEvent ()
2220 ev_chord.append_grace (grace_chord)
2222 if hasattr (grace, 'slash') and not is_after_grace:
2223 # TODO: use grace_type = "appoggiatura" for slurred grace notes
2224 if grace.slash == "yes":
2225 ev_chord.grace_type = "acciaccatura"
2226 # now that we have inserted the chord into the grace music, insert
2227 # everything into that chord instead of the ev_chord
2228 ev_chord = grace_chord
2229 ev_chord.append (main_event)
2230 ignore_lyrics = True
2232 ev_chord.append (main_event)
2233 # When a note/chord has grace notes (duration==0), the duration of the
2234 # event chord is not yet known, but the event chord was already added
2235 # with duration 0. The following correct this when we hit the real note!
2236 if voice_builder.current_duration () == 0 and n._duration > 0:
2237 voice_builder.set_duration (n._duration)
2239 # if we have a figured bass, set its voice builder to the correct position
2240 # and insert the pending figures
2241 if pending_figured_bass:
2243 figured_bass_builder.jumpto (n._when)
2244 except NegativeSkip, neg:
2246 for fb in pending_figured_bass:
2247 # if a duration is given, use that, otherwise the one of the note
2248 dur = fb.real_duration
2250 dur = ev_chord.get_length ()
2252 fb.duration = ev_chord.get_duration ()
2253 figured_bass_builder.add_music (fb, dur)
2254 pending_figured_bass = []
2256 if pending_chordnames:
2258 chordnames_builder.jumpto (n._when)
2259 except NegativeSkip, neg:
2261 for cn in pending_chordnames:
2262 # Assign the duration of the EventChord
2263 cn.duration = ev_chord.get_duration ()
2264 chordnames_builder.add_music (cn, ev_chord.get_length ())
2265 pending_chordnames = []
2267 notations_children = n.get_typed_children (musicxml.Notations)
2271 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
2272 # +tied | +slur | +tuplet | glissando | slide |
2273 # ornaments | technical | articulations | dynamics |
2274 # +fermata | arpeggiate | non-arpeggiate |
2275 # accidental-mark | other-notation
2276 for notations in notations_children:
2277 for tuplet_event in notations.get_tuplets():
2278 time_mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
2279 tuplet_events.append ((ev_chord, tuplet_event, time_mod))
2281 # First, close all open slurs, only then start any new slur
2282 # TODO: Record the number of the open slur to dtermine the correct
2284 endslurs = [s for s in notations.get_named_children ('slur')
2285 if s.get_type () in ('stop')]
2286 if endslurs and not inside_slur:
2287 endslurs[0].message (_ ('Encountered closing slur, but no slur is open'))
2289 if len (endslurs) > 1:
2290 endslurs[0].message (_ ('Cannot have two simultaneous (closing) slurs'))
2291 # record the slur status for the next note in the loop
2293 lily_ev = musicxml_spanner_to_lily_event (endslurs[0])
2294 ev_chord.append (lily_ev)
2296 startslurs = [s for s in notations.get_named_children ('slur')
2297 if s.get_type () in ('start')]
2298 if startslurs and inside_slur:
2299 startslurs[0].message (_ ('Cannot have a slur inside another slur'))
2301 if len (startslurs) > 1:
2302 startslurs[0].message (_ ('Cannot have two simultaneous slurs'))
2303 # record the slur status for the next note in the loop
2305 lily_ev = musicxml_spanner_to_lily_event (startslurs[0])
2306 ev_chord.append (lily_ev)
2310 mxl_tie = notations.get_tie ()
2311 if mxl_tie and mxl_tie.type == 'start':
2312 ev_chord.append (musicexp.TieEvent ())
2318 fermatas = notations.get_named_children ('fermata')
2320 ev = musicxml_fermata_to_lily_event (a)
2322 ev_chord.append (ev)
2324 arpeggiate = notations.get_named_children ('arpeggiate')
2325 for a in arpeggiate:
2326 ev = musicxml_arpeggiate_to_lily_event (a)
2328 ev_chord.append (ev)
2330 arpeggiate = notations.get_named_children ('non-arpeggiate')
2331 for a in arpeggiate:
2332 ev = musicxml_nonarpeggiate_to_lily_event (a)
2334 ev_chord.append (ev)
2336 glissandos = notations.get_named_children ('glissando')
2337 glissandos += notations.get_named_children ('slide')
2338 for a in glissandos:
2339 ev = musicxml_spanner_to_lily_event (a)
2341 ev_chord.append (ev)
2343 # accidental-marks are direct children of <notation>!
2344 for a in notations.get_named_children ('accidental-mark'):
2345 ev = musicxml_articulation_to_lily_event (a)
2347 ev_chord.append (ev)
2349 # Articulations can contain the following child elements:
2350 # accent | strong-accent | staccato | tenuto |
2351 # detached-legato | staccatissimo | spiccato |
2352 # scoop | plop | doit | falloff | breath-mark |
2353 # caesura | stress | unstress
2354 # Technical can contain the following child elements:
2355 # up-bow | down-bow | harmonic | open-string |
2356 # thumb-position | fingering | pluck | double-tongue |
2357 # triple-tongue | stopped | snap-pizzicato | fret |
2358 # string | hammer-on | pull-off | bend | tap | heel |
2359 # toe | fingernails | other-technical
2360 # Ornaments can contain the following child elements:
2361 # trill-mark | turn | delayed-turn | inverted-turn |
2362 # shake | wavy-line | mordent | inverted-mordent |
2363 # schleifer | tremolo | other-ornament, accidental-mark
2364 ornaments = notations.get_named_children ('ornaments')
2365 ornaments += notations.get_named_children ('articulations')
2366 ornaments += notations.get_named_children ('technical')
2369 for ch in a.get_all_children ():
2370 ev = musicxml_articulation_to_lily_event (ch)
2372 ev_chord.append (ev)
2374 dynamics = notations.get_named_children ('dynamics')
2376 for ch in a.get_all_children ():
2377 ev = musicxml_dynamics_to_lily_event (ch)
2379 ev_chord.append (ev)
2382 mxl_beams = [b for b in n.get_named_children ('beam')
2383 if (b.get_type () in ('begin', 'end')
2384 and b.is_primary ())]
2385 if mxl_beams and not conversion_settings.ignore_beaming:
2386 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
2388 ev_chord.append (beam_ev)
2389 if beam_ev.span_direction == -1: # beam and thus melisma starts here
2391 elif beam_ev.span_direction == 1: # beam and thus melisma ends here
2394 # Extract the lyrics
2395 if not rest and not ignore_lyrics:
2396 note_lyrics_processed = []
2397 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
2398 for l in note_lyrics_elements:
2399 if l.get_number () < 0:
2400 for k in lyrics.keys ():
2401 lyrics[k].append (musicxml_lyrics_to_text (l))
2402 note_lyrics_processed.append (k)
2404 lyrics[l.number].append(musicxml_lyrics_to_text (l))
2405 note_lyrics_processed.append (l.number)
2406 for lnr in lyrics.keys ():
2407 if not lnr in note_lyrics_processed:
2408 lyrics[lnr].append ("\skip4")
2410 # Assume that a <tie> element only lasts for one note.
2411 # This might not be correct MusicXML interpretation, but works for
2412 # most cases and fixes broken files, which have the end tag missing
2413 if is_tied and not tie_started:
2416 ## force trailing mm rests to be written out.
2417 voice_builder.add_music (musicexp.ChordEvent (), Rational (0))
2419 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
2420 ly_voice = group_repeats (ly_voice)
2422 seq_music = musicexp.SequentialMusic ()
2424 if 'drummode' in modes_found.keys ():
2425 ## \key <pitch> barfs in drummode.
2426 ly_voice = [e for e in ly_voice
2427 if not isinstance(e, musicexp.KeySignatureChange)]
2429 seq_music.elements = ly_voice
2430 for k in lyrics.keys ():
2431 return_value.lyrics_dict[k] = musicexp.Lyrics ()
2432 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
2435 if len (modes_found) > 1:
2436 error_message (_ ('cannot simultaneously have more than one mode: %s') % modes_found.keys ())
2438 if options.relative:
2439 v = musicexp.RelativeMusic ()
2440 v.element = seq_music
2441 v.basepitch = first_pitch
2444 return_value.ly_voice = seq_music
2445 for mode in modes_found.keys ():
2446 v = musicexp.ModeChangingMusicWrapper()
2447 v.element = seq_music
2449 return_value.ly_voice = v
2451 # create \figuremode { figured bass elements }
2452 if figured_bass_builder.has_relevant_elements:
2453 fbass_music = musicexp.SequentialMusic ()
2454 fbass_music.elements = group_repeats (figured_bass_builder.elements)
2455 v = musicexp.ModeChangingMusicWrapper()
2456 v.mode = 'figuremode'
2457 v.element = fbass_music
2458 return_value.figured_bass = v
2460 # create \chordmode { chords }
2461 if chordnames_builder.has_relevant_elements:
2462 cname_music = musicexp.SequentialMusic ()
2463 cname_music.elements = group_repeats (chordnames_builder.elements)
2464 v = musicexp.ModeChangingMusicWrapper()
2465 v.mode = 'chordmode'
2466 v.element = cname_music
2467 return_value.chordnames = v
2471 def musicxml_id_to_lily (id):
2472 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
2473 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
2475 for digit in digits:
2476 d = digits.index (digit)
2477 id = re.sub ('%d' % d, digit, id)
2479 id = re.sub ('[^a-zA-Z]', 'X', id)
2482 def musicxml_pitch_to_lily (mxl_pitch):
2483 p = musicexp.Pitch ()
2484 p.alteration = mxl_pitch.get_alteration ()
2485 p.step = musicxml_step_to_lily (mxl_pitch.get_step ())
2486 p.octave = mxl_pitch.get_octave () - 4
2489 def musicxml_unpitched_to_lily (mxl_unpitched):
2491 step = mxl_unpitched.get_step ()
2493 p = musicexp.Pitch ()
2494 p.step = musicxml_step_to_lily (step)
2495 octave = mxl_unpitched.get_octave ()
2497 p.octave = octave - 4
2500 def musicxml_restdisplay_to_lily (mxl_rest):
2502 step = mxl_rest.get_step ()
2504 p = musicexp.Pitch ()
2505 p.step = musicxml_step_to_lily (step)
2506 octave = mxl_rest.get_octave ()
2508 p.octave = octave - 4
2511 def voices_in_part (part):
2512 """Return a Name -> Voice dictionary for PART"""
2514 part.extract_voices ()
2515 voices = part.get_voices ()
2516 part_info = part.get_staff_attributes ()
2518 return (voices, part_info)
2520 def voices_in_part_in_parts (parts):
2521 """return a Part -> Name -> Voice dictionary"""
2522 # don't crash if p doesn't have an id (that's invalid MusicXML,
2523 # but such files are out in the wild!
2526 voices = voices_in_part (p)
2527 if (hasattr (p, "id")):
2528 dictionary[p.id] = voices
2530 # TODO: extract correct part id from other sources
2531 dictionary[None] = voices
2535 def get_all_voices (parts):
2536 all_voices = voices_in_part_in_parts (parts)
2539 all_ly_staffinfo = {}
2540 for p, (name_voice, staff_info) in all_voices.items ():
2543 for n, v in name_voice.items ():
2544 progress (_ ("Converting to LilyPond expressions..."))
2545 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
2546 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
2548 all_ly_voices[p] = part_ly_voices
2549 all_ly_staffinfo[p] = staff_info
2551 return (all_ly_voices, all_ly_staffinfo)
2554 def option_parser ():
2555 p = ly.get_option_parser (usage = _ ("musicxml2ly [OPTION]... FILE.xml"),
2557 _ ("""Convert MusicXML from FILE.xml to LilyPond input.
2558 If the given filename is -, musicxml2ly reads from the command line.
2559 """), add_help_option=False)
2561 p.add_option("-h", "--help",
2563 help=_ ("show this help and exit"))
2565 p.version = ('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
2567 _ ("""Copyright (c) 2005--2011 by
2568 Han-Wen Nienhuys <hanwen@xs4all.nl>,
2569 Jan Nieuwenhuizen <janneke@gnu.org> and
2570 Reinhold Kainhofer <reinhold@kainhofer.com>
2574 This program is free software. It is covered by the GNU General Public
2575 License and you are welcome to change it and/or distribute copies of it
2576 under certain conditions. Invoke as `%s --warranty' for more
2577 information.""") % 'lilypond')
2579 p.add_option("--version",
2581 help=_ ("show version number and exit"))
2583 p.add_option ('-v', '--verbose',
2584 action = "store_true",
2586 help = _ ("be verbose"))
2588 p.add_option ('', '--lxml',
2589 action = "store_true",
2592 help = _ ("use lxml.etree; uses less memory and cpu time"))
2594 p.add_option ('-z', '--compressed',
2595 action = "store_true",
2596 dest = 'compressed',
2598 help = _ ("input file is a zip-compressed MusicXML file"))
2600 p.add_option ('-r', '--relative',
2601 action = "store_true",
2604 help = _ ("convert pitches in relative mode (default)"))
2606 p.add_option ('-a', '--absolute',
2607 action = "store_false",
2609 help = _ ("convert pitches in absolute mode"))
2611 p.add_option ('-l', '--language',
2612 metavar = _ ("LANG"),
2614 help = _ ("use LANG for pitch names, e.g. 'deutsch' for note names in German"))
2616 p.add_option ('--nd', '--no-articulation-directions',
2617 action = "store_false",
2619 dest = "convert_directions",
2620 help = _ ("do not convert directions (^, _ or -) for articulations, dynamics, etc."))
2622 p.add_option ('--nrp', '--no-rest-positions',
2623 action = "store_false",
2625 dest = "convert_rest_positions",
2626 help = _ ("do not convert exact vertical positions of rests"))
2628 p.add_option ('--npl', '--no-page-layout',
2629 action = "store_false",
2631 dest = "convert_page_layout",
2632 help = _ ("do not convert the exact page layout and breaks"))
2634 p.add_option ('--no-beaming',
2635 action = "store_false",
2637 dest = "convert_beaming",
2638 help = _ ("do not convert beaming information, use lilypond's automatic beaming instead"))
2640 p.add_option ('-o', '--output',
2641 metavar = _ ("FILE"),
2645 dest = 'output_name',
2646 help = _ ("set output filename to FILE, stdout if -"))
2647 p.add_option_group ('',
2649 _ ("Report bugs via %s")
2650 % 'http://post.gmane.org/post.php'
2651 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
2654 def music_xml_voice_name_to_lily_name (part_id, name):
2655 str = "Part%sVoice%s" % (part_id, name)
2656 return musicxml_id_to_lily (str)
2658 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
2659 str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
2660 return musicxml_id_to_lily (str)
2662 def music_xml_figuredbass_name_to_lily_name (part_id, voicename):
2663 str = "Part%sVoice%sFiguredBass" % (part_id, voicename)
2664 return musicxml_id_to_lily (str)
2666 def music_xml_chordnames_name_to_lily_name (part_id, voicename):
2667 str = "Part%sVoice%sChords" % (part_id, voicename)
2668 return musicxml_id_to_lily (str)
2670 def print_voice_definitions (printer, part_list, voices):
2671 for part in part_list:
2673 nv_dict = voices.get (part_id, {})
2674 for (name, voice) in nv_dict.items ():
2675 k = music_xml_voice_name_to_lily_name (part_id, name)
2676 printer.dump ('%s = ' % k)
2677 voice.ly_voice.print_ly (printer)
2679 if voice.chordnames:
2680 cnname = music_xml_chordnames_name_to_lily_name (part_id, name)
2681 printer.dump ('%s = ' % cnname )
2682 voice.chordnames.print_ly (printer)
2684 for l in voice.lyrics_order:
2685 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
2686 printer.dump ('%s = ' % lname )
2687 voice.lyrics_dict[l].print_ly (printer)
2689 if voice.figured_bass:
2690 fbname = music_xml_figuredbass_name_to_lily_name (part_id, name)
2691 printer.dump ('%s = ' % fbname )
2692 voice.figured_bass.print_ly (printer)
2697 return dict ([(elt,1) for elt in l]).keys ()
2699 # format the information about the staff in the form
2702 # [voiceid1, [lyricsid11, lyricsid12,...], figuredbassid1],
2703 # [voiceid2, [lyricsid21, lyricsid22,...], figuredbassid2],
2707 # raw_voices is of the form [(voicename, lyricsids, havefiguredbass)*]
2708 def format_staff_info (part_id, staff_id, raw_voices):
2710 for (v, lyricsids, figured_bass, chordnames) in raw_voices:
2711 voice_name = music_xml_voice_name_to_lily_name (part_id, v)
2712 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
2714 figured_bass_name = ''
2716 figured_bass_name = music_xml_figuredbass_name_to_lily_name (part_id, v)
2717 chordnames_name = ''
2719 chordnames_name = music_xml_chordnames_name_to_lily_name (part_id, v)
2720 voices.append ([voice_name, voice_lyrics, figured_bass_name, chordnames_name])
2721 return [staff_id, voices]
2723 def update_score_setup (score_structure, part_list, voices):
2725 for part_definition in part_list:
2726 part_id = part_definition.id
2727 nv_dict = voices.get (part_id)
2729 error_message (_ ('unknown part in part-list: %s') % part_id)
2732 staves = reduce (lambda x,y: x+ y,
2733 [voice.voicedata._staves.keys ()
2734 for voice in nv_dict.values ()],
2737 if len (staves) > 1:
2739 staves = uniq_list (staves)
2742 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2743 for (voice_name, voice) in nv_dict.items ()
2744 if voice.voicedata._start_staff == s]
2745 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
2747 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2748 for (voice_name, voice) in nv_dict.items ()]
2749 staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
2750 score_structure.set_part_information (part_id, staves_info)
2752 # Set global values in the \layout block, like auto-beaming etc.
2753 def update_layout_information ():
2754 if not conversion_settings.ignore_beaming and layout_information:
2755 layout_information.set_context_item ('Score', 'autoBeaming = ##f')
2757 def print_ly_preamble (printer, filename):
2758 printer.dump_version ()
2759 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
2761 def print_ly_additional_definitions (printer, filename):
2762 if needed_additional_definitions:
2764 printer.print_verbatim ('%% additional definitions required by the score:')
2766 for a in set(needed_additional_definitions):
2767 printer.print_verbatim (additional_definitions.get (a, ''))
2771 # Read in the tree from the given I/O object (either file or string) and
2772 # demarshall it using the classes from the musicxml.py file
2773 def read_xml (io_object, use_lxml):
2776 tree = lxml.etree.parse (io_object)
2777 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
2780 from xml.dom import minidom, Node
2781 doc = minidom.parse(io_object)
2782 node = doc.documentElement
2783 return musicxml.minidom_demarshal_node (node)
2787 def read_musicxml (filename, compressed, use_lxml):
2791 progress (_ ("Input is compressed, extracting raw MusicXML data from stdin") )
2792 # unfortunately, zipfile.ZipFile can't read directly from
2793 # stdin, so copy everything from stdin to a temp file and read
2794 # that. TemporaryFile() will remove the file when it is closed.
2795 tmp = tempfile.TemporaryFile()
2796 sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0) # Make sys.stdin binary
2797 bytes_read = sys.stdin.read (8192)
2799 for b in bytes_read:
2801 bytes_read = sys.stdin.read (8192)
2802 z = zipfile.ZipFile (tmp, "r")
2804 progress (_ ("Input file %s is compressed, extracting raw MusicXML data") % filename)
2805 z = zipfile.ZipFile (filename, "r")
2806 container_xml = z.read ("META-INF/container.xml")
2807 if not container_xml:
2809 container = read_xml (StringIO.StringIO (container_xml), use_lxml)
2812 rootfiles = container.get_maybe_exist_named_child ('rootfiles')
2815 rootfile_list = rootfiles.get_named_children ('rootfile')
2817 if len (rootfile_list) > 0:
2818 mxml_file = getattr (rootfile_list[0], 'full-path', None)
2820 raw_string = z.read (mxml_file)
2823 io_object = StringIO.StringIO (raw_string)
2824 elif filename == "-":
2825 io_object = sys.stdin
2827 io_object = filename
2829 return read_xml (io_object, use_lxml)
2832 def convert (filename, options):
2834 progress (_ ("Reading MusicXML from Standard input ...") )
2836 progress (_ ("Reading MusicXML from %s ...") % filename)
2838 tree = read_musicxml (filename, options.compressed, options.use_lxml)
2839 score_information = extract_score_information (tree)
2840 paper_information = extract_paper_information (tree)
2842 parts = tree.get_typed_children (musicxml.Part)
2843 (voices, staff_info) = get_all_voices (parts)
2846 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
2848 score = extract_score_structure (mxl_pl, staff_info)
2849 part_list = mxl_pl.get_named_children ("score-part")
2851 # score information is contained in the <work>, <identification> or <movement-title> tags
2852 update_score_setup (score, part_list, voices)
2853 # After the conversion, update the list of settings for the \layout block
2854 update_layout_information ()
2856 if not options.output_name:
2857 options.output_name = os.path.basename (filename)
2858 options.output_name = os.path.splitext (options.output_name)[0]
2859 elif re.match (".*\.ly", options.output_name):
2860 options.output_name = os.path.splitext (options.output_name)[0]
2863 #defs_ly_name = options.output_name + '-defs.ly'
2864 if (options.output_name == "-"):
2865 output_ly_name = 'Standard output'
2867 output_ly_name = options.output_name + '.ly'
2869 progress (_ ("Output to `%s'") % output_ly_name)
2870 printer = musicexp.Output_printer()
2871 #progress (_ ("Output to `%s'") % defs_ly_name)
2872 if (options.output_name == "-"):
2873 printer.set_file (codecs.getwriter ("utf-8")(sys.stdout))
2875 printer.set_file (codecs.open (output_ly_name, 'wb', encoding='utf-8'))
2876 print_ly_preamble (printer, filename)
2877 print_ly_additional_definitions (printer, filename)
2878 if score_information:
2879 score_information.print_ly (printer)
2880 if paper_information and conversion_settings.convert_page_layout:
2881 paper_information.print_ly (printer)
2882 if layout_information:
2883 layout_information.print_ly (printer)
2884 print_voice_definitions (printer, part_list, voices)
2887 printer.dump ("% The score definition")
2889 score.print_ly (printer)
2894 def get_existing_filename_with_extension (filename, ext):
2895 if os.path.exists (filename):
2897 newfilename = filename + "." + ext
2898 if os.path.exists (newfilename):
2900 newfilename = filename + ext
2901 if os.path.exists (newfilename):
2906 opt_parser = option_parser()
2909 (options, args) = opt_parser.parse_args ()
2911 opt_parser.print_usage()
2914 if options.language:
2915 musicexp.set_pitch_language (options.language)
2916 needed_additional_definitions.append (options.language)
2917 additional_definitions[options.language] = "\\language \"%s\"\n" % options.language
2918 conversion_settings.ignore_beaming = not options.convert_beaming
2919 conversion_settings.convert_page_layout = options.convert_page_layout
2921 # Allow the user to leave out the .xml or xml on the filename
2922 basefilename = args[0].decode('utf-8')
2923 if basefilename == "-": # Read from stdin
2926 filename = get_existing_filename_with_extension (basefilename, "xml")
2928 filename = get_existing_filename_with_extension (basefilename, "mxl")
2929 options.compressed = True
2930 if filename and filename.endswith ("mxl"):
2931 options.compressed = True
2933 if filename and (filename == "-" or os.path.exists (filename)):
2934 voices = convert (filename, options)
2936 progress (_ ("Unable to find input file %s") % basefilename)
2938 if __name__ == '__main__':