diff options
author | John Gourlay <john@weathervanefarm.net> | 2016-02-18 21:47:49 -0500 |
---|---|---|
committer | John Gourlay <john@weathervanefarm.net> | 2016-02-18 21:47:49 -0500 |
commit | 2ab5d80245dcab194daea64ec83ded3ec8252e51 (patch) | |
tree | 34c247e35ad2b16bcc687e89213d7ca7552260c4 /python | |
parent | ba40d4da58323da7829ff9eb4f8b6ea576d47559 (diff) |
Copy the lastest musicxml2ly files from Philomelos. These versions overwrite
changes made directly in the LilyPond repository. Those changes will be
reintroduced subsequently.
Diffstat (limited to 'python')
-rw-r--r-- | python/musicexp.py | 822 | ||||
-rw-r--r-- | python/musicxml.py | 1868 |
2 files changed, 1858 insertions, 832 deletions
diff --git a/python/musicexp.py b/python/musicexp.py index a564f29ce5..a0b13efcc6 100644 --- a/python/musicexp.py +++ b/python/musicexp.py @@ -3,7 +3,10 @@ import inspect import sys import string import re +import math import lilylib as ly +import warnings +import utilities _ = ly._ @@ -12,7 +15,8 @@ from rational import Rational # Store previously converted pitch for \relative conversion as a global state variable previous_pitch = None relative_pitches = False - +whatOrnament = "" +ly_dur = None # stores lilypond durations def escape_instrument_string (input_string): retstring = string.replace (input_string, "\"", "\\\"") @@ -35,13 +39,11 @@ class Output_stack_element: o.factor = self.factor return o -class Output_printer: - - """A class that takes care of formatting (eg.: indenting) a +class Output_printer(object): + """ + A class that takes care of formatting (eg.: indenting) a Music expression as a .ly file. - """ - def __init__ (self): self._line = '' self._indent = 4 @@ -56,8 +58,7 @@ class Output_printer: self._file = file def dump_version (self): - self.newline () - self.print_verbatim ('\\version "@TOPLEVEL_VERSION@"') + self.print_verbatim ('\\version "2.19.15"') self.newline () def get_indent (self): @@ -69,7 +70,7 @@ class Output_printer: def add_factor (self, factor): self.override() - self._output_state_stack[-1].factor *= factor + self._output_state_stack[-1].factor *= factor def revert (self): del self._output_state_stack[-1] @@ -84,13 +85,13 @@ class Output_printer: def unformatted_output (self, str): # don't indent on \< and indent only once on << - self._nesting += ( str.count ('<') + self._nesting += (str.count ('<') - str.count ('\<') - str.count ('<<') - + str.count ('{') ) - self._nesting -= ( str.count ('>') - str.count ('\>') - str.count ('>>') + + str.count ('{')) + self._nesting -= (str.count ('>') - str.count ('\>') - str.count ('>>') - str.count ('->') - str.count ('_>') - str.count ('^>') - + str.count ('}') ) + + str.count ('}')) self.print_verbatim (str) def print_duration_string (self, str): @@ -99,6 +100,15 @@ class Output_printer: self.unformatted_output (str) +# def print_note_color (self, object, rgb=None): +# if rgb: +# str = ("\\once\\override %s #'color = #(rgb-color %s # %s %s)" % (object, rgb[0], rgb[1], rgb[2])) +# else: +# str = "\\revert %s #'color" % object +# self.newline() +# self.add_word(str) +# self.newline() + def add_word (self, str): if (len (str) + 1 + len (self._line) > self._line_len): self.newline() @@ -125,11 +135,11 @@ class Output_printer: self._skipspace = False self.unformatted_output (str) else: - words = string.split (str) + # Avoid splitting quoted strings (e.g. "1. Wie") when indenting. + words = utilities.split_string_and_preserve_doublequoted_substrings(str) for w in words: self.add_word (w) - def close (self): self.newline () self._file.close () @@ -137,19 +147,19 @@ class Output_printer: class Duration: - def __init__ (self): + def __init__(self): self.duration_log = 0 self.dots = 0 - self.factor = Rational (1) + self.factor = Rational(1) - def lisp_expression (self): + def lisp_expression(self): return '(ly:make-duration %d %d %d %d)' % (self.duration_log, self.dots, - self.factor.numerator (), - self.factor.denominator ()) - + self.factor.numerator(), + self.factor.denominator()) - def ly_expression (self, factor = None, scheme_mode = False): + def ly_expression(self, factor=None, scheme_mode=False): + global ly_dur # stores lilypond durations if not factor: factor = self.factor @@ -158,58 +168,131 @@ class Duration: longer_dict = {-1: "breve", -2: "longa"} else: longer_dict = {-1: "\\breve", -2: "\\longa"} - str = longer_dict.get (self.duration_log, "1") + dur_str = longer_dict.get(self.duration_log, "1") else: - str = '%d' % (1 << self.duration_log) - str += '.'*self.dots + dur_str = '%d' % (1 << self.duration_log) + dur_str += '.' * self.dots - if factor <> Rational (1,1): - if factor.denominator () <> 1: - str += '*%d/%d' % (factor.numerator (), factor.denominator ()) + if factor <> Rational(1, 1): + if factor.denominator() <> 1: + dur_str += '*%d/%d' % (factor.numerator(), factor.denominator()) else: - str += '*%d' % factor.numerator () + dur_str += '*%d' % factor.numerator() - return str + if dur_str.isdigit(): + ly_dur = int(dur_str) + # TODO: We need to deal with dotted notes and scaled durations + # otherwise ly_dur won't work in combination with tremolos. + return dur_str - def print_ly (self, outputter): - str = self.ly_expression (self.factor / outputter.duration_factor ()) - outputter.print_duration_string (str) + def print_ly(self, outputter): + dur_str = self.ly_expression(self.factor / outputter.duration_factor()) + outputter.print_duration_string(dur_str) def __repr__(self): return self.ly_expression() - def copy (self): - d = Duration () + def copy(self): + d = Duration() d.dots = self.dots d.duration_log = self.duration_log d.factor = self.factor return d - def get_length (self): - dot_fact = Rational( (1 << (1 + self.dots))-1, + def get_length(self): + dot_fact = Rational((1 << (1 + self.dots)) - 1, 1 << self.dots) - log = abs (self.duration_log) + log = abs(self.duration_log) dur = 1 << log if self.duration_log < 0: - base = Rational (dur) + base = Rational(dur) else: - base = Rational (1, dur) + base = Rational(1, dur) return base * dot_fact * self.factor -# implement the midi command line option '-m' and '--midi' -# if TRUE add midi-block to .ly file (see below) -def set_create_midi (option): +def set_create_midi(option): + """ + Implement the midi command line option '-m' and '--midi'. + If True, add midi-block to .ly file (see L{musicexp.Score.print_ly}). + + @param option: Indicates whether the midi-block has to be added or not. + @type option: boolean + """ global midi_option midi_option = option def get_create_midi (): + """ + Return, if exists the state of the midi-option. + + @return: The state of the midi-option. + @rtype: boolean + """ try: return midi_option except: return False +# implement the command line option '--transpose' +def set_transpose(option): + global transpose_option + transpose_option = option + +def get_transpose(optType): + try: + if(optType == "string"): + return '\\transpose c %s' % transpose_option + elif(optType == "integer"): + p = generic_tone_to_pitch(transpose_option) + return p.semitones() + except: + if(optType == "string"): + return "" + elif(optType == "integer"): + return 0 + +# implement the command line option '--tab-clef' +def set_tab_clef(option): + global tab_clef_option + tab_clef_option = option + +def get_tab_clef(): + try: + return ("tab", tab_clef_option)[tab_clef_option == "tab" or tab_clef_option == "moderntab"] + except: + return "tab" + +# definitions of the command line option '--string-numbers' +def set_string_numbers(option): + global string_numbers_option + string_numbers_option = option + +def get_string_numbers(): + try: + return ("t", string_numbers_option)[string_numbers_option == "t" or string_numbers_option == "f"] + except: + return "t" + +def generic_tone_to_pitch (tone): + accidentals_dict = { + "" : 0, + "es" : -1, + "s" : -1, + "eses" : -2, + "ses" : -2, + "is" : 1, + "isis" : 2 + } + p = Pitch () + tone_ = tone.strip().lower() + p.octave = tone_.count("'") - tone_.count(",") + tone_ = tone_.replace(",","").replace("'","") + p.step = ((ord (tone_[0]) - ord ('a') + 5) % 7) + p.alteration = accidentals_dict.get(tone_[1:], 0) + return p + # Implement the different note names for the various languages def pitch_generic (pitch, notenames, accidentals): str = notenames[pitch.step] @@ -224,7 +307,7 @@ def pitch_generic (pitch, notenames, accidentals): ly.warning (_ ("Language does not support microtones contained in the piece")) else: try: - str += {-0.5: accidentals[1], 0.5: accidentals[2]}[pitch.alteration-halftones] + str += {-0.5: accidentals[1], 0.5: accidentals[2]}[pitch.alteration - halftones] except KeyError: ly.warning (_ ("Language does not support microtones contained in the piece")) return str @@ -283,7 +366,6 @@ def set_pitch_language (language): # global variable to hold the formatting function. pitch_generating_function = pitch_general - class Pitch: def __init__ (self): self.alteration = 0 @@ -296,12 +378,12 @@ class Pitch: def transposed (self, interval): c = self.copy () - c.alteration += interval.alteration + c.alteration += interval.alteration c.step += interval.step c.octave += interval.octave c.normalize () - target_st = self.semitones() + interval.semitones() + target_st = self.semitones() + interval.semitones() c.alteration += target_st - c.semitones() return c @@ -310,7 +392,7 @@ class Pitch: c.step += 7 c.octave -= 1 c.octave += c.step / 7 - c.step = c.step % 7 + c.step = c.step % 7 def lisp_expression (self): return '(ly:make-pitch %d %d %d)' % (self.octave, @@ -322,13 +404,36 @@ class Pitch: p.alteration = self.alteration p.step = self.step p.octave = self.octave + p._force_absolute_pitch = self._force_absolute_pitch return p def steps (self): - return self.step + self.octave *7 + return self.step + self.octave * 7 def semitones (self): - return self.octave * 12 + [0,2,4,5,7,9,11][self.step] + self.alteration + return self.octave * 12 + [0, 2, 4, 5, 7, 9, 11][self.step] + self.alteration + + def normalize_alteration (c): + if(c.alteration < 0 and [True, False, False, True, False, False, False][c.step]): + c.alteration += 1 + c.step -= 1 + elif(c.alteration > 0 and [False, False, True, False, False, False, True][c.step]): + c.alteration -= 1 + c.step += 1 + c.normalize () + + def add_semitones (self, number): + semi = number + self.alteration + self.alteration = 0 + if(semi == 0): + return + sign = (1,-1)[semi < 0] + prev = self.semitones() + while abs((prev + semi) - self.semitones ()) > 1: + self.step += sign + self.normalize() + self.alteration += (prev + semi) - self.semitones () + self.normalize_alteration () def ly_step_expression (self): return pitch_generating_function (self) @@ -363,7 +468,6 @@ class Pitch: str += self.relative_pitch () else: str += self.absolute_pitch () - return str def print_ly (self, outputter): @@ -398,7 +502,7 @@ class Music: props = self.get_properties () - return "(make-music '%s %s)" % (name, props) + return "(make-music '%s %s)" % (name, props) def set_start (self, start): self.start = start @@ -408,7 +512,7 @@ class Music: return self return None - def print_comment (self, printer, text = None): + def print_comment (self, printer, text=None): if not text: text = self.comment @@ -589,12 +693,12 @@ class NestedMusic(Music): def get_subset_properties (self, predicate): return ("'elements (list %s)" % string.join (map (lambda x: x.lisp_expression(), - filter ( predicate, self.elements)))) + filter (predicate, self.elements)))) def get_neighbor (self, music, dir): assert music.parent == self idx = self.elements.index (music) idx += dir - idx = min (idx, len (self.elements) -1) + idx = min (idx, len (self.elements) - 1) idx = max (idx, 0) return self.elements[idx] @@ -624,7 +728,7 @@ class NestedMusic(Music): class SequentialMusic (NestedMusic): def get_last_event_chord (self): value = None - at = len( self.elements ) - 1 + at = len(self.elements) - 1 while (at >= 0 and not isinstance (self.elements[at], ChordEvent) and not isinstance (self.elements[at], BarLine)): @@ -634,7 +738,7 @@ class SequentialMusic (NestedMusic): value = self.elements[at] return value - def print_ly (self, printer, newline = True): + def print_ly (self, printer, newline=True): printer ('{') if self.comment: self.print_comment (printer) @@ -654,7 +758,7 @@ class SequentialMusic (NestedMusic): props = self.get_subset_properties (pred) - return "(make-music '%s %s)" % (name, props) + return "(make-music '%s %s)" % (name, props) def set_start (self, start): for e in self.elements: @@ -697,39 +801,71 @@ class Lyrics: self.lyrics_syllables = [] def print_ly (self, printer): - printer.dump ("\lyricmode {") - for l in self.lyrics_syllables: - printer.dump ( "%s " % l ) - printer.dump ("}") + printer.dump (self.ly_expression ()) + printer.newline() + printer.dump ('}') + printer.newline() def ly_expression (self): - lstr = "\lyricmode {\n " + lstr = "\lyricmode {\set ignoreMelismata = ##t" for l in self.lyrics_syllables: - lstr += l + " " - lstr += "\n}" + lstr += l + #lstr += "\n}" return lstr - class Header: + def __init__ (self): self.header_fields = {} + def set_field (self, field, value): self.header_fields[field] = value - def print_ly (self, printer): - printer.dump ("\header {") - printer.newline () - for (k,v) in self.header_fields.items (): + def format_header_strings(self, key, value, printer): + printer.dump(key + ' = ') + + # If a header item contains a line break, it is segmented. The + # substrings are formatted with the help of \markup, using + # \column and \line. + if '\n' in value: + value = value.replace('"', '') + printer.dump(r'\markup \column {') + substrings = value.split('\n') + for s in substrings: + printer.newline() + printer.dump(r'\line { "' + s + '"}') + printer.dump('}') + printer.newline() + else: + printer.dump(value) + printer.newline() + + def print_ly(self, printer): + printer.dump("\header {") + printer.newline() + for (k, v) in self.header_fields.items(): if v: - printer.dump ('%s = %s' % (k,v)) - printer.newline () - printer.dump ("}") - printer.newline () - printer.newline () + self.format_header_strings(k, v, printer) + #printer.newline() + printer.dump(r'tagline = \markup {') + printer.newline() + printer.dump(r' \center-column {') + printer.newline() + printer.dump('\line {"Music engraving by LilyPond " $(lilypond-version) | \with-url #"http://www.lilypond.org" {www.lilypond.org}}') + printer.newline() + printer.dump('\line {\with-url #"https://philomelos.net" {\with-color #grey {Learn, teach and share music on https://philomelos.net}}}') + printer.newline() + printer.dump('}') + printer.newline() + printer.dump('}') + printer.newline() + printer.dump("}") + printer.newline() + printer.newline() class Paper: - def __init__ (self): + def __init__(self): self.global_staff_size = -1 # page size self.page_width = -1 @@ -743,17 +879,32 @@ class Paper: self.system_right_margin = -1 self.system_distance = -1 self.top_system_distance = -1 + self.indent = 0 + self.short_indent = 0 + self.instrument_names = [] def print_length_field (self, printer, field, value): if value >= 0: printer.dump ("%s = %s\\cm" % (field, value)) printer.newline () + + def get_longest_instrument_name(self): + result = '' + for name in self.instrument_names: + lines = name.split('\n') + for line in lines: + if len(line) > len(result): + result = line + return result + def print_ly (self, printer): if self.global_staff_size > 0: printer.dump ('#(set-global-staff-size %s)' % self.global_staff_size) printer.newline () printer.dump ('\\paper {') printer.newline () + printer.dump ("markup-system-spacing #'padding = #2") + printer.newline () self.print_length_field (printer, "paper-width", self.page_width) self.print_length_field (printer, "paper-height", self.page_height) self.print_length_field (printer, "top-margin", self.top_margin) @@ -765,6 +916,14 @@ class Paper: # system_right_margin in LilyPond? self.print_length_field (printer, "between-system-space", self.system_distance) self.print_length_field (printer, "page-top-space", self.top_system_distance) + # TODO: Compute the indentation with the instrument name lengths + + # TODO: font width ? + char_per_cm = (len(self.get_longest_instrument_name()) * 13) / self.page_width + if (self.indent != 0): + self.print_length_field (printer, "indent", self.indent/char_per_cm) + if (self.short_indent != 0): + self.print_length_field (printer, "short-indent", self.short_indent/char_per_cm) printer.dump ('}') printer.newline () @@ -863,6 +1022,7 @@ class ChordEvent (NestedMusic): # Print all overrides and other settings needed by the # articulations/ornaments before the note + for e in other_events: e.print_before_note (printer) @@ -874,10 +1034,17 @@ class ChordEvent (NestedMusic): global previous_pitch pitches = [] basepitch = None + stem = None for x in note_events: + if(x.associated_events): + for aev in x.associated_events: + if (isinstance(aev, StemEvent) and aev.value): + stem = aev pitches.append (x.chord_element_ly ()) if not basepitch: basepitch = previous_pitch + if stem: + printer (stem.ly_expression ()) printer ('<%s>' % string.join (pitches)) previous_pitch = basepitch duration = self.get_duration () @@ -953,7 +1120,7 @@ class SpanEvent (Event): self.span_direction = 0 # start/stop self.line_type = 'solid' self.span_type = 0 # e.g. cres/decrescendo, ottava up/down - self.size = 0 # size of e.g. ocrave shift + self.size = 0 # size of e.g. octave shift def wait_for_note (self): return True def get_properties(self): @@ -987,14 +1154,39 @@ class PedalEvent (SpanEvent): 1:'\\sustainOff'}.get (self.span_direction, '') class TextSpannerEvent (SpanEvent): + def print_before_note (self, printer): + if hasattr(self, 'style') and self.style=="wave": + printer.dump("\once \override TextSpanner #'style = #'trill") + try: + x = {-1:'\\textSpannerDown', 0:'\\textSpannerNeutral', 1: '\\textSpannerUp'}.get(self.force_direction, '') + printer.dump (x) + except: + pass + + def print_after_note (self, printer): + pass + def ly_expression (self): - return {-1: '\\startTextSpan', - 1:'\\stopTextSpan'}.get (self.span_direction, '') + global whatOrnament + if hasattr(self, 'style') and self.style=="ignore": + return "" + # if self.style=="wave": + if whatOrnament == "wave": + return {-1: '\\startTextSpan', + 1:'\\stopTextSpan'}.get (self.span_direction, '') + else: + if hasattr(self, 'style') and self.style=="stop" and whatOrnament != "trill": return "" + return {-1: '\\startTrillSpan', + 1:'\\stopTrillSpan'}.get (self.span_direction, '') class BracketSpannerEvent (SpanEvent): # Ligature brackets use prefix-notation!!! def print_before_note (self, printer): if self.span_direction == -1: + if self.force_direction == 1: + printer.dump("\once \override LigatureBracket #' direction = #UP") + elif self.force_direction == -1: + printer.dump("\once \override LigatureBracket #' direction = #DOWN") printer.dump ('\[') # the bracket after the last note def print_after_note (self, printer): @@ -1009,7 +1201,7 @@ class OctaveShiftEvent (SpanEvent): def wait_for_note (self): return False def set_span_type (self, type): - self.span_type = {'up': 1, 'down': -1}.get (type, 0) + self.span_type = {'up': 1, 'down':-1}.get (type, 0) def ly_octave_shift_indicator (self): # convert 8/15 to lilypond indicators (+-1/+-2) try: @@ -1018,7 +1210,7 @@ class OctaveShiftEvent (SpanEvent): ly.warning (_ ("Invalid octave shift size found: %s. Using no shift.") % self.size) value = 0 # negative values go up! - value *= -1*self.span_type + value *= -1 * self.span_type return value def ly_expression (self): dir = self.ly_octave_shift_indicator () @@ -1026,7 +1218,7 @@ class OctaveShiftEvent (SpanEvent): if dir: value = '\ottava #%s' % dir return { - -1: value, + - 1: value, 1: '\ottava #0'}.get (self.span_direction, '') class TrillSpanEvent (SpanEvent): @@ -1038,7 +1230,7 @@ class TrillSpanEvent (SpanEvent): class GlissandoEvent (SpanEvent): def print_before_note (self, printer): if self.span_direction == -1: - style= { + style = { "dashed" : "dashed-line", "dotted" : "dotted-line", "wavy" : "zigzag" @@ -1077,20 +1269,24 @@ class TieEvent(Event): class HairpinEvent (SpanEvent): def set_span_type (self, type): - self.span_type = {'crescendo' : 1, 'decrescendo' : -1, 'diminuendo' : -1 }.get (type, 0) + self.span_type = {'crescendo' : 1, 'decrescendo' :-1, 'diminuendo' :-1 }.get (type, 0) def hairpin_to_ly (self): if self.span_direction == 1: return '\!' else: return {1: '\<', -1: '\>'}.get (self.span_type, '') + def direction_mod (self): + return { 1: '^', -1: '_', 0: '-' }.get (self.force_direction, '-') + def ly_expression (self): return self.hairpin_to_ly () def print_ly (self, printer): val = self.hairpin_to_ly () if val: - printer.dump (val) + # printer.dump (val) + printer.dump ('%s%s' % (self.direction_mod (), val)) @@ -1098,6 +1294,7 @@ class DynamicsEvent (Event): def __init__ (self): Event.__init__ (self) self.type = None + self.force_direction = 0 def wait_for_note (self): return True def ly_expression (self): @@ -1106,9 +1303,12 @@ class DynamicsEvent (Event): else: return + def direction_mod (self): + return { 1: '^', -1: '_', 0: '-' }.get (self.force_direction, '-') + def print_ly (self, printer): if self.type: - printer.dump ("\\%s" % self.type) + printer.dump ('%s\\%s' % (self.direction_mod (), self.type)) class MarkEvent (Event): def __init__ (self, text="\\default"): @@ -1139,9 +1339,30 @@ class TextEvent (Event): self.force_direction = None self.markup = '' def wait_for_note (self): + """ This is problematic: the lilypond-markup ^"text" + requires wait_for_note to be true. Otherwise the + compilation will fail. So we are forced to set return to True. + But in some cases this might lead to a wrong placement of the text. + In case of words like Allegro the text should be put in a '\tempo'-command. + In this case we don't want to wait for the next note. + In some other cases the text is supposed to be used in a '\mark\markup' construct. + We would not want to wait for the next note either. + There might be other problematic situations. + In the long run we should differentiate between various contexts in MusicXML, e.g. + the following markup should be interpreted as '\tempo "Allegretto"': + <direction placement="above"> + <direction-type> + <words>Allegretto</words> + </direction-type> + <sound tempo="120"/> + </direction> + In the mean time arising problems have to be corrected manually after the conversion. + """ return True def direction_mod (self): + """ 1: placement="above"; -1: placement="below"; 0: no placement attribute. + see musicxml_direction_to_indicator in musicxml2ly_conversion.py """ return { 1: '^', -1: '_', 0: '-' }.get (self.force_direction, '-') def ly_expression (self): @@ -1175,9 +1396,21 @@ class ShortArticulationEvent (ArticulationEvent): return '' class NoDirectionArticulationEvent (ArticulationEvent): + + def is_breathing_sign(self): + return self.type == 'breathe' + + def print_after_note(self, printer): + # The breathing sign should, according to current LilyPond + # praxis, be treated as an independent musical + # event. Consequently, it should be printed _after_ the note + # to which it is attached. + if self.is_breathing_sign(): + printer.dump(r'\breathe') + def ly_expression (self): - if self.type: - return '\\%s' % self.type + if self.type and not self.is_breathing_sign(): + return '\\%s' % self.type else: return '' @@ -1206,11 +1439,11 @@ class FretEvent (MarkupEvent): if self.frets <> 4: val += "h:%s;" % self.frets if self.barre and len (self.barre) >= 3: - val += "c:%s-%s-%s;" % (self.barre[0], self.barre[1], self.barre[2]) + val += "c:%s-%s-%s;" % (self.barre[0], self.barre[1], self.barre[2]+get_transpose("integer")) have_fingering = False for i in self.elements: if len (i) > 1: - val += "%s-%s" % (i[0], i[1]) + val += "%s-%s" % (i[0], i[1]+(get_transpose("integer"),'')[isinstance(i[1],str)]) if len (i) > 2: have_fingering = True val += "-%s" % i[2] @@ -1222,9 +1455,35 @@ class FretEvent (MarkupEvent): else: return '' +class FretBoardNote (Music): + def __init__ (self): + Music.__init__ (self) + self.pitch = None + self.string = None + self.fingering = None + def ly_expression (self): + str = self.pitch.ly_expression() + if self.fingering: + str += "-%s" % self.fingering + if self.string: + str += "\%s" % self.string + return str + +class FretBoardEvent (NestedMusic): + def __init__ (self): + NestedMusic.__init__ (self) + self.duration = None + def print_ly (self, printer): + fretboard_notes = [n for n in self.elements if isinstance (n, FretBoardNote)] + if fretboard_notes: + notes = [] + for n in fretboard_notes: + notes.append (n.ly_expression ()) + contents = string.join (notes) + printer ('<%s>%s' % (contents,self.duration)) class FunctionWrapperEvent (Event): - def __init__ (self, function_name = None): + def __init__ (self, function_name=None): Event.__init__ (self) self.function_name = function_name def pre_note_ly (self, is_chord_element): @@ -1244,16 +1503,36 @@ class ParenthesizeEvent (FunctionWrapperEvent): def __init__ (self): FunctionWrapperEvent.__init__ (self, "parenthesize") -class NotestyleEvent (Event): +class StemEvent (Event): + """" + A class to take care of stem values (up, down, double, none) + """ + def __init__ (self): + Event.__init__ (self) + self.value = None + def pre_chord_ly (self): + if self.value: + return "\\%s" % self.value + else: + return '' + def pre_note_ly (self, is_chord_element): + return '' + def ly_expression (self): + return self.pre_chord_ly () + +class NotestyleEvent (Event): #class changed by DaLa: additional attribute color def __init__ (self): Event.__init__ (self) self.style = None self.filled = None + self.color = None def pre_chord_ly (self): + return_string = '' if self.style: - return "\\once \\override NoteHead #'style = #%s" % self.style - else: - return '' + return_string += " \\once \\override NoteHead #'style = #%s" % self.style + if self.color: + return_string += " \\once \\override NoteHead #'color = #(rgb-color %s %s %s)" % (self.color[0], self.color[1], self.color[2]) + return return_string def pre_note_ly (self, is_chord_element): if self.style and is_chord_element: return "\\tweak #'style #%s" % self.style @@ -1262,6 +1541,20 @@ class NotestyleEvent (Event): def ly_expression (self): return self.pre_chord_ly () +class StemstyleEvent (Event): #class added by DaLa + def __init__ (self): + Event.__init__ (self) + self.color = None + def pre_chord_ly (self): + if self.color: + return "\\once \\override Stem #'color = #(rgb-color %s %s %s)" % (self.color[0], self.color[1], self.color[2]) + else: + return '' + def pre_note_ly (self, is_chord_element): + return '' + def ly_expression (self): + return self.pre_chord_ly () + class ChordPitch: def __init__ (self): @@ -1297,14 +1590,14 @@ class ChordNameEvent (Event): def add_modification (self, mod): self.modifications.append (mod) def ly_expression (self): + if not self.root: return '' value = self.root.ly_expression () if self.duration: value += self.duration.ly_expression () if self.kind: - value += ":" - value += self.kind + value = self.kind.format(value) # First print all additions/changes, and only afterwards all subtractions for m in self.modifications: if m.type == 1: @@ -1317,16 +1610,37 @@ class ChordNameEvent (Event): return value -class TremoloEvent (ArticulationEvent): - def __init__ (self): - Event.__init__ (self) - self.bars = 0 - - def ly_expression (self): - str='' - if self.bars and self.bars > 0: - str += ':%s' % (2 ** (2 + string.atoi (self.bars))) - return str +class TremoloEvent(ArticulationEvent): + def __init__(self): + Event.__init__(self) + self.strokes = 0 + + def ly_expression(self): + ly_str = '' + if self.strokes and int(self.strokes) > 0: + # ly_dur is a global variable defined in class Duration + # ly_dur stores the value of the reciprocal values of notes + # ly_dur is used here to check the current note duration + # if the duration is smaller than 8, e.g. + # quarter, half and whole notes, + # `:(2 ** (2 + number of tremolo strokes))' + # should be appended to the pitch and duration, e.g. + # 1 stroke: `c4:8' or `c2:8' or `c1:8' + # 2 strokes: `c4:16' or `c2:16' or `c1:16' + # ... + # else (if ly_dur is equal to or greater than 8): + # we need to make sure that the tremolo value that is to + # be appended to the pitch and duration is twice the + # duration (if there is only one tremolo stroke. + # Each additional stroke doubles the tremolo value, e.g.: + # 1 stroke: `c8:16', `c16:32', `c32:64', ... + # 2 strokes: `c8:32', `c16:64', `c32:128', ... + # ... + if ly_dur < 8: + ly_str += ':%s' % (2 ** (2 + int(self.strokes))) + else: + ly_str += ':%s' % (2 ** int((math.log(ly_dur, 2)) + int(self.strokes))) + return ly_str class BendEvent (ArticulationEvent): def __init__ (self): @@ -1382,6 +1696,10 @@ class RestEvent (RhythmicEvent): def print_ly (self, printer): for ev in self.associated_events: ev.print_ly (printer) +# if hasattr(self, 'color'): +# printer.print_note_color("NoteHead", self.color) +# printer.print_note_color("Stem", self.color) +# printer.print_note_color("Beam", self.color) if self.pitch: self.pitch.print_ly (printer) self.duration.print_ly (printer) @@ -1397,7 +1715,7 @@ class SkipEvent (RhythmicEvent): class NoteEvent(RhythmicEvent): def __init__ (self): RhythmicEvent.__init__ (self) - self.pitch = None + #self.pitch = None self.drum_type = None self.cautionary = False self.forced_accidental = False @@ -1445,6 +1763,11 @@ class NoteEvent(RhythmicEvent): def print_ly (self, printer): for ev in self.associated_events: ev.print_ly (printer) + if hasattr(self, 'color'): + printer.print_note_color("NoteHead", self.color) + printer.print_note_color("Stem", self.color) + printer.print_note_color("Beam", self.color) + if self.pitch: self.pitch.print_ly (printer) printer (self.pitch_mods ()) @@ -1453,6 +1776,11 @@ class NoteEvent(RhythmicEvent): self.duration.print_ly (printer) +# if hasattr(self, 'color'): +# printer.print_note_color("NoteHead") +# printer.print_note_color("Stem") +# printer.print_note_color("Beam") + class KeySignatureChange (Music): def __init__ (self): Music.__init__ (self) @@ -1462,9 +1790,9 @@ class KeySignatureChange (Music): def format_non_standard_alteration (self, a): alter_dict = { -2: ",DOUBLE-FLAT", - -1.5: ",THREE-Q-FLAT", - -1: ",FLAT", - -0.5: ",SEMI-FLAT", + - 1.5: ",THREE-Q-FLAT", + - 1: ",FLAT", + - 0.5: ",SEMI-FLAT", 0: ",NATURAL", 0.5: ",SEMI-SHARP", 1: ",SHARP", @@ -1489,15 +1817,46 @@ class KeySignatureChange (Music): elif self.non_standard_alterations: alterations = [self.format_non_standard_alteration (a) for a in self.non_standard_alterations] - return "\\set Staff.keyAlterations = #`(%s)" % string.join (alterations, " ") + return "\\set Staff.keySignature = #`(%s)" % string.join (alterations, " ") else: return '' +class ShiftDurations (MusicWrapper): + def __init__ (self): + MusicWrapper.__init__ (self) + self.params = [0,0] + + def set_shift_durations_parameters(self, timeSigChange): + self.params = timeSigChange.get_shift_durations_parameters() + + def print_ly (self, func): + func (' \\shiftDurations #%d #%d ' % tuple(self.params)) + MusicWrapper.print_ly (self, func) + class TimeSignatureChange (Music): def __init__ (self): Music.__init__ (self) - self.fractions = [4,4] + self.fractions = [4, 4] self.style = None + # Used for the --time-signature option of musicxml2ly + self.originalFractions = [4, 4] + + def get_fractions_ratio (self): + """ + Calculate the ratio between the original time fraction and the new one. + Used for the "--time-signature" option. + + @return: The ratio between the two time fractions. + @rtype: float + """ + return (float(self.originalFractions[0])/self.originalFractions[1])*(float(self.fractions[1])/self.fractions[0]) + + def get_shift_durations_parameters (self): + dur = math.ceil(math.log(self.get_fractions_ratio(),2)) + dots = (1/self.get_fractions_ratio())/(math.pow(2,-dur)) + dots = int(math.log(2-dots,0.5)) + return [dur, dots] + def format_fraction (self, frac): if isinstance (frac, list): l = [self.format_fraction (f) for f in frac] @@ -1510,7 +1869,7 @@ class TimeSignatureChange (Music): # Print out the style if we have ome, but the '() should only be # forced for 2/2 or 4/4, since in all other cases we'll get numeric # signatures anyway despite the default 'C signature style! - is_common_signature = self.fractions in ([2,2], [4,4], [4,2]) + is_common_signature = self.fractions in ([2, 2], [4, 4], [4, 2]) if self.style: if self.style == "common": st = "\\defaultTimeSignature" @@ -1536,6 +1895,7 @@ class ClefChange (Music): def octave_modifier (self): return {1: "^8", 2: "^15", -1: "_8", -2: "_15"}.get (self.octave, '') + def clef_name (self): return {('G', 2): "treble", ('G', 1): "french", @@ -1548,9 +1908,10 @@ class ClefChange (Music): ('F', 4): "bass", ('F', 5): "subbass", ("percussion", 2): "percussion", - # Workaround: MuseScore uses PERC instead of percussion + # Workaround: MuseScore uses PERC instead of percussion ("PERC", 2): "percussion", - ("TAB", 5): "tab"}.get ((self.type, self.position), None) + ("TAB", 5): get_tab_clef ()}.get ((self.type, self.position), None) + def ly_expression (self): return '\\clef "%s%s"' % (self.clef_name (), self.octave_modifier ()) @@ -1747,10 +2108,11 @@ class Break (Music): printer.dump ("\\%s" % self.type) class StaffGroup: - def __init__ (self, command = "StaffGroup"): + def __init__ (self, command="StaffGroup"): self.stafftype = command self.id = None self.instrument_name = None + self.sound = None self.short_instrument_name = None self.symbol = None self.spanbar = None @@ -1780,6 +2142,10 @@ class StaffGroup: for c in self.children: if c: c.print_ly (printer) + #Intention: I want to put the content of new StaffGroup in angled brackets (<< >>) + #printer.dump ("test")# test is printed twice at the end of a staffgroup with two staves. + #printer ("test") # test is printed twice at the end of a staffgroup with two staves. + def needs_with (self): needs_with = False needs_with |= self.spanbar == "no" @@ -1787,13 +2153,14 @@ class StaffGroup: needs_with |= self.short_instrument_name != None needs_with |= (self.symbol != None) and (self.symbol != "bracket") return needs_with + def print_ly_context_mods (self, printer): if self.instrument_name or self.short_instrument_name: printer.dump ("\\consists \"Instrument_name_engraver\"") if self.spanbar == "no": printer.dump ("\\override SpanBar #'transparent = ##t") brack = {"brace": "SystemStartBrace", - "none": "SystemStartBar", + "none": "f", "line": "SystemStartSquare"}.get (self.symbol, None) if brack: printer.dump ("systemStartDelimiter = #'%s" % brack) @@ -1805,50 +2172,122 @@ class StaffGroup: self.print_ly_context_mods (printer) for m in self.context_modifications: printer.dump (m) - printer.dump ("}") - - def print_ly_chords (self,printer): + printer.dump ("} <<") + printer.newline () + #print a single << after StaffGroup only when the with-block is not needed. + #This doesn't work. << is printed before and after StaffGroup! + #else: + # printer.dump (" <<") + #prints loads off << before and after StaffGroup and before \set Staff.instrumentName + #elif not needs_with: + # printer.dump (" <<") + + def print_chords(self, printer): try: for [staff_id, voices] in self.part_information: - for [v, lyrics, figuredbass, chordnames] in voices: + for [v, lyrics, figuredbass, chordnames, fretboards] in voices: if chordnames: - printer ('\context ChordNames = "%s" \\%s' % (chordnames, chordnames)) - printer.newline () + printer ('\context ChordNames = "%s" {%s \\%s}' % (chordnames, get_transpose ("string"), chordnames)) + printer.newline() + except TypeError: + return + + def print_fretboards(self, printer): + try: + for [staff_id, voices] in self.part_information: + for [v, lyrics, figuredbass, chordnames, fretboards] in voices: + if fretboards: + printer ('\context FretBoards = "%s" {%s \\%s}' % (fretboards, get_transpose ("string"), fretboards)) + printer.newline() except TypeError: return def print_ly (self, printer): - self.print_ly_chords (printer) + #prints two << before a StaffGroup, one after a StaffGroup and one before each \new Staff + #printer.dump("<<") + #printer.newline () + self.print_chords(printer) + self.print_fretboards(printer) if self.stafftype: printer.dump ("\\new %s" % self.stafftype) + printer.dump ("<<") + printer.newline () + # if there is a width-block << should not be printed after StaffGroup but after the width-block + # this seems to work. It prints \new StaffGroup \with{} <<: +# if self.stafftype == "StaffGroup" and self.print_ly_overrides: + #prints a new line before each new staff type, e.g. before \new StaffGroup and \new Staff... + #printer.newline () +# printer.dump("\\new %s" % self.stafftype) + #self.print_ly_overrides (printer) + #prints a << and a new line after each new staff type. + # printer.dump ("<<") + # printer.newline() + # print a << after all other staff types: + # can't use "else:" because then we get a '\new None' staff type in LilyPond... +# elif self.stafftype == "StaffGroup": +# printer.dump ("\\new %s" % self.stafftype) +# printer.dump ("<<") +# printer.newline () + # << should be printed directly after StaffGroups without a with-block: + # this doesn't work: +# elif self.stafftype == "StaffGroup" and not self.print_ly_overrides: +# printer.dump ("<<") +# printer.newline () + # this is bullshit: +# elif self.stafftype == "StaffGroup" and self.stafftype == "Staff": +# printer.dump ("<<") +# printer.newline () + # this prints \new Staff << for every staff in the score: +# elif self.stafftype: +# printer.dump ("\\new %s" % self.stafftype) +# printer.dump ("<<") +# printer.newline () self.print_ly_overrides (printer) - printer.dump ("<<") - printer.newline () + #printer.dump ("<<") + #printer.newline () if self.stafftype and self.instrument_name: printer.dump ("\\set %s.instrumentName = %s" % (self.stafftype, escape_instrument_string (self.instrument_name))) - printer.newline () + #printer.newline () if self.stafftype and self.short_instrument_name: printer.dump ("\\set %s.shortInstrumentName = %s" % (self.stafftype, escape_instrument_string (self.short_instrument_name))) printer.newline () + if self.sound: + printer.dump( + r'\set {stafftype}.midiInstrument = #"{sound}"'.format( + stafftype=self.stafftype, sound=self.sound)) self.print_ly_contents (printer) printer.newline () - printer.dump (">>") - printer.newline () +# This is a crude hack: In scores with staff groups the closing angled brackets are not printed. +# That's why I added the following two lines. I couldn't find a proper solution. This won't work with scores several staff groups!!! + if self.stafftype == "StaffGroup": + printer.dump (">>") + #printer.dump (">>") + #printer.dump (">>") + #printer.newline () + #printer.dump ("test") #test is printed 4 times in a staffgroup with two staves: once at the end of each staff and twice at the end of the staffgroup. That's not what we want! + #printer.dump ("test") NameError: name 'printer' is not defined + +#test +# def print_staffgroup_closing_brackets (self, printer): #test see class Staff / Score. +# printer.dump ("test") class Staff (StaffGroup): - def __init__ (self, command = "Staff"): + def __init__ (self, command="Staff"): StaffGroup.__init__ (self, command) self.is_group = False self.part = None self.voice_command = "Voice" self.substafftype = None + self.sound = None def needs_with (self): return False + def print_ly_context_mods (self, printer): + #printer.dump ("test") #does nothing. pass def print_ly_contents (self, printer): @@ -1857,39 +2296,59 @@ class Staff (StaffGroup): sub_staff_type = self.substafftype if not sub_staff_type: sub_staff_type = self.stafftype + #printer.dump ("test") #prints test in each staff after the definitions of the instrument name and before the definition of the contexts. + printer.newline() for [staff_id, voices] in self.part_information: + # now comes the real staff definition: if staff_id: printer ('\\context %s = "%s" << ' % (sub_staff_type, staff_id)) else: printer ('\\context %s << ' % sub_staff_type) printer.newline () + printer.dump("\mergeDifferentlyDottedOn\mergeDifferentlyHeadedOn") + printer.newline() n = 0 nr_voices = len (voices) - for [v, lyrics, figuredbass, chordnames] in voices: + for [v, lyrics, figuredbass, chordnames, fretboards] in voices: n += 1 voice_count_text = '' if nr_voices > 1: - voice_count_text = {1: ' \\voiceOne', 2: ' \\voiceTwo', - 3: ' \\voiceThree'}.get (n, ' \\voiceFour') - printer ('\\context %s = "%s" {%s \\%s }' % (self.voice_command, v, voice_count_text, v)) + """ +The next line contains a bug: The voices might not appear in numerical order! Some voices might be missing e.g. if the xml file contains only voice one, three and four, this would result in: \voiceOne, \voiceTwo and \voiceThree. This causes wrong stem directions and collisions. + """ + voice_count_text = {1: ' \\voiceOne', 2: ' \\voiceTwo', 3: ' \\voiceThree'}.get (n, ' \\voiceFour') + printer ('\\context %s = "%s" {%s %s \\%s }' % (self.voice_command, v, get_transpose ("string"), voice_count_text, v)) printer.newline () - + lyrics_id = 1 for l in lyrics: - printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (v,l)) + printer ('\\new Lyrics \\lyricsto "%s" { \\set stanza = "%s." \\%s }' % (v, lyrics_id, l)) + lyrics_id += 1 printer.newline() if figuredbass: printer ('\context FiguredBass = "%s" \\%s' % (figuredbass, figuredbass)) printer ('>>') + #printer.dump ("test") #prints test after each definition of a context. + #printer.newline () + #printer.dump ("test") #prints test after each definition of a context. def print_ly (self, printer): if self.part_information and len (self.part_information) > 1: self.stafftype = "PianoStaff" self.substafftype = "Staff" + #printer.dump ('test') StaffGroup.print_ly (self, printer) + #StaffGroup.print_staffgroup_closing_brackets (self, printer) prints test after each definition of a staff + printer.dump ('>>') + #printer.dump ("test") #prints test after each definition of a context. + printer.newline () + #StaffGroup.print_staffgroup_closing_brackets(self, printer) #prints test after each definition of a staff. + #printer.dump ("test")# NameError: name 'printer' is not defined + #StaffGroup.print_staffgroup_closing_brackets() #TypeError: unbound method print_staffgroup_closing_brackets() must be called with StaffGroup instance as first argument (got nothing instead) + class TabStaff (Staff): - def __init__ (self, command = "TabStaff"): + def __init__ (self, command="TabStaff"): Staff.__init__ (self, command) self.string_tunings = [] self.tablature_format = None @@ -1908,7 +2367,7 @@ class TabStaff (Staff): class DrumStaff (Staff): - def __init__ (self, command = "DrumStaff"): + def __init__ (self, command="DrumStaff"): Staff.__init__ (self, command) self.drum_style_table = None self.voice_command = "DrumVoice" @@ -1919,11 +2378,18 @@ class DrumStaff (Staff): printer.dump ("}") class RhythmicStaff (Staff): - def __init__ (self, command = "RhythmicStaff"): + def __init__ (self, command="RhythmicStaff"): Staff.__init__ (self, command) +#Test +#def print_staffgroup_closing_brackets (self, printer): #test see class Score / class Staff +# printer.dump ("test") + class Score: def __init__ (self): + """ + Constructs a new Score object. + """ self.contents = None self.create_midi = False @@ -1934,28 +2400,67 @@ class Score: if self.contents: self.contents.set_part_information (part_id, staves_info) + def set_tempo (self, tempo): + """ + Set the tempo attribute of the Score. + This attribute can be used in L{print_ly} for the midi output (see L{musicxml.Sound}). + + @param tempo: The value of the tempo, in beats per minute. + @type tempo: String + """ + self.tempo = tempo + #Test +# def print_staffgroup_closing_brackets (self, printer): #test see class Score / class Staff +# printer.dump ("test") + def print_ly (self, printer): - self.create_midi = get_create_midi () - printer.dump ("\\score {"); + """ + Print the content of the score to the printer, in lilypond format. + + @param printer: A printer given to display correctly the output. + @type printer: L{Output_printer<musicexp.Output_printer>} + """ + self.create_midi = get_create_midi() + printer.dump("\\score {") + printer.newline () + #prints opening <<: + printer.dump ('<<') printer.newline () if self.contents: - self.contents.print_ly (printer); - printer.dump ("\\layout {}"); + self.contents.print_ly(printer) + #printer.dump ("test") prints test once before the >> of the score block, independent of the existence of a staffgroup. + #if StaffGroup == False: # True or False: nothing happens. + # printer.dump ('>>') + printer.dump ('>>') printer.newline () - if not self.create_midi: - printer.dump ("% To create MIDI output, uncomment the following line:"); - printer.newline (); - printer.dump ("% "); - printer.dump ("\\midi {}"); + #StaffGroup.print_staffgroup_closing_brackets(self, printer) #TypeError: unbound method print_staffgroup_closing_brackets() must be called with StaffGroup instance as first argument (got Score instance instead) + #print_staffgroup_closing_brackets(self, printer) #NameError: global name 'print_staffgroup_closing_brackets' is not defined. prints test once before the >> of the score block, independent of the existence of a staffgroup. + printer.dump ("\\layout {}") printer.newline () - printer.dump ("}"); + # If the --midi option was not passed to musicxml2ly, that comments the "midi" line + if self.create_midi: + printer.dump ("}") + printer.newline() + printer.dump("\\score {") + printer.newline () + printer.dump("\\unfoldRepeats \\articulate {") + printer.newline () + self.contents.print_ly(printer) + printer.dump("}") + printer.newline () + else: + printer.dump ("% To create MIDI output, uncomment the following line:") + printer.newline () + printer.dump ("% ") + printer.dump ("\\midi {\\tempo 4 = "+self.tempo+" }") + printer.newline () + printer.dump ("}") printer.newline () - def test_pitch (): bflat = Pitch() bflat.alteration = -1 - bflat.step = 6 + bflat.step = 6 bflat.octave = -1 fifth = Pitch() fifth.step = 4 @@ -1965,7 +2470,7 @@ def test_pitch (): print bflat.semitones() - print bflat.transposed (fifth), bflat.transposed (fifth).transposed (fifth) + print bflat.transposed (fifth), bflat.transposed (fifth).transposed (fifth) print bflat.transposed (fifth).transposed (fifth).transposed (fifth) print bflat.semitones(), 'down' @@ -2037,8 +2542,8 @@ def test_expr (): tonic.step = 2 tonic.alteration = -2 n = KeySignatureChange() - n.tonic=tonic.copy() - n.scale = [0, 0, -2, 0, 0,-2,-2] + n.tonic = tonic.copy() + n.scale = [0, 0, -2, 0, 0, -2, -2] evc.insert_around (None, n, 0) m.insert_around (None, evc, 0) @@ -2054,11 +2559,10 @@ if __name__ == '__main__': expr = test_expr() expr.set_start (Rational (0)) print expr.ly_expression() - start = Rational (0,4) - stop = Rational (4,2) + start = Rational (0, 4) + stop = Rational (4, 2) def sub(x, start=start, stop=stop): - ok = x.start >= start and x.start +x.get_length() <= stop + ok = x.start >= start and x.start + x.get_length() <= stop return ok print expr.lisp_sub_expression(sub) - diff --git a/python/musicxml.py b/python/musicxml.py index 6eb3b45aba..c4635c6aca 100644 --- a/python/musicxml.py +++ b/python/musicxml.py @@ -6,45 +6,18 @@ import re import sys import copy import lilylib as ly +import warnings _ = ly._ - -def escape_ly_output_string (input_string): - return_string = input_string - needs_quotes = not re.match (u"^[a-zA-ZäöüÜÄÖßñ]*$", return_string); - if needs_quotes: - return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\"" - return return_string - - -def musicxml_duration_to_log (dur): - return {'256th': 8, - '128th': 7, - '64th': 6, - '32nd': 5, - '16th': 4, - 'eighth': 3, - 'quarter': 2, - 'half': 1, - 'whole': 0, - 'breve': -1, - 'longa': -2, - 'long': -2}.get (dur, 0) - - - -def interpret_alter_element (alter_elm): - alter = 0 - if alter_elm: - val = eval(alter_elm.get_text ()) - if type (val) in (int, float): - alter = val - return alter +import musicexp +import musicxml2ly_conversion +import utilities class Xml_node: - def __init__ (self): + + def __init__(self): self._children = [] self._data = None self._original = None @@ -52,581 +25,1261 @@ class Xml_node: self._parent = None self._attribute_dict = {} - def get_parent (self): + def get_parent(self): return self._parent - def is_first (self): - return self._parent.get_typed_children (self.__class__)[0] == self + def is_first(self): + return self._parent.get_typed_children(self.__class__)[0] == self - def original (self): + def original(self): return self._original - def get_name (self): + def get_name(self): return self._name - def get_text (self): + def get_text(self): if self._data: return self._data if not self._children: return '' - return ''.join ([c.get_text () for c in self._children]) + return ''.join([c.get_text() for c in self._children]) - def message (self, msg): - ly.warning (msg) + def message(self, msg): + ly.warning(msg) p = self while p: - ly.progress (' In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items ()]))) - p = p.get_parent () + ly.progress(' In: <%s %s>\n' %(p._name, ' '.join(['%s=%s' % item for item in p._attribute_dict.items()]))) + p = p.get_parent() - def dump (self, indent = ''): - ly.debug_output ('%s<%s%s>' % (indent, self._name, ''.join ([' %s=%s' % item for item in self._attribute_dict.items ()]))) - non_text_children = [c for c in self._children if not isinstance (c, Hash_text)] + def dump(self, indent=''): + ly.debug_output('%s<%s%s>' %(indent, self._name, ''.join([' %s=%s' % item for item in self._attribute_dict.items()]))) + non_text_children = [c for c in self._children if not isinstance(c, Hash_text)] if non_text_children: - ly.debug_output ('\n') + ly.debug_output('\n') for c in self._children: - c.dump (indent + " ") + c.dump(indent + " ") if non_text_children: - ly.debug_output (indent) - ly.debug_output ('</%s>\n' % self._name) + ly.debug_output(indent) + ly.debug_output('</%s>\n' % self._name) - def get_typed_children (self, klass): + def get_typed_children(self, klass): if not klass: return [] else: return [c for c in self._children if isinstance(c, klass)] - def get_named_children (self, nm): - return self.get_typed_children (get_class (nm)) + def get_named_children(self, nm): + return self.get_typed_children(get_class(nm)) - def get_named_child (self, nm): - return self.get_maybe_exist_named_child (nm) + def get_named_child(self, nm): + return self.get_maybe_exist_named_child(nm) - def get_children (self, predicate): + def get_children(self, predicate): return [c for c in self._children if predicate(c)] - def get_all_children (self): + def get_all_children(self): return self._children - def get_maybe_exist_named_child (self, name): - return self.get_maybe_exist_typed_child (get_class (name)) + def get_maybe_exist_named_child(self, name): + return self.get_maybe_exist_typed_child(get_class(name)) - def get_maybe_exist_typed_child (self, klass): - cn = self.get_typed_children (klass) - if len (cn)==0: + def get_maybe_exist_typed_child(self, klass): + cn = self.get_typed_children(klass) + if len(cn) == 0: return None - elif len (cn) == 1: - return cn[0] else: - raise "More than 1 child", klass - - def get_unique_typed_child (self, klass): + try: + assert len(cn) == 1 + return cn[0] + except: + msg = ' '.join( + ['more than one child of class ', + klass.__name__, + '...all but the first will be ignored!']) + warnings.warn(msg) + return cn[0] + + def get_unique_typed_child(self, klass): cn = self.get_typed_children(klass) - if len (cn) <> 1: - ly.error (self.__dict__) - raise 'Child is not unique for', (klass, 'found', cn) + if len(cn) <> 1: + ly.error(self.__dict__) + raise 'Child is not unique for',(klass, 'found', cn) return cn[0] - def get_named_child_value_number (self, name, default): - n = self.get_maybe_exist_named_child (name) + def get_named_child_value_number(self, name, default): + n = self.get_maybe_exist_named_child(name) if n: - return string.atoi (n.get_text()) + return int(n.get_text()) else: return default -class Music_xml_node (Xml_node): - def __init__ (self): - Xml_node.__init__ (self) - self.duration = Rational (0) - self.start = Rational (0) +class Music_xml_node(Xml_node): + def __init__(self): + Xml_node.__init__(self) + self.duration = Rational(0) + self.start = Rational(0) + self.converted = False + + +class Music_xml_spanner(Music_xml_node): -class Work (Xml_node): - def get_work_information (self, tag): - wt = self.get_maybe_exist_named_child (tag) + def get_type(self): + if hasattr(self, 'type'): + return self.type + else: + return 0 + + def get_size(self): + if hasattr(self, 'size'): + return int(self.size) + else: + return 0 + + +class Measure_element(Music_xml_node): + + def get_voice_id(self): + voice_id = self.get_maybe_exist_named_child('voice') + if voice_id: + return voice_id.get_text() + else: + return None + + def is_first(self): + # Look at all measure elements(previously we had self.__class__, which + # only looked at objects of the same type! + cn = self._parent.get_typed_children(Measure_element) + # But only look at the correct voice; But include Attributes, too, which + # are not tied to any particular voice + cn = [c for c in cn if(c.get_voice_id() == self.get_voice_id()) or isinstance(c, Attributes)] + return cn[0] == self + + +class Work(Xml_node): + + def get_work_information(self, tag): + wt = self.get_maybe_exist_named_child(tag) if wt: - return wt.get_text () + return wt.get_text() else: return '' - def get_work_title (self): - return self.get_work_information ('work-title') - def get_work_number (self): - return self.get_work_information ('work-number') - def get_opus (self): - return self.get_work_information ('opus') + def get_work_title(self): + return self.get_work_information('work-title') -class Identification (Xml_node): - def get_rights (self): - rights = self.get_named_children ('rights') + def get_work_number(self): + return self.get_work_information('work-number') + + # def get_opus(self): + # return self.get_work_information('opus') + + +class Identification(Xml_node): + + def get_rights(self): + rights = self.get_named_children('rights') ret = [] for r in rights: - ret.append (r.get_text ()) - return string.join (ret, "\n") + text = r.get_text() + # if this Xml_node has an attribute, such as 'type="words"', + # include it in the header. Otherwise, it is assumed that + # the text contents of this node looks something like this: + # 'Copyright: X.Y.' and thus already contains the relevant + # information. + if hasattr(r, 'type'): + rights_type = r.type.title() # capitalize first letter + result = ''.join([rights_type, ': ', text]) + ret.append(result) + else: + ret.append(text) + return string.join(ret, "\n") - # get contents of the source-element (usually used for publishing information). (These contents are saved in a custom variable named "source" in the header of the .ly file.) - def get_source (self): - source = self.get_named_children ('source') + # get contents of the source-element(usually used for publishing information).(These contents are saved in a custom variable named "source" in the header of the .ly file.) + def get_source(self): + source = self.get_named_children('source') ret = [] for r in source: - ret.append (r.get_text ()) - return string.join (ret, "\n") + ret.append(r.get_text()) + return string.join(ret, "\n") - def get_creator (self, type): - creators = self.get_named_children ('creator') + def get_creator(self, type): + creators = self.get_named_children('creator') # return the first creator tag that has the particular type for i in creators: - if hasattr (i, 'type') and i.type == type: - return i.get_text () + if hasattr(i, 'type') and i.type == type: + return i.get_text() return None - def get_composer (self): - c = self.get_creator ('composer') + def get_composer(self): + c = self.get_creator('composer') if c: return c - creators = self.get_named_children ('creator') + creators = self.get_named_children('creator') # return the first creator tag that has no type at all for i in creators: - if not hasattr (i, 'type'): - return i.get_text () + if not hasattr(i, 'type'): + return i.get_text() return None - def get_arranger (self): - return self.get_creator ('arranger') - def get_editor (self): - return self.get_creator ('editor') - def get_poet (self): - v = self.get_creator ('lyricist') + + def get_arranger(self): + return self.get_creator('arranger') + + def get_editor(self): + return self.get_creator('editor') + + def get_poet(self): + v = self.get_creator('lyricist') if v: return v - v = self.get_creator ('poet') + v = self.get_creator('poet') return v - def get_encoding_information (self, type): - enc = self.get_named_children ('encoding') + def get_encoding_information(self, type): + enc = self.get_named_children('encoding') if enc: - children = enc[0].get_named_children (type) + children = enc[0].get_named_children(type) if children: - return children[0].get_text () + return children[0].get_text() else: return None - def get_encoding_software (self): - return self.get_encoding_information ('software') - def get_encoding_date (self): - return self.get_encoding_information ('encoding-date') - def get_encoding_person (self): - return self.get_encoding_information ('encoder') - def get_encoding_description (self): - return self.get_encoding_information ('encoding-description') - - def get_encoding_software_list (self): - enc = self.get_named_children ('encoding') + def get_encoding_software(self): + return self.get_encoding_information('software') + + def get_encoding_date(self): + return self.get_encoding_information('encoding-date') + + def get_encoding_person(self): + return self.get_encoding_information('encoder') + + def get_encoding_description(self): + return self.get_encoding_information('encoding-description') + + def get_encoding_software_list(self): + enc = self.get_named_children('encoding') software = [] for e in enc: - softwares = e.get_named_children ('software') + softwares = e.get_named_children('software') for s in softwares: - software.append (s.get_text ()) + software.append(s.get_text()) return software - def get_file_description (self): - misc = self.get_named_children ('miscellaneous') + def get_file_description(self): + misc = self.get_named_children('miscellaneous') for m in misc: - misc_fields = m.get_named_children ('miscellaneous-field') + misc_fields = m.get_named_children('miscellaneous-field') for mf in misc_fields: - if hasattr (mf, 'name') and mf.name == 'description': - return mf.get_text () + if hasattr(mf, 'name') and mf.name == 'description': + return mf.get_text() return None -class Duration (Music_xml_node): - def get_length (self): - dur = int (self.get_text ()) * Rational (1,4) + +class Credit(Xml_node): + + def get_type(self): + type = self.get_maybe_exist_named_child('credit-type') + if(type != None): + return type.get_text() + else: + return None + + def find_type(self, credits): + sizes = self.get_font_sizes(credits) + sizes.sort(reverse=True) + ys = self.get_default_ys(credits) + ys.sort(reverse=True) + xs = self.get_default_xs(credits) + xs.sort(reverse=True) + + # Words child of the self credit-element + words = self.get_maybe_exist_named_child('credit-words') + size = None + x = None + y = None + halign = None + valign = None + justify = None + if(words != None): + if hasattr(words, 'font-size'): + size = utilities.string_to_integer(getattr(words, 'font-size')) + if hasattr(words, 'default-x'): + x = round(float(getattr(words, 'default-x'))) + if hasattr(words, 'default-y'): + y = round(float(getattr(words, 'default-y'))) + if hasattr(words, 'halign'): + halign = getattr(words, 'halign') + if hasattr(words, 'valign'): + valign = getattr(words, 'valign') + if hasattr(words, 'justify'): + justify = getattr(words, 'justify') + if(size and size == max(sizes) and y and y == max(ys) and(justify or halign) and(justify == 'center' or halign == 'center')): + return 'title' + elif((y and y > min(ys) and y < max(ys)) and((justify or halign) and(justify == 'center' or halign == 'center'))): + return 'subtitle' + elif((justify or halign) and(justify == 'left' or halign == 'left') and(not(x) or x == min(xs))): + return 'lyricist' + elif((justify or halign) and(justify == 'right' or halign == 'right') and(not(x) or x == max(xs))): + return 'composer' + elif(size and size == min(sizes) and y == min(ys)): + return 'rights' + # Special cases for Finale NotePad + elif((valign and(valign == 'top')) and(y and y == ys[1])): + return 'subtitle' + elif((valign and(valign == 'top')) and(x and x == min(xs))): + return 'lyricist' + elif((valign and(valign == 'top')) and(y and y == min(ys))): + return 'rights' + # Other special cases + elif((valign and(valign == 'bottom'))): + return 'rights' + elif(len([item for item in range(len(ys)) if ys[item] == y]) == 2): + # The first one is the composer, the second one is the lyricist + return 'composer' + + return None # no type recognized + + def get_font_sizes(self, credits): + sizes = [] + for cred in credits: + words = cred.get_maybe_exist_named_child('credit-words') + if((words != None) and hasattr(words, 'font-size')): + sizes.append(getattr(words, 'font-size')) + return map(utilities.string_to_integer, sizes) + + def get_default_xs(self, credits): + default_xs = [] + for cred in credits: + words = cred.get_maybe_exist_named_child('credit-words') + if((words != None) and hasattr(words, 'default-x')): + default_xs.append(getattr(words, 'default-x')) + return map(round, map(float, default_xs)) + + def get_default_ys(self, credits): + default_ys = [] + for cred in credits: + words = cred.get_maybe_exist_named_child('credit-words') + if((words != None) and hasattr(words, 'default-y')): + default_ys.append(getattr(words, 'default-y')) + return map(round, map(float, default_ys)) + + def get_text(self): + words = self.get_maybe_exist_named_child('credit-words') + if(words != None): + return words.get_text() + else: + return '' + + +class Duration(Music_xml_node): + + def get_length(self): + dur = int(self.get_text()) * Rational(1, 4) return dur -class Hash_comment (Music_xml_node): - pass -class Hash_text (Music_xml_node): - def dump (self, indent = ''): - ly.debug_output ('%s' % string.strip (self._data)) - -class Pitch (Music_xml_node): - def get_step (self): - ch = self.get_unique_typed_child (get_class (u'step')) - step = ch.get_text ().strip () + +class Hash_text(Music_xml_node): + + def dump(self, indent=''): + ly.debug_output('%s' % string.strip(self._data)) + + +class Pitch(Music_xml_node): + + def get_step(self): + ch = self.get_unique_typed_child(get_class(u'step')) + step = ch.get_text().strip() return step - def get_octave (self): - ch = self.get_unique_typed_child (get_class (u'octave')) - octave = ch.get_text ().strip () - return int (octave) - - def get_alteration (self): - ch = self.get_maybe_exist_typed_child (get_class (u'alter')) - return interpret_alter_element (ch) - -class Unpitched (Music_xml_node): - def get_step (self): - ch = self.get_unique_typed_child (get_class (u'display-step')) - step = ch.get_text ().strip () + + def get_octave(self): + ch = self.get_unique_typed_child(get_class(u'octave')) + octave = ch.get_text().strip() + return int(octave) + + def get_alteration(self): + ch = self.get_maybe_exist_typed_child(get_class(u'alter')) + return utilities.interpret_alter_element(ch) + + def to_lily_object(self): + p = musicexp.Pitch() + p.alteration = self.get_alteration() + p.step = musicxml2ly_conversion.musicxml_step_to_lily(self.get_step()) + p.octave = self.get_octave() - 4 + return p + + +class Unpitched(Music_xml_node): + + def get_step(self): + ch = self.get_unique_typed_child(get_class(u'display-step')) + step = ch.get_text().strip() return step - def get_octave (self): - ch = self.get_unique_typed_child (get_class (u'display-octave')) + def get_octave(self): + ch = self.get_unique_typed_child(get_class(u'display-octave')) if ch: - octave = ch.get_text ().strip () - return int (octave) + octave = ch.get_text().strip() + return int(octave) else: return None -class Measure_element (Music_xml_node): - def get_voice_id (self): - voice_id = self.get_maybe_exist_named_child ('voice') - if voice_id: - return voice_id.get_text () - else: - return None + def to_lily_object(self): + p = None + step = self.get_step() + if step: + p = musicexp.Pitch() + p.step = musicxml2ly_conversion.musicxml_step_to_lily(step) + octave = self.get_octave() + if octave and p: + p.octave = octave - 4 + return p - def is_first (self): - # Look at all measure elements (previously we had self.__class__, which - # only looked at objects of the same type! - cn = self._parent.get_typed_children (Measure_element) - # But only look at the correct voice; But include Attributes, too, which - # are not tied to any particular voice - cn = [c for c in cn if (c.get_voice_id () == self.get_voice_id ()) or isinstance (c, Attributes)] - return cn[0] == self -class Attributes (Measure_element): - def __init__ (self): - Measure_element.__init__ (self) +class Attributes(Measure_element): + + def __init__(self): + Measure_element.__init__(self) self._dict = {} self._original_tag = None self._time_signature_cache = None - def is_first (self): - cn = self._parent.get_typed_children (self.__class__) + def is_first(self): + cn = self._parent.get_typed_children(self.__class__) if self._original_tag: return cn[0] == self._original_tag else: return cn[0] == self - def set_attributes_from_previous (self, dict): - self._dict.update (dict) + def set_attributes_from_previous(self, dict): + self._dict.update(dict) - def read_self (self): - for c in self.get_all_children (): + def read_self(self): + for c in self.get_all_children(): self._dict[c.get_name()] = c - def get_named_attribute (self, name): - return self._dict.get (name) + def get_named_attribute(self, name): + return self._dict.get(name) - def single_time_sig_to_fraction (self, sig): - if len (sig) < 2: + def single_time_sig_to_fraction(self, sig): + if len(sig) < 2: return 0 n = 0 for i in sig[0:-1]: n += i - return Rational (n, sig[-1]) + return Rational(n, sig[-1]) - def get_measure_length (self): - sig = self.get_time_signature () - if not sig or len (sig) == 0: + def get_measure_length(self): + sig = self.get_time_signature() + if not sig or len(sig) == 0: return 1 - if isinstance (sig[0], list): + if isinstance(sig[0], list): # Complex compound time signature l = 0 for i in sig: - l += self.single_time_sig_to_fraction (i) + l += self.single_time_sig_to_fraction(i) return l else: - # Simple (maybe compound) time signature of the form (beat, ..., type) - return self.single_time_sig_to_fraction (sig) + # Simple(maybe compound) time signature of the form(beat, ..., type) + return self.single_time_sig_to_fraction(sig) return 0 - def get_time_signature (self): - "Return time sig as a (beat, beat-type) tuple. For compound signatures," - "return either (beat, beat,..., beat-type) or ((beat,..., type), " + def get_time_signature(self): + "Return time sig as a(beat, beat-type) tuple. For compound signatures," + "return either(beat, beat,..., beat-type) or((beat,..., type), " "(beat,..., type), ...)." if self._time_signature_cache: return self._time_signature_cache try: - mxl = self.get_named_attribute ('time') + mxl = self.get_named_attribute('time') if not mxl: return None - if mxl.get_maybe_exist_named_child ('senza-misura'): + if mxl.get_maybe_exist_named_child('senza-misura'): # TODO: Handle pieces without a time signature! - ly.warning (_ ("Senza-misura time signatures are not yet supported!")) - return (4, 4) + ly.warning(_("Senza-misura time signatures are not yet supported!")) + return(4, 4) else: signature = [] current_sig = [] - for i in mxl.get_all_children (): - if isinstance (i, Beats): - beats = string.split (i.get_text ().strip (), "+") - current_sig = [int (j) for j in beats] - elif isinstance (i, BeatType): - current_sig.append (int (i.get_text ())) - signature.append (current_sig) + for i in mxl.get_all_children(): + if isinstance(i, Beats): + beats = string.split(i.get_text().strip(), "+") + current_sig = [int(j) for j in beats] + elif isinstance(i, BeatType): + current_sig.append(int(i.get_text())) + signature.append(current_sig) current_sig = [] - if isinstance (signature[0], list) and len (signature) == 1: + if isinstance(signature[0], list) and len(signature) == 1: signature = signature[0] self._time_signature_cache = signature return signature - except (KeyError, ValueError): - self.message (_ ("Unable to interpret time signature! Falling back to 4/4.")) - return (4, 4) + except(KeyError, ValueError): + self.message(_("Unable to interpret time signature! Falling back to 4/4.")) + return(4, 4) - # returns clef information in the form ("cleftype", position, octave-shift) - def get_clef_information (self): + # returns clef information in the form("cleftype", position, octave-shift) + def get_clef_information(self): clefinfo = ['G', 2, 0] - mxl = self.get_named_attribute ('clef') + mxl = self.get_named_attribute('clef') if not mxl: return clefinfo - sign = mxl.get_maybe_exist_named_child ('sign') + sign = mxl.get_maybe_exist_named_child('sign') if sign: clefinfo[0] = sign.get_text() - line = mxl.get_maybe_exist_named_child ('line') + line = mxl.get_maybe_exist_named_child('line') if line: - clefinfo[1] = string.atoi (line.get_text ()) - octave = mxl.get_maybe_exist_named_child ('clef-octave-change') + clefinfo[1] = int(line.get_text()) + octave = mxl.get_maybe_exist_named_child('clef-octave-change') if octave: - clefinfo[2] = string.atoi (octave.get_text ()) + clefinfo[2] = int(octave.get_text()) return clefinfo - def get_key_signature (self): - "return (fifths, mode) tuple if the key signatures is given as " + def get_key_signature(self): + "return(fifths, mode) tuple if the key signatures is given as " "major/minor in the Circle of fifths. Otherwise return an alterations" "list of the form [[step,alter<,octave>], [step,alter<,octave>], ...], " "where the octave values are optional." - key = self.get_named_attribute ('key') + key = self.get_named_attribute('key') if not key: return None - fifths_elm = key.get_maybe_exist_named_child ('fifths') + fifths_elm = key.get_maybe_exist_named_child('fifths') if fifths_elm: - mode_node = key.get_maybe_exist_named_child ('mode') + mode_node = key.get_maybe_exist_named_child('mode') mode = None if mode_node: - mode = mode_node.get_text () + mode = mode_node.get_text() if not mode or mode == '': mode = 'major' - fifths = int (fifths_elm.get_text ()) + fifths = int(fifths_elm.get_text()) # TODO: Shall we try to convert the key-octave and the cancel, too? - return (fifths, mode) + return(fifths, mode) else: alterations = [] current_step = 0 - for i in key.get_all_children (): - if isinstance (i, KeyStep): - current_step = i.get_text ().strip () - elif isinstance (i, KeyAlter): - alterations.append ([current_step, interpret_alter_element (i)]) - elif isinstance (i, KeyOctave): + for i in key.get_all_children(): + if isinstance(i, KeyStep): + current_step = i.get_text().strip() + elif isinstance(i, KeyAlter): + alterations.append([current_step, utilities.interpret_alter_element(i)]) + elif isinstance(i, KeyOctave): nr = -1 - if hasattr (i, 'number'): - nr = int (i.number) - if (nr > 0) and (nr <= len (alterations)): + if hasattr(i, 'number'): + nr = int(i.number) + if(nr > 0) and(nr <= len(alterations)): # MusicXML Octave 4 is middle C -> shift to 0 - alterations[nr-1].append (int (i.get_text ())-4) + alterations[nr - 1].append(int(i.get_text()) - 4) else: - i.message (_ ("Key alteration octave given for a " - "non-existing alteration nr. %s, available numbers: %s!") % (nr, len(alterations))) + i.message(_("Key alteration octave given for a " + "non-existing alteration nr. %s, available numbers: %s!") %(nr, len(alterations))) return alterations - def get_transposition (self): - return self.get_named_attribute ('transpose') + def get_transposition(self): + return self.get_named_attribute('transpose') + + +class Barline(Measure_element): + + def to_lily_object(self): + # retval contains all possible markers in the order: + # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending + retval = {} + bartype_element = self.get_maybe_exist_named_child("bar-style") + repeat_element = self.get_maybe_exist_named_child("repeat") + ending_element = self.get_maybe_exist_named_child("ending") + + bartype = None + if bartype_element: + bartype = bartype_element.get_text() + + if repeat_element and hasattr(repeat_element, 'direction'): + repeat = musicxml2ly_conversion.RepeatMarker() + repeat.direction = {"forward":-1, "backward": 1}.get( + repeat_element.direction, 0) + + if((repeat_element.direction == "forward" and bartype == "heavy-light") or + (repeat_element.direction == "backward" and bartype == "light-heavy")): + bartype = None + if hasattr(repeat_element, 'times'): + try: + repeat.times = int(repeat_element.times) + except ValueError: + repeat.times = 2 + repeat.event = self + if repeat.direction == -1: + retval[3] = repeat + else: + retval[1] = repeat + + if ending_element and hasattr(ending_element, 'type'): + ending = musicxml2ly_conversion.EndingMarker() + ending.direction = {"start":-1, "stop": 1, "discontinue": 1}.get( + ending_element.type, 0) + ending.event = self + if ending.direction == -1: + retval[4] = ending + else: + retval[0] = ending + # TODO. ending number="" -class KeyAlter (Music_xml_node): - pass -class KeyStep (Music_xml_node): - pass -class KeyOctave (Music_xml_node): - pass + if bartype: + b = musicexp.BarLine() + b.type = bartype + retval[2] = b + return retval.values() -class Barline (Measure_element): - pass -class BarStyle (Music_xml_node): - pass -class Partial (Measure_element): - def __init__ (self, partial): - Measure_element.__init__ (self) + +class Partial(Measure_element): + def __init__(self, partial): + Measure_element.__init__(self) self.partial = partial -class Note (Measure_element): - def __init__ (self): - Measure_element.__init__ (self) + +class Stem(Music_xml_node): + + stem_value_dict = { + 'down': 'stemDown', + 'up': 'stemUp', + 'double': None, # TODO: Implement + 'none': 'stemNeutral' + } + + def to_stem_event(self): + values = [] + value = self.stem_value_dict.get(self.get_text(), None) + stem_value = musicexp.StemEvent() + if value: + stem_value.value = value + values.append(stem_value) + return values + + def to_stem_style_event(self): + styles = [] + style_elm = musicexp.StemstyleEvent() + if hasattr(self, 'color'): + style_elm.color = utilities.hex_to_color(getattr(self, 'color')) + if(style_elm.color != None): + styles.append(style_elm) + return styles + + +class Notehead(Music_xml_node): + + notehead_styles_dict = { + 'slash': '\'slash', + 'triangle': '\'triangle', + 'diamond': '\'diamond', + 'square': '\'la', # TODO: Proper squared note head + 'cross': None, # TODO: + shaped note head + 'x': '\'cross', + 'circle-x': '\'xcircle', + 'inverted triangle': None, # TODO: Implement + 'arrow down': None, # TODO: Implement + 'arrow up': None, # TODO: Implement + 'slashed': None, # TODO: Implement + 'back slashed': None, # TODO: Implement + 'normal': None, + 'cluster': None, # TODO: Implement + 'none': '#f', + 'do': '\'do', + 're': '\'re', + 'mi': '\'mi', + 'fa': '\'fa', + 'so': None, + 'la': '\'la', + 'ti': '\'ti', + } + + def to_lily_object(self): #function changed: additionally processcolor attribute + styles = [] + + # Notehead style + key = self.get_text().strip() + style = self.notehead_styles_dict.get(key, None) + event = musicexp.NotestyleEvent() + if style: + event.style = style + if hasattr(self, 'filled'): + event.filled =(getattr(self, 'filled') == "yes") + if hasattr(self, 'color'): + event.color = utilities.hex_to_color(getattr(self, 'color')) + if event.style or(event.filled != None) or(event.color != None): + styles.append(event) + # parentheses + if hasattr(self, 'parentheses') and(self.parentheses == "yes"): + styles.append(musicexp.ParenthesizeEvent()) + + return styles + + +class Note(Measure_element): + + drumtype_dict = { + 'Acoustic Snare Drum': 'acousticsnare', + 'Side Stick': 'sidestick', + 'Open Triangle': 'opentriangle', + 'Mute Triangle': 'mutetriangle', + 'Tambourine': 'tambourine', + 'Bass Drum': 'bassdrum', + } + + def __init__(self): + Measure_element.__init__(self) self.instrument_name = '' self._after_grace = False - def is_grace (self): - return self.get_maybe_exist_named_child (u'grace') - def is_after_grace (self): + self._duration = 1 + + def is_grace(self): + return self.get_maybe_exist_named_child(u'grace') + + def is_after_grace(self): if not self.is_grace(): return False; - gr = self.get_maybe_exist_typed_child (Grace) - return self._after_grace or hasattr (gr, 'steal-time-previous'); + gr = self.get_maybe_exist_typed_child(Grace) + return self._after_grace or hasattr(gr, 'steal-time-previous'); - def get_duration_log (self): - ch = self.get_maybe_exist_named_child (u'type') + def get_duration_log(self): + ch = self.get_maybe_exist_named_child(u'type') if ch: - log = ch.get_text ().strip() - return musicxml_duration_to_log (log) - elif self.get_maybe_exist_named_child (u'grace'): + log = ch.get_text().strip() + return utilities.musicxml_duration_to_log(log) + elif self.get_maybe_exist_named_child(u'grace'): # FIXME: is it ok to default to eight note for grace notes? return 3 else: return None - def get_duration_info (self): - log = self.get_duration_log () + def get_duration_info(self): + log = self.get_duration_log() if log != None: - dots = len (self.get_typed_children (Dot)) - return (log, dots) + dots = len(self.get_typed_children(Dot)) + return(log, dots) else: return None - def get_factor (self): + def get_factor(self): return 1 - def get_pitches (self): - return self.get_typed_children (get_class (u'pitch')) + def get_pitches(self): + return self.get_typed_children(get_class(u'pitch')) + + def set_notehead_style(self, event): + noteheads = self.get_named_children('notehead') + for nh in noteheads: + styles = nh.to_lily_object() + for style in styles: + event.add_associated_event(style) + + def set_stem_directions(self, event): + stems = self.get_named_children('stem') + for stem in stems: + values = stem.to_stem_event() + for v in values: + event.add_associated_event(v) + + def set_stem_style(self, event): + stems = self.get_named_children('stem') + for stem in stems: + styles = stem.to_stem_style_event() + for style in styles: + event.add_associated_event(style) + + def initialize_duration(self): + from musicxml2ly_conversion import rational_to_lily_duration + from musicexp import Duration + # if the note has no Type child, then that method returns None. In that case, + # use the <duration> tag instead. If that doesn't exist, either -> Error + dur = self.get_duration_info() + if dur: + d = Duration() + d.duration_log = dur[0] + d.dots = dur[1] + # Grace notes by specification have duration 0, so no time modification + # factor is possible. It even messes up the output with *0/1 + if not self.get_maybe_exist_typed_child(Grace): + d.factor = self._duration / d.get_length() + return d + else: + if self._duration > 0: + return rational_to_lily_duration(self._duration) + else: + self.message( + _("Encountered note at %s without type and duration(=%s)") \ + %(mxl_note.start, mxl_note._duration)) + return None + + def initialize_pitched_event(self): + mxl_pitch = self.get_maybe_exist_typed_child(Pitch) + pitch = mxl_pitch.to_lily_object() + event = musicexp.NoteEvent() + event.pitch = pitch + acc = self.get_maybe_exist_named_child('accidental') + if acc: + # let's not force accs everywhere. + event.cautionary = acc.cautionary + # TODO: Handle editorial accidentals + # TODO: Handle the level-display setting for displaying brackets/parentheses + return event + + def initialize_unpitched_event(self): + # Unpitched elements have display-step and can also have + # display-octave. + unpitched = self.get_maybe_exist_typed_child(Unpitched) + event = musicexp.NoteEvent() + event.pitch = unpitched.to_lily_object() + return event + + def initialize_rest_event(self, convert_rest_positions=True): + # rests can have display-octave and display-step, which are + # treated like an ordinary note pitch + rest = self.get_maybe_exist_typed_child(Rest) + event = musicexp.RestEvent() + if convert_rest_positions: + pitch = rest.to_lily_object() + event.pitch = pitch + return event + + def initialize_drum_event(self): + event = musicexp.NoteEvent() + drum_type = self.drumtype_dict.get(self.instrument_name) + if drum_type: + event.drum_type = drum_type + else: + self.message( + _("drum %s type unknown, please add to instrument_drumtype_dict") + % n.instrument_name) + event.drum_type = 'acousticsnare' + return event + + def to_lily_object(self, + convert_stem_directions=True, + convert_rest_positions=True): + pitch = None + duration = None + event = None + + if self.get_maybe_exist_typed_child(Pitch): + event = self.initialize_pitched_event() + elif self.get_maybe_exist_typed_child(Unpitched): + event = self.initialize_unpitched_event() + elif self.get_maybe_exist_typed_child(Rest): + event = self.initialize_rest_event(convert_rest_positions) + elif self.instrument_name: + event = self.initialize_drum_event() + else: + self.message(_("cannot find suitable event")) + + if event: + event.duration = self.initialize_duration() -class Part_list (Music_xml_node): - def __init__ (self): - Music_xml_node.__init__ (self) + self.set_notehead_style(event) + self.set_stem_style(event) + if convert_stem_directions: + self.set_stem_directions(event) + + return event + + +class Part_list(Music_xml_node): + + def __init__(self): + Music_xml_node.__init__(self) self._id_instrument_name_dict = {} - def generate_id_instrument_dict (self): + def generate_id_instrument_dict(self): ## not empty to make sure this happens only once. mapping = {1: 1} - for score_part in self.get_named_children ('score-part'): - for instr in score_part.get_named_children ('score-instrument'): + for score_part in self.get_named_children('score-part'): + for instr in score_part.get_named_children('score-instrument'): id = instr.id - name = instr.get_named_child ("instrument-name") - mapping[id] = name.get_text () + name = instr.get_named_child("instrument-name") + mapping[id] = name.get_text() self._id_instrument_name_dict = mapping - def get_instrument (self, id): + def get_instrument(self, id): if not self._id_instrument_name_dict: self.generate_id_instrument_dict() - instrument_name = self._id_instrument_name_dict.get (id) + instrument_name = self._id_instrument_name_dict.get(id) if instrument_name: return instrument_name else: - ly.warning (_ ("Unable to find instrument for ID=%s\n") % id) + ly.warning(_("Unable to find instrument for ID=%s\n") % id) return "Grand Piano" -class Part_group (Music_xml_node): - pass -class Score_part (Music_xml_node): - pass -class Measure (Music_xml_node): - def __init__ (self): - Music_xml_node.__init__ (self) +class Measure(Music_xml_node): + + def __init__(self): + Music_xml_node.__init__(self) self.partial = 0 - def is_implicit (self): - return hasattr (self, 'implicit') and self.implicit == 'yes' - def get_notes (self): - return self.get_typed_children (get_class (u'note')) -class Syllabic (Music_xml_node): - def continued (self): + def is_implicit(self): + return hasattr(self, 'implicit') and self.implicit == 'yes' + + def get_notes(self): + return self.get_typed_children(get_class(u'note')) + + +class Syllabic(Music_xml_node): + + def continued(self): text = self.get_text() - return (text == "begin") or (text == "middle") -class Elision (Music_xml_node): - pass -class Extend (Music_xml_node): - pass -class Text (Music_xml_node): - pass + return(text == "begin") or(text == "middle") + + def begin(self): + return(text == "begin") + + def middle(self): + return(text == "middle") + + def end(self): + return(text == "end") + + +class Lyric(Music_xml_node): + + def get_number(self): + """ + Return the number attribute(if it exists) of the lyric element. -class Lyric (Music_xml_node): - def get_number (self): - if hasattr (self, 'number'): + @rtype: number + @return: The value of the number attribute + """ + if hasattr(self, 'number'): return self.number else: return -1 + +class Sound(Music_xml_node): + + def get_tempo(self): + """ + Return the tempo attribute(if it exists) of the sound element. + This attribute can be used by musicxml2ly for the midi output(see L{musicexp.Score}). + + @rtype: string + @return: The value of the tempo attribute + """ + if hasattr(self, 'tempo'): + return self.tempo + else: + return None + + +class Notations(Music_xml_node): + + def get_tie(self): + ts = self.get_named_children('tied') + starts = [t for t in ts if t.type == 'start'] + if starts: + return starts[0] + else: + return None + + def get_tuplets(self): + return self.get_typed_children(Tuplet) + + +class Time_modification(Music_xml_node): + + def get_fraction(self): + b = self.get_maybe_exist_named_child('actual-notes') + a = self.get_maybe_exist_named_child('normal-notes') + return(int(a.get_text()), int(b.get_text())) + + def get_normal_type(self): + tuplet_type = self.get_maybe_exist_named_child('normal-type') + if tuplet_type: + dots = self.get_named_children('normal-dot') + log = utilities.musicxml_duration_to_log(tuplet_type.get_text().strip()) + return(log , len(dots)) + else: + return None + + +class Accidental(Music_xml_node): + + def __init__(self): + Music_xml_node.__init__(self) + self.editorial = False + self.cautionary = False + + +class Tuplet(Music_xml_spanner): + + def duration_info_from_tuplet_note(self, tuplet_note): + tuplet_type = tuplet_note.get_maybe_exist_named_child('tuplet-type') + if tuplet_type: + dots = tuplet_note.get_named_children('tuplet-dot') + log = utilities.musicxml_duration_to_log(tuplet_type.get_text().strip()) + return(log, len(dots)) + else: + return None + + # Return tuplet note type as(log, dots) + def get_normal_type(self): + tuplet = self.get_maybe_exist_named_child('tuplet-normal') + if tuplet: + return self.duration_info_from_tuplet_note(tuplet) + else: + return None + + def get_actual_type(self): + tuplet = self.get_maybe_exist_named_child('tuplet-actual') + if tuplet: + return self.duration_info_from_tuplet_note(tuplet) + else: + return None + + def get_tuplet_note_count(self, tuplet_note): + if tuplet_note: + tuplet_nr = tuplet_note.get_maybe_exist_named_child('tuplet-number') + if tuplet_nr: + return int(tuplet_nr.get_text()) + return None + + def get_normal_nr(self): + return self.get_tuplet_note_count(self.get_maybe_exist_named_child('tuplet-normal')) + + def get_actual_nr(self): + return self.get_tuplet_note_count(self.get_maybe_exist_named_child('tuplet-actual')) + + +class Slur(Music_xml_spanner): + + def get_type(self): + return self.type + + +class Tied(Music_xml_spanner): + + def get_type(self): + return self.type + + +class Beam(Music_xml_spanner): + def get_type(self): + return self.get_text() + def is_primary(self): + if hasattr(self, 'number'): + return self.number == "1" + else: + return True + +class Octave_shift(Music_xml_spanner): + # default is 8 for the octave-shift! + def get_size(self): + if hasattr(self, 'size'): + return int(self.size) + else: + return 8 + + +# Rests in MusicXML are <note> blocks with a <rest> inside. This class is only +# for the inner <rest> element, not the whole rest block. +class Rest(Music_xml_node): + + def __init__(self): + Music_xml_node.__init__(self) + self._is_whole_measure = False + + def is_whole_measure(self): + return self._is_whole_measure + + def get_step(self): + ch = self.get_maybe_exist_typed_child(get_class(u'display-step')) + if ch: + return ch.get_text().strip() + else: + return None + + def get_octave(self): + ch = self.get_maybe_exist_typed_child(get_class(u'display-octave')) + if ch: + oct = ch.get_text().strip() + return int(oct) + else: + return None + + def to_lily_object(self): + p = None + step = self.get_step() + if step: + p = musicexp.Pitch() + p.step = musicxml2ly_conversion.musicxml_step_to_lily(step) + octave = self.get_octave() + if octave and p: + p.octave = octave - 4 + return p + + +class Bend(Music_xml_node): + + def bend_alter(self): + alter = self.get_maybe_exist_named_child('bend-alter') + return utilities.interpret_alter_element(alter) + + +class ChordPitch(Music_xml_node): + + def step_class_name(self): + return u'root-step' + + def alter_class_name(self): + return u'root-alter' + + def get_step(self): + ch = self.get_unique_typed_child(get_class(self.step_class_name())) + return ch.get_text().strip() + + def get_alteration(self): + ch = self.get_maybe_exist_typed_child(get_class(self.alter_class_name())) + return utilities.interpret_alter_element(ch) + + +class Bass(ChordPitch): + + def step_class_name(self): + return u'bass-step' + + def alter_class_name(self): + return u'bass-alter' + + +class ChordModification(Music_xml_node): + + def get_type(self): + ch = self.get_maybe_exist_typed_child(get_class(u'degree-type')) + return {'add': 1, 'alter': 1, 'subtract':-1}.get(ch.get_text().strip(), 0) + + def get_value(self): + ch = self.get_maybe_exist_typed_child(get_class(u'degree-value')) + value = 0 + if ch: + value = int(ch.get_text().strip()) + return value + + def get_alter(self): + ch = self.get_maybe_exist_typed_child(get_class(u'degree-alter')) + return utilities.interpret_alter_element(ch) + + +class Frame(Music_xml_node): + + def get_frets(self): + return self.get_named_child_value_number('frame-frets', 4) + + def get_strings(self): + return self.get_named_child_value_number('frame-strings', 6) + + def get_first_fret(self): + return self.get_named_child_value_number('first-fret', 1) + + +class Frame_Note(Music_xml_node): + + def get_string(self): + return self.get_named_child_value_number('string', 1) + + def get_fret(self): + return self.get_named_child_value_number('fret', 0) + + def get_fingering(self): + return self.get_named_child_value_number('fingering', -1) + + def get_barre(self): + n = self.get_maybe_exist_named_child('barre') + if n: + return getattr(n, 'type', '') + else: + return '' + + class Musicxml_voice: - def __init__ (self): + + def __init__(self): self._elements = [] self._staves = {} self._start_staff = None self._lyrics = [] self._has_lyrics = False - def add_element (self, e): - self._elements.append (e) - if (isinstance (e, Note) - and e.get_maybe_exist_typed_child (Staff)): - name = e.get_maybe_exist_typed_child (Staff).get_text () + def add_element(self, e): + self._elements.append(e) + if(isinstance(e, Note) + and e.get_maybe_exist_typed_child(Staff)): + name = e.get_maybe_exist_typed_child(Staff).get_text() - if not self._start_staff and not e.get_maybe_exist_typed_child (Grace): + if not self._start_staff and not e.get_maybe_exist_typed_child(Grace): self._start_staff = name self._staves[name] = True - lyrics = e.get_typed_children (Lyric) + lyrics = e.get_typed_children(Lyric) if not self._has_lyrics: - self.has_lyrics = len (lyrics) > 0 + self.has_lyrics = len(lyrics) > 0 for l in lyrics: nr = l.get_number() - if (nr > 0) and not (nr in self._lyrics): - self._lyrics.append (nr) + if(nr > 0) and not(nr in self._lyrics): + self._lyrics.append(nr) - def insert (self, idx, e): - self._elements.insert (idx, e) + def insert(self, idx, e): + self._elements.insert(idx, e) - def get_lyrics_numbers (self): - if (len (self._lyrics) == 0) and self._has_lyrics: + def get_lyrics_numbers(self): + if(len(self._lyrics) == 0) and self._has_lyrics: #only happens if none of the <lyric> tags has a number attribute return [1] else: return self._lyrics -def graces_to_aftergraces (pending_graces): - for gr in pending_graces: - gr._when = gr._prev_when - gr._measure_position = gr._prev_measure_position - gr._after_grace = True +class Part(Music_xml_node): - -class Part (Music_xml_node): - def __init__ (self): - Music_xml_node.__init__ (self) + def __init__(self): + Music_xml_node.__init__(self) self._voices = {} self._staff_attributes_dict = {} - def get_part_list (self): + def get_part_list(self): n = self while n and n.get_name() != 'score-partwise': n = n._parent - return n.get_named_child ('part-list') + return n.get_named_child('part-list') + + def graces_to_aftergraces(self, pending_graces): + for gr in pending_graces: + gr._when = gr._prev_when + gr._measure_position = gr._prev_measure_position + gr._after_grace = True - def interpret (self): + def interpret(self): """Set durations and starting points.""" """The starting point of the very first note is 0!""" - part_list = self.get_part_list () + part_list = self.get_part_list() - now = Rational (0) - factor = Rational (1) + now = Rational(0) + factor = Rational(1) attributes_dict = {} attributes_object = None - measures = self.get_typed_children (Measure) - last_moment = Rational (-1) - last_measure_position = Rational (-1) - measure_position = Rational (0) + measures = self.get_typed_children(Measure) + last_moment = Rational(-1) + last_measure_position = Rational(-1) + measure_position = Rational(0) measure_start_moment = now is_first_measure = True previous_measure = None @@ -637,14 +1290,14 @@ class Part (Music_xml_node): # implicit measures are used for artificial measures, e.g. when # a repeat bar line splits a bar into two halves. In this case, # don't reset the measure position to 0. They are also used for - # upbeats (initial value of 0 fits these, too). + # upbeats(initial value of 0 fits these, too). # Also, don't reset the measure position at the end of the loop, - # but rather when starting the next measure (since only then do we + # but rather when starting the next measure(since only then do we # know if the next measure is implicit and continues that measure) - if not m.is_implicit (): + if not m.is_implicit(): # Warn about possibly overfull measures and reset the position if attributes_object and previous_measure and previous_measure.partial == 0: - length = attributes_object.get_measure_length () + length = attributes_object.get_measure_length() new_now = measure_start_moment + length if now <> new_now: problem = 'incomplete' @@ -652,55 +1305,55 @@ class Part (Music_xml_node): problem = 'overfull' ## only for verbose operation. if problem <> 'incomplete' and previous_measure: - previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now)) + previous_measure.message('%s measure? Expected: %s, Difference: %s' %(problem, now, new_now - now)) now = new_now measure_start_moment = now - measure_position = Rational (0) + measure_position = Rational(0) - for n in m.get_all_children (): + for n in m.get_all_children(): # figured bass has a duration, but applies to the next note # and should not change the current measure position! - if isinstance (n, FiguredBass): - n._divisions = factor.denominator () + if isinstance(n, FiguredBass): + n._divisions = factor.denominator() n._when = now n._measure_position = measure_position continue - if isinstance (n, Hash_text): + if isinstance(n, Hash_text): continue - dur = Rational (0) + dur = Rational(0) if n.__class__ == Attributes: - n.set_attributes_from_previous (attributes_dict) - n.read_self () - attributes_dict = n._dict.copy () + n.set_attributes_from_previous(attributes_dict) + n.read_self() + attributes_dict = n._dict.copy() attributes_object = n - factor = Rational (1, - int (attributes_dict.get ('divisions').get_text ())) + factor = Rational(1, + int(attributes_dict.get('divisions').get_text())) - if (n.get_maybe_exist_typed_child (Duration)): - mxl_dur = n.get_maybe_exist_typed_child (Duration) - dur = mxl_dur.get_length () * factor + if(n.get_maybe_exist_typed_child(Duration)): + mxl_dur = n.get_maybe_exist_typed_child(Duration) + dur = mxl_dur.get_length() * factor if n.get_name() == 'backup': - dur = - dur + dur = -dur # reset all graces before the backup to after-graces: - graces_to_aftergraces (pending_graces) + self.graces_to_aftergraces(pending_graces) pending_graces = [] - if n.get_maybe_exist_typed_child (Grace): - dur = Rational (0) + if n.get_maybe_exist_typed_child(Grace): + dur = Rational(0) - rest = n.get_maybe_exist_typed_child (Rest) - if (rest + rest = n.get_maybe_exist_typed_child(Rest) + if(rest and attributes_object - and attributes_object.get_measure_length () == dur): + and attributes_object.get_measure_length() == dur): rest._is_whole_measure = True - if (dur > Rational (0) - and n.get_maybe_exist_typed_child (Chord)): + if(dur > Rational(0) + and n.get_maybe_exist_typed_child(Chord)): now = last_moment measure_position = last_measure_position @@ -709,27 +1362,27 @@ class Part (Music_xml_node): # For all grace notes, store the previous note, in case need # to turn the grace note into an after-grace later on! - if isinstance(n, Note) and n.is_grace (): + if isinstance(n, Note) and n.is_grace(): n._prev_when = last_moment n._prev_measure_position = last_measure_position # After-graces are placed at the same position as the previous note - if isinstance(n, Note) and n.is_after_grace (): + if isinstance(n, Note) and n.is_after_grace(): # TODO: We should do the same for grace notes at the end of # a measure with no following note!!! n._when = last_moment n._measure_position = last_measure_position - elif isinstance(n, Note) and n.is_grace (): - pending_graces.append (n) - elif (dur > Rational (0)): + elif isinstance(n, Note) and n.is_grace(): + pending_graces.append(n) + elif(dur > Rational(0)): pending_graces = []; n._duration = dur - if dur > Rational (0): + if dur > Rational(0): last_moment = now last_measure_position = measure_position now += dur measure_position += dur - elif dur < Rational (0): + elif dur < Rational(0): # backup element, reset measure position now += dur measure_position += dur @@ -740,430 +1393,294 @@ class Part (Music_xml_node): last_moment = now last_measure_position = measure_position if n._name == 'note': - instrument = n.get_maybe_exist_named_child ('instrument') + instrument = n.get_maybe_exist_named_child('instrument') if instrument: - n.instrument_name = part_list.get_instrument (instrument.id) + n.instrument_name = part_list.get_instrument(instrument.id) # reset all graces at the end of the measure to after-graces: - graces_to_aftergraces (pending_graces) + self.graces_to_aftergraces(pending_graces) pending_graces = [] # Incomplete first measures are not padded, but registered as partial if is_first_measure: is_first_measure = False # upbeats are marked as implicit measures - if attributes_object and m.is_implicit (): - length = attributes_object.get_measure_length () + if attributes_object and m.is_implicit(): + length = attributes_object.get_measure_length() measure_end = measure_start_moment + length if measure_end <> now: m.partial = now previous_measure = m # modify attributes so that only those applying to the given staff remain - def extract_attributes_for_staff (part, attr, staff): - attributes = copy.copy (attr) + def extract_attributes_for_staff(part, attr, staff): + attributes = copy.copy(attr) attributes._children = []; - attributes._dict = attr._dict.copy () + attributes._dict = attr._dict.copy() attributes._original_tag = attr # copy only the relevant children over for the given staff if staff == "None": staff = "1" for c in attr._children: - if (not (hasattr (c, 'number') and (c.number != staff)) and - not (isinstance (c, Hash_text))): - attributes._children.append (c) + if(not(hasattr(c, 'number') and(c.number != staff)) and + not(isinstance(c, Hash_text))): + attributes._children.append(c) if not attributes._children: return None else: return attributes - def extract_voices (part): + def extract_voices(part): + # The last indentified voice + last_voice = None + voices = {} - measures = part.get_typed_children (Measure) + measures = part.get_typed_children(Measure) elements = [] for m in measures: if m.partial > 0: - elements.append (Partial (m.partial)) - elements.extend (m.get_all_children ()) + elements.append(Partial(m.partial)) + elements.extend(m.get_all_children()) # make sure we know all voices already so that dynamics, clefs, etc. # can be assigned to the correct voices voice_to_staff_dict = {} for n in elements: - voice_id = n.get_maybe_exist_named_child (u'voice') + voice_id = n.get_maybe_exist_named_child(u'voice') vid = None if voice_id: - vid = voice_id.get_text () - elif isinstance (n, Note): + vid = voice_id.get_text() + elif isinstance(n, Note): # TODO: Check whether we shall really use "None" here, or # rather use "1" as the default? - vid = "None" + if n.get_maybe_exist_named_child(u'chord'): + vid = last_voice + else: + vid = "1" + + if(vid != None): + last_voice = vid - staff_id = n.get_maybe_exist_named_child (u'staff') + staff_id = n.get_maybe_exist_named_child(u'staff') sid = None if staff_id: - sid = staff_id.get_text () + sid = staff_id.get_text() else: # TODO: Check whether we shall really use "None" here, or # rather use "1" as the default? # If this is changed, need to change the corresponding # check in extract_attributes_for_staff, too. sid = "None" - if vid and not voices.has_key (vid): + if vid and not voices.has_key(vid): voices[vid] = Musicxml_voice() - if vid and sid and not n.get_maybe_exist_typed_child (Grace): - if not voice_to_staff_dict.has_key (vid): + if vid and sid and not n.get_maybe_exist_typed_child(Grace): + if not voice_to_staff_dict.has_key(vid): voice_to_staff_dict[vid] = sid - # invert the voice_to_staff_dict into a staff_to_voice_dict (since we + + # invert the voice_to_staff_dict into a staff_to_voice_dict(since we # need to assign staff-assigned objects like clefs, times, etc. to # all the correct voices. This will never work entirely correct due # to staff-switches, but that's the best we can do! staff_to_voice_dict = {} - for (v,s) in voice_to_staff_dict.items (): - if not staff_to_voice_dict.has_key (s): + for(v, s) in voice_to_staff_dict.items(): + if not staff_to_voice_dict.has_key(s): staff_to_voice_dict[s] = [v] else: - staff_to_voice_dict[s].append (v) - + staff_to_voice_dict[s].append(v) start_attr = None assign_to_next_note = [] id = None for n in elements: - voice_id = n.get_maybe_exist_typed_child (get_class ('voice')) + voice_id = n.get_maybe_exist_typed_child(get_class('voice')) if voice_id: - id = voice_id.get_text () + id = voice_id.get_text() else: - id = "None" + if n.get_maybe_exist_typed_child(get_class('chord')): + id = last_voice + else: + id = "1" + + if(id != "None"): + last_voice = id # We don't need backup/forward any more, since we have already # assigned the correct onset times. # TODO: Let Grouping through. Also: link, print, bokmark sound - if not (isinstance (n, Note) or isinstance (n, Attributes) or - isinstance (n, Direction) or isinstance (n, Partial) or - isinstance (n, Barline) or isinstance (n, Harmony) or - isinstance (n, FiguredBass) or isinstance (n, Print)): + if not(isinstance(n, Note) or isinstance(n, Attributes) or + isinstance(n, Direction) or isinstance(n, Partial) or + isinstance(n, Barline) or isinstance(n, Harmony) or + isinstance(n, FiguredBass) or isinstance(n, Print)): continue - if isinstance (n, Attributes) and not start_attr: + if isinstance(n, Attributes) and not start_attr: start_attr = n continue - if isinstance (n, Attributes): + if isinstance(n, Attributes): # assign these only to the voices they really belong to! - for (s, vids) in staff_to_voice_dict.items (): - staff_attributes = part.extract_attributes_for_staff (n, s) + for(s, vids) in staff_to_voice_dict.items(): + staff_attributes = part.extract_attributes_for_staff(n, s) if staff_attributes: for v in vids: - voices[v].add_element (staff_attributes) + voices[v].add_element(staff_attributes) continue - if isinstance (n, Partial) or isinstance (n, Barline) or isinstance (n, Print): - for v in voices.keys (): - voices[v].add_element (n) + if isinstance(n, Partial) or isinstance(n, Barline) or isinstance(n, Print): + for v in voices.keys(): + voices[v].add_element(n) continue - if isinstance (n, Direction): - staff_id = n.get_maybe_exist_named_child (u'staff') + if isinstance(n, Direction): + staff_id = n.get_maybe_exist_named_child(u'staff') if staff_id: - staff_id = staff_id.get_text () + staff_id = staff_id.get_text() if staff_id: - dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ()) + dir_voices = staff_to_voice_dict.get(staff_id, voices.keys()) else: - dir_voices = voices.keys () + dir_voices = voices.keys() for v in dir_voices: - voices[v].add_element (n) + voices[v].add_element(n) continue - if isinstance (n, Harmony) or isinstance (n, FiguredBass): + if isinstance(n, Harmony) or isinstance(n, FiguredBass): # store the harmony or figured bass element until we encounter # the next note and assign it only to that one voice. - assign_to_next_note.append (n) + assign_to_next_note.append(n) continue - if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no": + if hasattr(n, 'print-object') and getattr(n, 'print-object') == "no": #Skip this note. pass else: for i in assign_to_next_note: - voices[id].add_element (i) + voices[id].add_element(i) assign_to_next_note = [] - voices[id].add_element (n) + voices[id].add_element(n) # Assign all remaining elements from assign_to_next_note to the voice # of the previous note: for i in assign_to_next_note: - voices[id].add_element (i) + voices[id].add_element(i) assign_to_next_note = [] if start_attr: - for (s, vids) in staff_to_voice_dict.items (): - staff_attributes = part.extract_attributes_for_staff (start_attr, s) - staff_attributes.read_self () + for(s, vids) in staff_to_voice_dict.items(): + staff_attributes = part.extract_attributes_for_staff(start_attr, s) + staff_attributes.read_self() part._staff_attributes_dict[s] = staff_attributes for v in vids: - voices[v].insert (0, staff_attributes) + voices[v].insert(0, staff_attributes) voices[v]._elements[0].read_self() part._voices = voices - def get_voices (self): + def get_voices(self): return self._voices - def get_staff_attributes (self): - return self._staff_attributes_dict - -class Notations (Music_xml_node): - def get_tie (self): - ts = self.get_named_children ('tied') - starts = [t for t in ts if t.type == 'start'] - if starts: - return starts[0] - else: - return None - - def get_tuplets (self): - return self.get_typed_children (Tuplet) -class Time_modification(Music_xml_node): - def get_fraction (self): - b = self.get_maybe_exist_named_child ('actual-notes') - a = self.get_maybe_exist_named_child ('normal-notes') - return (int(a.get_text ()), int (b.get_text ())) - - def get_normal_type (self): - tuplet_type = self.get_maybe_exist_named_child ('normal-type') - if tuplet_type: - dots = self.get_named_children ('normal-dot') - log = musicxml_duration_to_log (tuplet_type.get_text ().strip ()) - return (log , len (dots)) - else: - return None - - -class Accidental (Music_xml_node): - def __init__ (self): - Music_xml_node.__init__ (self) - self.editorial = False - self.cautionary = False + def get_staff_attributes(self): + return self._staff_attributes_dict -class Music_xml_spanner (Music_xml_node): - def get_type (self): - if hasattr (self, 'type'): - return self.type - else: - return 0 - def get_size (self): - if hasattr (self, 'size'): - return string.atoi (self.size) - else: - return 0 -class Wedge (Music_xml_spanner): +class BarStyle(Music_xml_node): pass -class Tuplet (Music_xml_spanner): - def duration_info_from_tuplet_note (self, tuplet_note): - tuplet_type = tuplet_note.get_maybe_exist_named_child ('tuplet-type') - if tuplet_type: - dots = tuplet_note.get_named_children ('tuplet-dot') - log = musicxml_duration_to_log (tuplet_type.get_text ().strip ()) - return (log, len (dots)) - else: - return None - - # Return tuplet note type as (log, dots) - def get_normal_type (self): - tuplet = self.get_maybe_exist_named_child ('tuplet-normal') - if tuplet: - return self.duration_info_from_tuplet_note (tuplet) - else: - return None - - def get_actual_type (self): - tuplet = self.get_maybe_exist_named_child ('tuplet-actual') - if tuplet: - return self.duration_info_from_tuplet_note (tuplet) - else: - return None +class BeatType(Music_xml_node): + pass - def get_tuplet_note_count (self, tuplet_note): - if tuplet_note: - tuplet_nr = tuplet_note.get_maybe_exist_named_child ('tuplet-number') - if tuplet_nr: - return int (tuplet_nr.get_text ()) - return None - def get_normal_nr (self): - return self.get_tuplet_note_count (self.get_maybe_exist_named_child ('tuplet-normal')) - def get_actual_nr (self): - return self.get_tuplet_note_count (self.get_maybe_exist_named_child ('tuplet-actual')) +class BeatUnit(Music_xml_node): + pass -class Bracket (Music_xml_spanner): +class BeatUnitDot(Music_xml_node): pass -class Dashes (Music_xml_spanner): +class Beats(Music_xml_node): pass -class Slur (Music_xml_spanner): - def get_type (self): - return self.type +class Bracket(Music_xml_spanner): + pass -class Beam (Music_xml_spanner): - def get_type (self): - return self.get_text () - def is_primary (self): - if hasattr (self, 'number'): - return self.number == "1" - else: - return True +class Chord(Music_xml_node): + pass -class Wavy_line (Music_xml_spanner): +class Dashes(Music_xml_spanner): pass -class Pedal (Music_xml_spanner): +class DirType(Music_xml_node): pass -class Glissando (Music_xml_spanner): +class Direction(Music_xml_node): pass -class Slide (Music_xml_spanner): +class Dot(Music_xml_node): pass -class Octave_shift (Music_xml_spanner): - # default is 8 for the octave-shift! - def get_size (self): - if hasattr (self, 'size'): - return string.atoi (self.size) - else: - return 8 +class Elision(Music_xml_node): + pass -class Chord (Music_xml_node): +class Extend(Music_xml_node): pass -class Dot (Music_xml_node): +class FiguredBass(Music_xml_node): pass -# Rests in MusicXML are <note> blocks with a <rest> inside. This class is only -# for the inner <rest> element, not the whole rest block. -class Rest (Music_xml_node): - def __init__ (self): - Music_xml_node.__init__ (self) - self._is_whole_measure = False - def is_whole_measure (self): - return self._is_whole_measure - def get_step (self): - ch = self.get_maybe_exist_typed_child (get_class (u'display-step')) - if ch: - return ch.get_text ().strip () - else: - return None - def get_octave (self): - ch = self.get_maybe_exist_typed_child (get_class (u'display-octave')) - if ch: - oct = ch.get_text ().strip () - return int (oct) - else: - return None +class Glissando(Music_xml_spanner): + pass -class Type (Music_xml_node): +class Grace(Music_xml_node): pass -class Grace (Music_xml_node): + +class Harmony(Music_xml_node): pass -class Staff (Music_xml_node): + +class Hash_comment(Music_xml_node): pass -class Direction (Music_xml_node): +class KeyAlter(Music_xml_node): pass -class DirType (Music_xml_node): + +class KeyOctave(Music_xml_node): pass -class Bend (Music_xml_node): - def bend_alter (self): - alter = self.get_maybe_exist_named_child ('bend-alter') - return interpret_alter_element (alter) +class KeyStep(Music_xml_node): + pass -class Words (Music_xml_node): +class Part_group(Music_xml_node): pass -class Harmony (Music_xml_node): +class Pedal(Music_xml_spanner): pass -class ChordPitch (Music_xml_node): - def step_class_name (self): - return u'root-step' - def alter_class_name (self): - return u'root-alter' - def get_step (self): - ch = self.get_unique_typed_child (get_class (self.step_class_name ())) - return ch.get_text ().strip () - def get_alteration (self): - ch = self.get_maybe_exist_typed_child (get_class (self.alter_class_name ())) - return interpret_alter_element (ch) - -class Root (ChordPitch): +class PerMinute(Music_xml_node): pass -class Bass (ChordPitch): - def step_class_name (self): - return u'bass-step' - def alter_class_name (self): - return u'bass-alter' +class Print(Music_xml_node): + pass -class ChordModification (Music_xml_node): - def get_type (self): - ch = self.get_maybe_exist_typed_child (get_class (u'degree-type')) - return {'add': 1, 'alter': 1, 'subtract': -1}.get (ch.get_text ().strip (), 0) - def get_value (self): - ch = self.get_maybe_exist_typed_child (get_class (u'degree-value')) - value = 0 - if ch: - value = int (ch.get_text ().strip ()) - return value - def get_alter (self): - ch = self.get_maybe_exist_typed_child (get_class (u'degree-alter')) - return interpret_alter_element (ch) - - -class Frame (Music_xml_node): - def get_frets (self): - return self.get_named_child_value_number ('frame-frets', 4) - def get_strings (self): - return self.get_named_child_value_number ('frame-strings', 6) - def get_first_fret (self): - return self.get_named_child_value_number ('first-fret', 1) - -class Frame_Note (Music_xml_node): - def get_string (self): - return self.get_named_child_value_number ('string', 1) - def get_fret (self): - return self.get_named_child_value_number ('fret', 0) - def get_fingering (self): - return self.get_named_child_value_number ('fingering', -1) - def get_barre (self): - n = self.get_maybe_exist_named_child ('barre') - if n: - return getattr (n, 'type', '') - else: - return '' +class Root(ChordPitch): + pass -class FiguredBass (Music_xml_node): +class Score_part(Music_xml_node): pass -class Beats (Music_xml_node): +class Slide(Music_xml_spanner): pass -class BeatType (Music_xml_node): +class Staff(Music_xml_node): pass -class BeatUnit (Music_xml_node): +class Text(Music_xml_node): pass -class BeatUnitDot (Music_xml_node): +class Type(Music_xml_node): pass -class PerMinute (Music_xml_node): +class Wavy_line(Music_xml_spanner): pass -class Print (Music_xml_node): +class Wedge(Music_xml_spanner): pass +class Words(Music_xml_node): + pass ## need this, not all classes are instantiated @@ -1185,6 +1702,7 @@ class_dict = { 'bend' : Bend, 'bracket' : Bracket, 'chord': Chord, + 'credit': Credit, 'dashes' : Dashes, 'degree' : ChordModification, 'dot': Dot, @@ -1207,9 +1725,10 @@ class_dict = { 'measure': Measure, 'notations': Notations, 'note': Note, + 'notehead': Notehead, 'octave-shift': Octave_shift, 'part': Part, - 'part-group': Part_group, + 'part-group': Part_group, 'part-list': Part_list, 'pedal': Pedal, 'per-minute': PerMinute, @@ -1220,10 +1739,13 @@ class_dict = { 'score-part': Score_part, 'slide': Slide, 'slur': Slur, + 'sound': Sound, 'staff': Staff, + 'stem': Stem, 'syllabic': Syllabic, 'text': Text, 'time-modification': Time_modification, + 'tied': Tied, 'tuplet': Tuplet, 'type': Type, 'unpitched': Unpitched, @@ -1233,59 +1755,59 @@ class_dict = { 'work': Work, } -def name2class_name (name): - name = name.replace ('-', '_') - name = name.replace ('#', 'hash_') +def name2class_name(name): + name = name.replace('-', '_') + name = name.replace('#', 'hash_') name = name[0].upper() + name[1:].lower() - return str (name) + return str(name) -def get_class (name): - classname = class_dict.get (name) +def get_class(name): + classname = class_dict.get(name) if classname: return classname else: - class_name = name2class_name (name) - klass = new.classobj (class_name, (Music_xml_node,) , {}) + class_name = name2class_name(name) + klass = new.classobj(class_name,(Music_xml_node,) , {}) class_dict[name] = klass return klass -def lxml_demarshal_node (node): +def lxml_demarshal_node(node): name = node.tag # Ignore comment nodes, which are also returned by the etree parser! if name is None or node.__class__.__name__ == "_Comment": return None - klass = get_class (name) + klass = get_class(name) py_node = klass() py_node._original = node py_node._name = name py_node._data = node.text - py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()] - py_node._children = filter (lambda x: x, py_node._children) + py_node._children = [lxml_demarshal_node(cn) for cn in node.getchildren()] + py_node._children = filter(lambda x: x, py_node._children) for c in py_node._children: c._parent = py_node - for (k, v) in node.items (): + for(k, v) in node.items(): py_node.__dict__[k] = v py_node._attribute_dict[k] = v return py_node -def minidom_demarshal_node (node): +def minidom_demarshal_node(node): name = node.nodeName - klass = get_class (name) - py_node = klass () + klass = get_class(name) + py_node = klass() py_node._name = name - py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes] + py_node._children = [minidom_demarshal_node(cn) for cn in node.childNodes] for c in py_node._children: c._parent = py_node if node.attributes: - for (nm, value) in node.attributes.items (): + for(nm, value) in node.attributes.items(): py_node.__dict__[nm] = value py_node._attribute_dict[nm] = value @@ -1297,11 +1819,11 @@ def minidom_demarshal_node (node): return py_node -if __name__ == '__main__': +if __name__ == '__main__': import lxml.etree - tree = lxml.etree.parse ('beethoven.xml') - mxl_tree = lxml_demarshal_node (tree.getroot ()) - ks = class_dict.keys () - ks.sort () - print '\n'.join (ks) + tree = lxml.etree.parse('beethoven.xml') + mxl_tree = lxml_demarshal_node(tree.getroot()) + ks = class_dict.keys() + ks.sort() + print '\n'.join(ks) |