1 # -*- coding: utf-8 -*-
9 def escape_ly_output_string (input_string):
10 return_string = input_string
11 needs_quotes = not re.match (u"^[a-zA-ZäöüÜÄÖßñ]*$", return_string);
13 return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
22 self._name = 'xml_node'
24 self._attribute_dict = {}
26 def get_parent (self):
30 return self._parent.get_typed_children (self.__class__)[0] == self
41 if not self._children:
44 return ''.join ([c.get_text () for c in self._children])
46 def message (self, msg):
47 sys.stderr.write (msg+'\n')
51 sys.stderr.write (' In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()])))
54 def get_typed_children (self, klass):
58 return [c for c in self._children if isinstance(c, klass)]
60 def get_named_children (self, nm):
61 return self.get_typed_children (get_class (nm))
63 def get_named_child (self, nm):
64 return self.get_maybe_exist_named_child (nm)
66 def get_children (self, predicate):
67 return [c for c in self._children if predicate(c)]
69 def get_all_children (self):
72 def get_maybe_exist_named_child (self, name):
73 return self.get_maybe_exist_typed_child (get_class (name))
75 def get_maybe_exist_typed_child (self, klass):
76 cn = self.get_typed_children (klass)
82 raise "More than 1 child", klass
84 def get_unique_typed_child (self, klass):
85 cn = self.get_typed_children(klass)
87 sys.stderr.write (self.__dict__ + '\n')
88 raise 'Child is not unique for', (klass, 'found', cn)
92 def get_named_child_value_number (self, name, default):
93 n = self.get_maybe_exist_named_child (name)
95 return string.atoi (n.get_text())
100 class Music_xml_node (Xml_node):
102 Xml_node.__init__ (self)
103 self.duration = Rational (0)
104 self.start = Rational (0)
106 class Work (Xml_node):
107 def get_work_information (self, tag):
108 wt = self.get_maybe_exist_named_child (tag)
110 return wt.get_text ()
114 def get_work_title (self):
115 return self.get_work_information ('work-title')
116 def get_work_number (self):
117 return self.get_work_information ('work-number')
119 return self.get_work_information ('opus')
121 class Identification (Xml_node):
122 def get_rights (self):
123 rights = self.get_maybe_exist_named_child ('rights')
125 return rights.get_text ()
129 def get_creator (self, type):
130 creators = self.get_named_children ('creator')
131 # return the first creator tag that has the particular type
133 if hasattr (i, 'type') and i.type == type:
137 def get_composer (self):
138 c = self.get_creator ('composer')
141 creators = self.get_named_children ('creator')
142 # return the first creator tag that has no type at all
144 if not hasattr (i, 'type'):
147 def get_arranger (self):
148 return self.get_creator ('arranger')
149 def get_editor (self):
150 return self.get_creator ('editor')
152 v = self.get_creator ('lyricist')
155 v = self.get_creator ('poet')
158 def get_encoding_information (self, type):
159 enc = self.get_named_children ('encoding')
161 children = enc[0].get_named_children (type)
163 return children[0].get_text ()
167 def get_encoding_software (self):
168 return self.get_encoding_information ('software')
169 def get_encoding_date (self):
170 return self.get_encoding_information ('encoding-date')
171 def get_encoding_person (self):
172 return self.get_encoding_information ('encoder')
173 def get_encoding_description (self):
174 return self.get_encoding_information ('encoding-description')
177 class Duration (Music_xml_node):
178 def get_length (self):
179 dur = int (self.get_text ()) * Rational (1,4)
182 class Hash_comment (Music_xml_node):
184 class Hash_text (Music_xml_node):
187 class Pitch (Music_xml_node):
189 ch = self.get_unique_typed_child (get_class (u'step'))
190 step = ch.get_text ().strip ()
192 def get_octave (self):
193 ch = self.get_unique_typed_child (get_class (u'octave'))
195 step = ch.get_text ().strip ()
198 def get_alteration (self):
199 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
202 alter = int (ch.get_text ().strip ())
205 class Unpitched (Music_xml_node):
207 ch = self.get_unique_typed_child (get_class (u'display-step'))
208 step = ch.get_text ().strip ()
211 def get_octave (self):
212 ch = self.get_unique_typed_child (get_class (u'display-octave'))
215 octave = ch.get_text ().strip ()
220 class Measure_element (Music_xml_node):
221 def get_voice_id (self):
222 voice_id = self.get_maybe_exist_named_child ('voice')
224 return voice_id.get_text ()
229 cn = self._parent.get_typed_children (self.__class__)
230 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
233 class Attributes (Measure_element):
235 Measure_element.__init__ (self)
238 def set_attributes_from_previous (self, dict):
239 self._dict.update (dict)
241 def read_self (self):
242 for c in self.get_all_children ():
243 self._dict[c.get_name()] = c
245 def get_named_attribute (self, name):
246 return self._dict.get (name)
248 def get_measure_length (self):
249 (n,d) = self.get_time_signature ()
250 return Rational (n,d)
252 def get_time_signature (self):
253 "return time sig as a (beat, beat-type) tuple"
256 mxl = self.get_named_attribute ('time')
258 beats = mxl.get_maybe_exist_named_child ('beats')
259 type = mxl.get_maybe_exist_named_child ('beat-type')
260 return (int (beats.get_text ()),
261 int (type.get_text ()))
265 sys.stderr.write (_ ("error: requested time signature, but time sig is unknown\n"))
268 # returns clef information in the form ("cleftype", position, octave-shift)
269 def get_clef_information (self):
270 clefinfo = ['G', 2, 0]
271 mxl = self.get_named_attribute ('clef')
274 sign = mxl.get_maybe_exist_named_child ('sign')
276 clefinfo[0] = sign.get_text()
277 line = mxl.get_maybe_exist_named_child ('line')
279 clefinfo[1] = string.atoi (line.get_text ())
280 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
282 clefinfo[2] = string.atoi (octave.get_text ())
285 def get_key_signature (self):
286 "return (fifths, mode) tuple"
288 key = self.get_named_attribute ('key')
289 mode_node = key.get_maybe_exist_named_child ('mode')
292 mode = mode_node.get_text ()
294 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
295 return (fifths, mode)
297 class Barline (Measure_element):
299 class BarStyle (Music_xml_node):
301 class Partial (Measure_element):
302 def __init__ (self, partial):
303 Measure_element.__init__ (self)
304 self.partial = partial
306 class Note (Measure_element):
308 Measure_element.__init__ (self)
309 self.instrument_name = ''
311 def get_duration_log (self):
312 ch = self.get_maybe_exist_named_child (u'type')
315 log = ch.get_text ().strip()
326 'long': -2}.get (log, 0)
327 elif self.get_maybe_exist_named_child (u'grace'):
328 # FIXME: is it ok to default to eight note for grace notes?
331 self.message (_ ("Encountered note at %s with %s duration (no <type> element):") % (self.start, self.duration) )
334 def get_factor (self):
337 def get_pitches (self):
338 return self.get_typed_children (get_class (u'pitch'))
340 class Part_list (Music_xml_node):
342 Music_xml_node.__init__ (self)
343 self._id_instrument_name_dict = {}
345 def generate_id_instrument_dict (self):
347 ## not empty to make sure this happens only once.
349 for score_part in self.get_named_children ('score-part'):
350 for instr in score_part.get_named_children ('score-instrument'):
352 name = instr.get_named_child ("instrument-name")
353 mapping[id] = name.get_text ()
355 self._id_instrument_name_dict = mapping
357 def get_instrument (self, id):
358 if not self._id_instrument_name_dict:
359 self.generate_id_instrument_dict()
361 instrument_name = self._id_instrument_name_dict.get (id)
363 return instrument_name
365 sys.stderr.write (_ ("Unable to find find instrument for ID=%s\n") % id)
368 class Part_group (Music_xml_node):
370 class Score_part (Music_xml_node):
373 class Measure (Music_xml_node):
375 Music_xml_node.__init__ (self)
377 def is_implicit (self):
378 return hasattr (self, 'implicit') and self.implicit == 'yes'
379 def get_notes (self):
380 return self.get_typed_children (get_class (u'note'))
382 class Syllabic (Music_xml_node):
383 def continued (self):
384 text = self.get_text()
385 return (text == "begin") or (text == "middle")
386 class Text (Music_xml_node):
389 class Lyric (Music_xml_node):
390 def get_number (self):
391 if hasattr (self, 'number'):
396 def lyric_to_text (self):
398 syllabic = self.get_maybe_exist_typed_child (Syllabic)
400 continued = syllabic.continued ()
401 text = self.get_maybe_exist_typed_child (Text)
404 text = text.get_text()
405 # We need to convert soft hyphens to -, otherwise the ascii codec as well
406 # as lilypond will barf on that character
407 text = string.replace( text, u'\xad', '-' )
409 if text == "-" and continued:
411 elif text == "_" and continued:
413 elif continued and text:
414 return escape_ly_output_string (text) + " --"
418 return escape_ly_output_string (text)
422 class Musicxml_voice:
426 self._start_staff = None
428 self._has_lyrics = False
430 def add_element (self, e):
431 self._elements.append (e)
432 if (isinstance (e, Note)
433 and e.get_maybe_exist_typed_child (Staff)):
434 name = e.get_maybe_exist_typed_child (Staff).get_text ()
436 if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
437 self._start_staff = name
438 self._staves[name] = True
440 lyrics = e.get_typed_children (Lyric)
441 if not self._has_lyrics:
442 self.has_lyrics = len (lyrics) > 0
446 if (nr > 0) and not (nr in self._lyrics):
447 self._lyrics.append (nr)
449 def insert (self, idx, e):
450 self._elements.insert (idx, e)
452 def get_lyrics_numbers (self):
453 if (len (self._lyrics) == 0) and self._has_lyrics:
454 #only happens if none of the <lyric> tags has a number attribute
460 class Part (Music_xml_node):
462 Music_xml_node.__init__ (self)
464 self._staff_attributes_dict = {}
466 def get_part_list (self):
468 while n and n.get_name() != 'score-partwise':
471 return n.get_named_child ('part-list')
473 def interpret (self):
474 """Set durations and starting points."""
475 """The starting point of the very first note is 0!"""
477 part_list = self.get_part_list ()
480 factor = Rational (1)
482 attributes_object = None
483 measures = self.get_typed_children (Measure)
484 last_moment = Rational (-1)
485 last_measure_position = Rational (-1)
486 measure_position = Rational (0)
487 measure_start_moment = now
488 is_first_measure = True
489 previous_measure = None
491 # implicit measures are used for artificial measures, e.g. when
492 # a repeat bar line splits a bar into two halves. In this case,
493 # don't reset the measure position to 0. They are also used for
494 # upbeats (initial value of 0 fits these, too).
495 # Also, don't reset the measure position at the end of the loop,
496 # but rather when starting the next measure (since only then do we
497 # know if the next measure is implicit and continues that measure)
498 if not m.is_implicit ():
499 # Warn about possibly overfull measures and reset the position
500 if attributes_object and previous_measure and previous_measure.partial == 0:
501 length = attributes_object.get_measure_length ()
502 new_now = measure_start_moment + length
504 problem = 'incomplete'
507 ## only for verbose operation.
508 if problem <> 'incomplete' and previous_measure:
509 previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
511 measure_start_moment = now
512 measure_position = Rational (0)
514 for n in m.get_all_children ():
515 if isinstance (n, Hash_text):
519 if n.__class__ == Attributes:
520 n.set_attributes_from_previous (attributes_dict)
522 attributes_dict = n._dict.copy ()
523 attributes_object = n
525 factor = Rational (1,
526 int (attributes_dict.get ('divisions').get_text ()))
529 if (n.get_maybe_exist_typed_child (Duration)):
530 mxl_dur = n.get_maybe_exist_typed_child (Duration)
531 dur = mxl_dur.get_length () * factor
533 if n.get_name() == 'backup':
535 if n.get_maybe_exist_typed_child (Grace):
538 rest = n.get_maybe_exist_typed_child (Rest)
540 and attributes_object
541 and attributes_object.get_measure_length () == dur):
543 rest._is_whole_measure = True
545 if (dur > Rational (0)
546 and n.get_maybe_exist_typed_child (Chord)):
548 measure_position = last_measure_position
551 n._measure_position = measure_position
553 if dur > Rational (0):
555 last_measure_position = measure_position
557 measure_position += dur
558 elif dur < Rational (0):
559 # backup element, reset measure position
561 measure_position += dur
562 if measure_position < 0:
563 # backup went beyond the measure start => reset to 0
564 now -= measure_position
567 last_measure_position = measure_position
568 if n._name == 'note':
569 instrument = n.get_maybe_exist_named_child ('instrument')
571 n.instrument_name = part_list.get_instrument (instrument.id)
573 # Incomplete first measures are not padded, but registered as partial
575 is_first_measure = False
576 # upbeats are marked as implicit measures
577 if attributes_object and m.is_implicit ():
578 length = attributes_object.get_measure_length ()
579 measure_end = measure_start_moment + length
580 if measure_end <> now:
584 # modify attributes so that only those applying to the given staff remain
585 def extract_attributes_for_staff (part, attr, staff):
586 attributes = copy.copy (attr)
587 attributes._children = copy.copy (attr._children)
588 attributes._dict = attr._dict.copy ()
589 for c in attributes._children:
590 if hasattr (c, 'number') and c.number != staff:
591 attributes._children.remove (c)
594 def extract_voices (part):
596 measures = part.get_typed_children (Measure)
600 elements.append (Partial (m.partial))
601 elements.extend (m.get_all_children ())
602 # make sure we know all voices already so that dynamics, clefs, etc.
603 # can be assigned to the correct voices
604 voice_to_staff_dict = {}
606 voice_id = n.get_maybe_exist_named_child (u'voice')
609 vid = voice_id.get_text ()
611 staff_id = n.get_maybe_exist_named_child (u'staff')
614 sid = staff_id.get_text ()
617 if vid and not voices.has_key (vid):
618 voices[vid] = Musicxml_voice()
619 if vid and sid and not n.get_maybe_exist_typed_child (Grace):
620 if not voice_to_staff_dict.has_key (vid):
621 voice_to_staff_dict[vid] = sid
622 # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
623 # need to assign staff-assigned objects like clefs, times, etc. to
624 # all the correct voices. This will never work entirely correct due
625 # to staff-switches, but that's the best we can do!
626 staff_to_voice_dict = {}
627 for (v,s) in voice_to_staff_dict.items ():
628 if not staff_to_voice_dict.has_key (s):
629 staff_to_voice_dict[s] = [v]
631 staff_to_voice_dict[s].append (v)
635 assign_to_next_note = []
638 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
640 if not (voice_id or isinstance (n, Attributes) or
641 isinstance (n, Direction) or isinstance (n, Partial) or
642 isinstance (n, Barline) or isinstance (n, Harmony) ):
645 if isinstance (n, Attributes) and not start_attr:
649 if isinstance (n, Attributes):
650 # assign these only to the voices they really belongs to!
651 for (s, vids) in staff_to_voice_dict.items ():
652 staff_attributes = part.extract_attributes_for_staff (n, s)
654 voices[v].add_element (staff_attributes)
657 if isinstance (n, Partial) or isinstance (n, Barline):
658 for v in voices.keys ():
659 voices[v].add_element (n)
662 if isinstance (n, Direction):
663 staff_id = n.get_maybe_exist_named_child (u'staff')
665 staff_id = staff_id.get_text ()
667 dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
669 dir_voices = voices.keys ()
671 voices[v].add_element (n)
674 if isinstance (n, Harmony):
675 # store the harmony element until we encounter the next note
676 # and assign it only to that one voice.
677 assign_to_next_note.append (n)
680 id = voice_id.get_text ()
681 if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
685 for i in assign_to_next_note:
686 voices[id].add_element (i)
687 assign_to_next_note = []
688 voices[id].add_element (n)
690 # Assign all remaining elements from assign_to_next_note to the voice
691 # of the previous note:
692 for i in assign_to_next_note:
693 voices[id].add_element (i)
694 assign_to_next_note = []
697 for (s, vids) in staff_to_voice_dict.items ():
698 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
699 staff_attributes.read_self ()
700 part._staff_attributes_dict[s] = staff_attributes
702 voices[v].insert (0, staff_attributes)
703 voices[v]._elements[0].read_self()
705 part._voices = voices
707 def get_voices (self):
709 def get_staff_attributes (self):
710 return self._staff_attributes_dict
712 class Notations (Music_xml_node):
714 ts = self.get_named_children ('tied')
715 starts = [t for t in ts if t.type == 'start']
721 def get_tuplets (self):
722 return self.get_typed_children (Tuplet)
724 class Time_modification(Music_xml_node):
725 def get_fraction (self):
726 b = self.get_maybe_exist_named_child ('actual-notes')
727 a = self.get_maybe_exist_named_child ('normal-notes')
728 return (int(a.get_text ()), int (b.get_text ()))
730 class Accidental (Music_xml_node):
732 Music_xml_node.__init__ (self)
733 self.editorial = False
734 self.cautionary = False
736 class Music_xml_spanner (Music_xml_node):
738 if hasattr (self, 'type'):
743 if hasattr (self, 'size'):
744 return string.atoi (self.size)
748 class Wedge (Music_xml_spanner):
751 class Tuplet (Music_xml_spanner):
754 class Bracket (Music_xml_spanner):
757 class Dashes (Music_xml_spanner):
760 class Slur (Music_xml_spanner):
764 class Beam (Music_xml_spanner):
766 return self.get_text ()
767 def is_primary (self):
768 return self.number == "1"
770 class Wavy_line (Music_xml_spanner):
773 class Pedal (Music_xml_spanner):
776 class Glissando (Music_xml_spanner):
779 class Slide (Music_xml_spanner):
782 class Octave_shift (Music_xml_spanner):
783 # default is 8 for the octave-shift!
785 if hasattr (self, 'size'):
786 return string.atoi (self.size)
790 class Chord (Music_xml_node):
793 class Dot (Music_xml_node):
796 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
797 # for the inner <rest> element, not the whole rest block.
798 class Rest (Music_xml_node):
800 Music_xml_node.__init__ (self)
801 self._is_whole_measure = False
802 def is_whole_measure (self):
803 return self._is_whole_measure
805 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
807 step = ch.get_text ().strip ()
811 def get_octave (self):
812 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
814 step = ch.get_text ().strip ()
819 class Type (Music_xml_node):
821 class Grace (Music_xml_node):
823 class Staff (Music_xml_node):
826 class Direction (Music_xml_node):
828 class DirType (Music_xml_node):
831 class Bend (Music_xml_node):
832 def bend_alter (self):
833 alter = self.get_maybe_exist_named_child ('bend-alter')
835 return alter.get_text()
839 class Words (Music_xml_node):
842 class Harmony (Music_xml_node):
845 class Frame (Music_xml_node):
846 def get_frets (self):
847 return self.get_named_child_value_number ('frame-frets', 4)
848 def get_strings (self):
849 return self.get_named_child_value_number ('frame-strings', 6)
850 def get_first_fret (self):
851 return self.get_named_child_value_number ('first-fret', 1)
852 class Frame_Note (Music_xml_node):
853 def get_string (self):
854 return self.get_named_child_value_number ('string', 1)
856 return self.get_named_child_value_number ('fret', 0)
857 def get_fingering (self):
858 return self.get_named_child_value_number ('fingering', -1)
859 def get_barre (self):
860 n = self.get_maybe_exist_named_child ('barre')
862 return getattr (n, 'type', '')
867 ## need this, not all classes are instantiated
868 ## for every input file. Only add those classes, that are either directly
869 ## used by class name or extend Music_xml_node in some way!
871 '#comment': Hash_comment,
873 'accidental': Accidental,
874 'attributes': Attributes,
876 'bar-style': BarStyle,
883 'direction': Direction,
884 'direction-type': DirType,
885 'duration': Duration,
887 'frame-note': Frame_Note,
888 'glissando': Glissando,
891 'identification': Identification,
894 'notations': Notations,
896 'octave-shift': Octave_shift,
898 'part-group': Part_group,
899 'part-list': Part_list,
903 'score-part': Score_part,
907 'syllabic': Syllabic,
909 'time-modification': Time_modification,
912 'unpitched': Unpitched,
913 'wavy-line': Wavy_line,
919 def name2class_name (name):
920 name = name.replace ('-', '_')
921 name = name.replace ('#', 'hash_')
922 name = name[0].upper() + name[1:].lower()
926 def get_class (name):
927 classname = class_dict.get (name)
931 class_name = name2class_name (name)
932 klass = new.classobj (class_name, (Music_xml_node,) , {})
933 class_dict[name] = klass
936 def lxml_demarshal_node (node):
941 klass = get_class (name)
944 py_node._original = node
946 py_node._data = node.text
947 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
948 py_node._children = filter (lambda x: x, py_node._children)
950 for c in py_node._children:
953 for (k,v) in node.items ():
954 py_node.__dict__[k] = v
955 py_node._attribute_dict[k] = v
959 def minidom_demarshal_node (node):
962 klass = get_class (name)
965 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
966 for c in py_node._children:
970 for (nm, value) in node.attributes.items():
971 py_node.__dict__[nm] = value
972 py_node._attribute_dict[nm] = value
975 if node.nodeType == node.TEXT_NODE and node.data:
976 py_node._data = node.data
978 py_node._original = node
982 if __name__ == '__main__':
985 tree = lxml.etree.parse ('beethoven.xml')
986 mxl_tree = lxml_demarshal_node (tree.getroot ())
987 ks = class_dict.keys()