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 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)
328 self.message ("Encountered note at %s with %s duration (no <type> element):" % (self.start, self.duration) )
331 def get_factor (self):
334 def get_pitches (self):
335 return self.get_typed_children (get_class (u'pitch'))
337 class Part_list (Music_xml_node):
339 Music_xml_node.__init__ (self)
340 self._id_instrument_name_dict = {}
342 def generate_id_instrument_dict (self):
344 ## not empty to make sure this happens only once.
346 for score_part in self.get_named_children ('score-part'):
347 for instr in score_part.get_named_children ('score-instrument'):
349 name = instr.get_named_child ("instrument-name")
350 mapping[id] = name.get_text ()
352 self._id_instrument_name_dict = mapping
354 def get_instrument (self, id):
355 if not self._id_instrument_name_dict:
356 self.generate_id_instrument_dict()
358 instrument_name = self._id_instrument_name_dict.get (id)
360 return instrument_name
362 sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
365 class Part_group (Music_xml_node):
367 class Score_part (Music_xml_node):
370 class Measure (Music_xml_node):
372 Music_xml_node.__init__ (self)
374 def is_implicit (self):
375 return hasattr (self, 'implicit') and self.implicit == 'yes'
376 def get_notes (self):
377 return self.get_typed_children (get_class (u'note'))
379 class Syllabic (Music_xml_node):
380 def continued (self):
381 text = self.get_text()
382 return (text == "begin") or (text == "middle")
383 class Text (Music_xml_node):
386 class Lyric (Music_xml_node):
387 def get_number (self):
388 if hasattr (self, 'number'):
393 def lyric_to_text (self):
395 syllabic = self.get_maybe_exist_typed_child (Syllabic)
397 continued = syllabic.continued ()
398 text = self.get_maybe_exist_typed_child (Text)
401 text = text.get_text()
402 # We need to convert soft hyphens to -, otherwise the ascii codec as well
403 # as lilypond will barf on that character
404 text = string.replace( text, u'\xad', '-' )
406 if text == "-" and continued:
408 elif text == "_" and continued:
410 elif continued and text:
411 return escape_ly_output_string (text) + " --"
415 return escape_ly_output_string (text)
419 class Musicxml_voice:
423 self._start_staff = None
425 self._has_lyrics = False
427 def add_element (self, e):
428 self._elements.append (e)
429 if (isinstance (e, Note)
430 and e.get_maybe_exist_typed_child (Staff)):
431 name = e.get_maybe_exist_typed_child (Staff).get_text ()
433 if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
434 self._start_staff = name
435 self._staves[name] = True
437 lyrics = e.get_typed_children (Lyric)
438 if not self._has_lyrics:
439 self.has_lyrics = len (lyrics) > 0
443 if (nr > 0) and not (nr in self._lyrics):
444 self._lyrics.append (nr)
446 def insert (self, idx, e):
447 self._elements.insert (idx, e)
449 def get_lyrics_numbers (self):
450 if (len (self._lyrics) == 0) and self._has_lyrics:
451 #only happens if none of the <lyric> tags has a number attribute
457 class Part (Music_xml_node):
459 Music_xml_node.__init__ (self)
461 self._staff_attributes_dict = {}
463 def get_part_list (self):
465 while n and n.get_name() != 'score-partwise':
468 return n.get_named_child ('part-list')
470 def interpret (self):
471 """Set durations and starting points."""
472 """The starting point of the very first note is 0!"""
474 part_list = self.get_part_list ()
477 factor = Rational (1)
479 attributes_object = None
480 measures = self.get_typed_children (Measure)
481 last_moment = Rational (-1)
482 last_measure_position = Rational (-1)
483 measure_position = Rational (0)
484 measure_start_moment = now
485 is_first_measure = True
486 previous_measure = None
488 # implicit measures are used for artificial measures, e.g. when
489 # a repeat bar line splits a bar into two halves. In this case,
490 # don't reset the measure position to 0. They are also used for
491 # upbeats (initial value of 0 fits these, too).
492 # Also, don't reset the measure position at the end of the loop,
493 # but rather when starting the next measure (since only then do we
494 # know if the next measure is implicit and continues that measure)
495 if not m.is_implicit ():
496 # Warn about possibly overfull measures and reset the position
497 if attributes_object and previous_measure and previous_measure.partial == 0:
498 length = attributes_object.get_measure_length ()
499 new_now = measure_start_moment + length
501 problem = 'incomplete'
504 ## only for verbose operation.
505 if problem <> 'incomplete' and previous_measure:
506 previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
508 measure_start_moment = now
509 measure_position = Rational (0)
511 for n in m.get_all_children ():
512 if isinstance (n, Hash_text):
516 if n.__class__ == Attributes:
517 n.set_attributes_from_previous (attributes_dict)
519 attributes_dict = n._dict.copy ()
520 attributes_object = n
522 factor = Rational (1,
523 int (attributes_dict.get ('divisions').get_text ()))
526 if (n.get_maybe_exist_typed_child (Duration)):
527 mxl_dur = n.get_maybe_exist_typed_child (Duration)
528 dur = mxl_dur.get_length () * factor
530 if n.get_name() == 'backup':
532 if n.get_maybe_exist_typed_child (Grace):
535 rest = n.get_maybe_exist_typed_child (Rest)
537 and attributes_object
538 and attributes_object.get_measure_length () == dur):
540 rest._is_whole_measure = True
542 if (dur > Rational (0)
543 and n.get_maybe_exist_typed_child (Chord)):
545 measure_position = last_measure_position
548 n._measure_position = measure_position
550 if dur > Rational (0):
552 last_measure_position = measure_position
554 measure_position += dur
555 elif dur < Rational (0):
556 # backup element, reset measure position
558 measure_position += dur
559 if measure_position < 0:
560 # backup went beyond the measure start => reset to 0
561 now -= measure_position
564 last_measure_position = measure_position
565 if n._name == 'note':
566 instrument = n.get_maybe_exist_named_child ('instrument')
568 n.instrument_name = part_list.get_instrument (instrument.id)
570 # Incomplete first measures are not padded, but registered as partial
572 is_first_measure = False
573 # upbeats are marked as implicit measures
574 if attributes_object and m.is_implicit ():
575 length = attributes_object.get_measure_length ()
576 measure_end = measure_start_moment + length
577 if measure_end <> now:
581 # modify attributes so that only those applying to the given staff remain
582 def extract_attributes_for_staff (part, attr, staff):
583 attributes = copy.copy (attr)
584 attributes._children = copy.copy (attr._children)
585 attributes._dict = attr._dict.copy ()
586 for c in attributes._children:
587 if hasattr (c, 'number') and c.number != staff:
588 attributes._children.remove (c)
591 def extract_voices (part):
593 measures = part.get_typed_children (Measure)
597 elements.append (Partial (m.partial))
598 elements.extend (m.get_all_children ())
599 # make sure we know all voices already so that dynamics, clefs, etc.
600 # can be assigned to the correct voices
601 voice_to_staff_dict = {}
603 voice_id = n.get_maybe_exist_named_child (u'voice')
606 vid = voice_id.get_text ()
608 staff_id = n.get_maybe_exist_named_child (u'staff')
611 sid = staff_id.get_text ()
614 if vid and not voices.has_key (vid):
615 voices[vid] = Musicxml_voice()
616 if vid and sid and not n.get_maybe_exist_typed_child (Grace):
617 if not voice_to_staff_dict.has_key (vid):
618 voice_to_staff_dict[vid] = sid
619 # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
620 # need to assign staff-assigned objects like clefs, times, etc. to
621 # all the correct voices. This will never work entirely correct due
622 # to staff-switches, but that's the best we can do!
623 staff_to_voice_dict = {}
624 for (v,s) in voice_to_staff_dict.items ():
625 if not staff_to_voice_dict.has_key (s):
626 staff_to_voice_dict[s] = [v]
628 staff_to_voice_dict[s].append (v)
632 assign_to_next_note = []
635 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
637 if not (voice_id or isinstance (n, Attributes) or
638 isinstance (n, Direction) or isinstance (n, Partial) or
639 isinstance (n, Barline) or isinstance (n, Harmony) ):
642 if isinstance (n, Attributes) and not start_attr:
646 if isinstance (n, Attributes):
647 # assign these only to the voices they really belongs to!
648 for (s, vids) in staff_to_voice_dict.items ():
649 staff_attributes = part.extract_attributes_for_staff (n, s)
651 voices[v].add_element (staff_attributes)
654 if isinstance (n, Partial) or isinstance (n, Barline):
655 for v in voices.keys ():
656 voices[v].add_element (n)
659 if isinstance (n, Direction):
660 staff_id = n.get_maybe_exist_named_child (u'staff')
662 staff_id = staff_id.get_text ()
664 dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
666 dir_voices = voices.keys ()
668 voices[v].add_element (n)
671 if isinstance (n, Harmony):
672 # store the harmony element until we encounter the next note
673 # and assign it only to that one voice.
674 assign_to_next_note.append (n)
677 id = voice_id.get_text ()
678 if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
682 for i in assign_to_next_note:
683 voices[id].add_element (i)
684 assign_to_next_note = []
685 voices[id].add_element (n)
687 # Assign all remaining elements from assign_to_next_note to the voice
688 # of the previous note:
689 for i in assign_to_next_note:
690 voices[id].add_element (i)
691 assign_to_next_note = []
694 for (s, vids) in staff_to_voice_dict.items ():
695 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
696 staff_attributes.read_self ()
697 part._staff_attributes_dict[s] = staff_attributes
699 voices[v].insert (0, staff_attributes)
700 voices[v]._elements[0].read_self()
702 part._voices = voices
704 def get_voices (self):
706 def get_staff_attributes (self):
707 return self._staff_attributes_dict
709 class Notations (Music_xml_node):
711 ts = self.get_named_children ('tied')
712 starts = [t for t in ts if t.type == 'start']
718 def get_tuplets (self):
719 return self.get_typed_children (Tuplet)
721 class Time_modification(Music_xml_node):
722 def get_fraction (self):
723 b = self.get_maybe_exist_named_child ('actual-notes')
724 a = self.get_maybe_exist_named_child ('normal-notes')
725 return (int(a.get_text ()), int (b.get_text ()))
727 class Accidental (Music_xml_node):
729 Music_xml_node.__init__ (self)
730 self.editorial = False
731 self.cautionary = False
733 class Music_xml_spanner (Music_xml_node):
735 if hasattr (self, 'type'):
740 if hasattr (self, 'size'):
741 return string.atoi (self.size)
745 class Wedge (Music_xml_spanner):
748 class Tuplet (Music_xml_spanner):
751 class Slur (Music_xml_spanner):
755 class Beam (Music_xml_spanner):
757 return self.get_text ()
758 def is_primary (self):
759 return self.number == "1"
761 class Wavy_line (Music_xml_spanner):
764 class Pedal (Music_xml_spanner):
767 class Glissando (Music_xml_spanner):
770 class Octave_shift (Music_xml_spanner):
771 # default is 8 for the octave-shift!
773 if hasattr (self, 'size'):
774 return string.atoi (self.size)
778 class Chord (Music_xml_node):
781 class Dot (Music_xml_node):
784 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
785 # for the inner <rest> element, not the whole rest block.
786 class Rest (Music_xml_node):
788 Music_xml_node.__init__ (self)
789 self._is_whole_measure = False
790 def is_whole_measure (self):
791 return self._is_whole_measure
793 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
795 step = ch.get_text ().strip ()
799 def get_octave (self):
800 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
802 step = ch.get_text ().strip ()
807 class Type (Music_xml_node):
809 class Grace (Music_xml_node):
811 class Staff (Music_xml_node):
814 class Direction (Music_xml_node):
816 class DirType (Music_xml_node):
819 class Bend (Music_xml_node):
820 def bend_alter (self):
821 alter = self.get_maybe_exist_named_child ('bend-alter')
823 return alter.get_text()
827 class Words (Music_xml_node):
830 class Harmony (Music_xml_node):
833 class Frame (Music_xml_node):
834 def get_frets (self):
835 return self.get_named_child_value_number ('frame-frets', 4)
836 def get_strings (self):
837 return self.get_named_child_value_number ('frame-strings', 6)
838 def get_first_fret (self):
839 return self.get_named_child_value_number ('first-fret', 1)
840 class Frame_Note (Music_xml_node):
841 def get_string (self):
842 return self.get_named_child_value_number ('string', 1)
844 return self.get_named_child_value_number ('fret', 0)
845 def get_fingering (self):
846 return self.get_named_child_value_number ('fingering', -1)
847 def get_barre (self):
848 n = self.get_maybe_exist_named_child ('barre')
850 return getattr (n, 'type', '')
855 ## need this, not all classes are instantiated
856 ## for every input file. Only add those classes, that are either directly
857 ## used by class name or extend Music_xml_node in some way!
859 '#comment': Hash_comment,
861 'accidental': Accidental,
862 'attributes': Attributes,
864 'bar-style': BarStyle,
869 'direction': Direction,
870 'direction-type': DirType,
871 'duration': Duration,
873 'frame-note': Frame_Note,
874 'glissando': Glissando,
877 'identification': Identification,
880 'notations': Notations,
882 'octave-shift': Octave_shift,
884 'part-group': Part_group,
885 'part-list': Part_list,
889 'score-part': Score_part,
892 'syllabic': Syllabic,
894 'time-modification': Time_modification,
897 'unpitched': Unpitched,
898 'wavy-line': Wavy_line,
904 def name2class_name (name):
905 name = name.replace ('-', '_')
906 name = name.replace ('#', 'hash_')
907 name = name[0].upper() + name[1:].lower()
911 def get_class (name):
912 classname = class_dict.get (name)
916 class_name = name2class_name (name)
917 klass = new.classobj (class_name, (Music_xml_node,) , {})
918 class_dict[name] = klass
921 def lxml_demarshal_node (node):
926 klass = get_class (name)
929 py_node._original = node
931 py_node._data = node.text
932 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
933 py_node._children = filter (lambda x: x, py_node._children)
935 for c in py_node._children:
938 for (k,v) in node.items ():
939 py_node.__dict__[k] = v
940 py_node._attribute_dict[k] = v
944 def minidom_demarshal_node (node):
947 klass = get_class (name)
950 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
951 for c in py_node._children:
955 for (nm, value) in node.attributes.items():
956 py_node.__dict__[nm] = value
957 py_node._attribute_dict[nm] = value
960 if node.nodeType == node.TEXT_NODE and node.data:
961 py_node._data = node.data
963 py_node._original = node
967 if __name__ == '__main__':
970 tree = lxml.etree.parse ('beethoven.xml')
971 mxl_tree = lxml_demarshal_node (tree.getroot ())
972 ks = class_dict.keys()