1 # -*- coding: utf-8 -*-
13 ly.stderr_write ((_ ("error: %s") % str) + "\n")
16 def escape_ly_output_string (input_string):
17 return_string = input_string
18 needs_quotes = not re.match (u"^[a-zA-ZäöüÜÄÖßñ]*$", return_string);
20 return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
29 self._name = 'xml_node'
31 self._attribute_dict = {}
33 def get_parent (self):
37 return self._parent.get_typed_children (self.__class__)[0] == self
48 if not self._children:
51 return ''.join ([c.get_text () for c in self._children])
53 def message (self, msg):
54 ly.stderr_write (msg+'\n')
58 sys.stderr.write (' In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()])))
61 def get_typed_children (self, klass):
65 return [c for c in self._children if isinstance(c, klass)]
67 def get_named_children (self, nm):
68 return self.get_typed_children (get_class (nm))
70 def get_named_child (self, nm):
71 return self.get_maybe_exist_named_child (nm)
73 def get_children (self, predicate):
74 return [c for c in self._children if predicate(c)]
76 def get_all_children (self):
79 def get_maybe_exist_named_child (self, name):
80 return self.get_maybe_exist_typed_child (get_class (name))
82 def get_maybe_exist_typed_child (self, klass):
83 cn = self.get_typed_children (klass)
89 raise "More than 1 child", klass
91 def get_unique_typed_child (self, klass):
92 cn = self.get_typed_children(klass)
94 sys.stderr.write (self.__dict__ + '\n')
95 raise 'Child is not unique for', (klass, 'found', cn)
99 def get_named_child_value_number (self, name, default):
100 n = self.get_maybe_exist_named_child (name)
102 return string.atoi (n.get_text())
107 class Music_xml_node (Xml_node):
109 Xml_node.__init__ (self)
110 self.duration = Rational (0)
111 self.start = Rational (0)
113 class Work (Xml_node):
114 def get_work_information (self, tag):
115 wt = self.get_maybe_exist_named_child (tag)
117 return wt.get_text ()
121 def get_work_title (self):
122 return self.get_work_information ('work-title')
123 def get_work_number (self):
124 return self.get_work_information ('work-number')
126 return self.get_work_information ('opus')
128 class Identification (Xml_node):
129 def get_rights (self):
130 rights = self.get_maybe_exist_named_child ('rights')
132 return rights.get_text ()
136 def get_creator (self, type):
137 creators = self.get_named_children ('creator')
138 # return the first creator tag that has the particular type
140 if hasattr (i, 'type') and i.type == type:
144 def get_composer (self):
145 c = self.get_creator ('composer')
148 creators = self.get_named_children ('creator')
149 # return the first creator tag that has no type at all
151 if not hasattr (i, 'type'):
154 def get_arranger (self):
155 return self.get_creator ('arranger')
156 def get_editor (self):
157 return self.get_creator ('editor')
159 v = self.get_creator ('lyricist')
162 v = self.get_creator ('poet')
165 def get_encoding_information (self, type):
166 enc = self.get_named_children ('encoding')
168 children = enc[0].get_named_children (type)
170 return children[0].get_text ()
174 def get_encoding_software (self):
175 return self.get_encoding_information ('software')
176 def get_encoding_date (self):
177 return self.get_encoding_information ('encoding-date')
178 def get_encoding_person (self):
179 return self.get_encoding_information ('encoder')
180 def get_encoding_description (self):
181 return self.get_encoding_information ('encoding-description')
183 def get_encoding_software_list (self):
184 enc = self.get_named_children ('encoding')
187 softwares = e.get_named_children ('software')
189 software.append (s.get_text ())
194 class Duration (Music_xml_node):
195 def get_length (self):
196 dur = int (self.get_text ()) * Rational (1,4)
199 class Hash_comment (Music_xml_node):
201 class Hash_text (Music_xml_node):
204 class Pitch (Music_xml_node):
206 ch = self.get_unique_typed_child (get_class (u'step'))
207 step = ch.get_text ().strip ()
209 def get_octave (self):
210 ch = self.get_unique_typed_child (get_class (u'octave'))
212 step = ch.get_text ().strip ()
215 def get_alteration (self):
216 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
219 alter = int (ch.get_text ().strip ())
222 class Unpitched (Music_xml_node):
224 ch = self.get_unique_typed_child (get_class (u'display-step'))
225 step = ch.get_text ().strip ()
228 def get_octave (self):
229 ch = self.get_unique_typed_child (get_class (u'display-octave'))
232 octave = ch.get_text ().strip ()
237 class Measure_element (Music_xml_node):
238 def get_voice_id (self):
239 voice_id = self.get_maybe_exist_named_child ('voice')
241 return voice_id.get_text ()
246 cn = self._parent.get_typed_children (self.__class__)
247 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
250 class Attributes (Measure_element):
252 Measure_element.__init__ (self)
255 def set_attributes_from_previous (self, dict):
256 self._dict.update (dict)
258 def read_self (self):
259 for c in self.get_all_children ():
260 self._dict[c.get_name()] = c
262 def get_named_attribute (self, name):
263 return self._dict.get (name)
265 def get_measure_length (self):
266 (n,d) = self.get_time_signature ()
267 return Rational (n,d)
269 def get_time_signature (self):
270 "return time sig as a (beat, beat-type) tuple"
273 mxl = self.get_named_attribute ('time')
275 beats = mxl.get_maybe_exist_named_child ('beats')
276 type = mxl.get_maybe_exist_named_child ('beat-type')
277 return (int (beats.get_text ()),
278 int (type.get_text ()))
282 error (_ ("requested time signature, but time sig is unknown"))
285 # returns clef information in the form ("cleftype", position, octave-shift)
286 def get_clef_information (self):
287 clefinfo = ['G', 2, 0]
288 mxl = self.get_named_attribute ('clef')
291 sign = mxl.get_maybe_exist_named_child ('sign')
293 clefinfo[0] = sign.get_text()
294 line = mxl.get_maybe_exist_named_child ('line')
296 clefinfo[1] = string.atoi (line.get_text ())
297 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
299 clefinfo[2] = string.atoi (octave.get_text ())
302 def get_key_signature (self):
303 "return (fifths, mode) tuple"
305 key = self.get_named_attribute ('key')
306 mode_node = key.get_maybe_exist_named_child ('mode')
309 mode = mode_node.get_text ()
311 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
312 return (fifths, mode)
314 class Barline (Measure_element):
316 class BarStyle (Music_xml_node):
318 class Partial (Measure_element):
319 def __init__ (self, partial):
320 Measure_element.__init__ (self)
321 self.partial = partial
323 class Note (Measure_element):
325 Measure_element.__init__ (self)
326 self.instrument_name = ''
328 def get_duration_log (self):
329 ch = self.get_maybe_exist_named_child (u'type')
332 log = ch.get_text ().strip()
343 'longa': -2}.get (log, 0)
344 elif self.get_maybe_exist_named_child (u'grace'):
345 # FIXME: is it ok to default to eight note for grace notes?
348 self.message (_ ("Encountered note at %s with %s duration (no <type> element):") % (self.start, self.duration) )
351 def get_factor (self):
354 def get_pitches (self):
355 return self.get_typed_children (get_class (u'pitch'))
357 class Part_list (Music_xml_node):
359 Music_xml_node.__init__ (self)
360 self._id_instrument_name_dict = {}
362 def generate_id_instrument_dict (self):
364 ## not empty to make sure this happens only once.
366 for score_part in self.get_named_children ('score-part'):
367 for instr in score_part.get_named_children ('score-instrument'):
369 name = instr.get_named_child ("instrument-name")
370 mapping[id] = name.get_text ()
372 self._id_instrument_name_dict = mapping
374 def get_instrument (self, id):
375 if not self._id_instrument_name_dict:
376 self.generate_id_instrument_dict()
378 instrument_name = self._id_instrument_name_dict.get (id)
380 return instrument_name
382 ly.stderr_write (_ ("Unable to find instrument for ID=%s\n") % id)
385 class Part_group (Music_xml_node):
387 class Score_part (Music_xml_node):
390 class Measure (Music_xml_node):
392 Music_xml_node.__init__ (self)
394 def is_implicit (self):
395 return hasattr (self, 'implicit') and self.implicit == 'yes'
396 def get_notes (self):
397 return self.get_typed_children (get_class (u'note'))
399 class Syllabic (Music_xml_node):
400 def continued (self):
401 text = self.get_text()
402 return (text == "begin") or (text == "middle")
403 class Text (Music_xml_node):
406 class Lyric (Music_xml_node):
407 def get_number (self):
408 if hasattr (self, 'number'):
413 def lyric_to_text (self):
415 syllabic = self.get_maybe_exist_typed_child (Syllabic)
417 continued = syllabic.continued ()
418 text = self.get_maybe_exist_typed_child (Text)
421 text = text.get_text()
422 # We need to convert soft hyphens to -, otherwise the ascii codec as well
423 # as lilypond will barf on that character
424 text = string.replace( text, u'\xad', '-' )
426 if text == "-" and continued:
428 elif text == "_" and continued:
430 elif continued and text:
431 return escape_ly_output_string (text) + " --"
435 return escape_ly_output_string (text)
439 class Musicxml_voice:
443 self._start_staff = None
445 self._has_lyrics = False
447 def add_element (self, e):
448 self._elements.append (e)
449 if (isinstance (e, Note)
450 and e.get_maybe_exist_typed_child (Staff)):
451 name = e.get_maybe_exist_typed_child (Staff).get_text ()
453 if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
454 self._start_staff = name
455 self._staves[name] = True
457 lyrics = e.get_typed_children (Lyric)
458 if not self._has_lyrics:
459 self.has_lyrics = len (lyrics) > 0
463 if (nr > 0) and not (nr in self._lyrics):
464 self._lyrics.append (nr)
466 def insert (self, idx, e):
467 self._elements.insert (idx, e)
469 def get_lyrics_numbers (self):
470 if (len (self._lyrics) == 0) and self._has_lyrics:
471 #only happens if none of the <lyric> tags has a number attribute
477 class Part (Music_xml_node):
479 Music_xml_node.__init__ (self)
481 self._staff_attributes_dict = {}
483 def get_part_list (self):
485 while n and n.get_name() != 'score-partwise':
488 return n.get_named_child ('part-list')
490 def interpret (self):
491 """Set durations and starting points."""
492 """The starting point of the very first note is 0!"""
494 part_list = self.get_part_list ()
497 factor = Rational (1)
499 attributes_object = None
500 measures = self.get_typed_children (Measure)
501 last_moment = Rational (-1)
502 last_measure_position = Rational (-1)
503 measure_position = Rational (0)
504 measure_start_moment = now
505 is_first_measure = True
506 previous_measure = None
508 # implicit measures are used for artificial measures, e.g. when
509 # a repeat bar line splits a bar into two halves. In this case,
510 # don't reset the measure position to 0. They are also used for
511 # upbeats (initial value of 0 fits these, too).
512 # Also, don't reset the measure position at the end of the loop,
513 # but rather when starting the next measure (since only then do we
514 # know if the next measure is implicit and continues that measure)
515 if not m.is_implicit ():
516 # Warn about possibly overfull measures and reset the position
517 if attributes_object and previous_measure and previous_measure.partial == 0:
518 length = attributes_object.get_measure_length ()
519 new_now = measure_start_moment + length
521 problem = 'incomplete'
524 ## only for verbose operation.
525 if problem <> 'incomplete' and previous_measure:
526 previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
528 measure_start_moment = now
529 measure_position = Rational (0)
531 for n in m.get_all_children ():
532 # figured bass has a duration, but applies to the next note
533 # and should not change the current measure position!
534 if isinstance (n, FiguredBass):
535 n._divisions = factor.denominator ()
538 if isinstance (n, Hash_text):
542 if n.__class__ == Attributes:
543 n.set_attributes_from_previous (attributes_dict)
545 attributes_dict = n._dict.copy ()
546 attributes_object = n
548 factor = Rational (1,
549 int (attributes_dict.get ('divisions').get_text ()))
552 if (n.get_maybe_exist_typed_child (Duration)):
553 mxl_dur = n.get_maybe_exist_typed_child (Duration)
554 dur = mxl_dur.get_length () * factor
556 if n.get_name() == 'backup':
558 if n.get_maybe_exist_typed_child (Grace):
561 rest = n.get_maybe_exist_typed_child (Rest)
563 and attributes_object
564 and attributes_object.get_measure_length () == dur):
566 rest._is_whole_measure = True
568 if (dur > Rational (0)
569 and n.get_maybe_exist_typed_child (Chord)):
571 measure_position = last_measure_position
574 n._measure_position = measure_position
576 if dur > Rational (0):
578 last_measure_position = measure_position
580 measure_position += dur
581 elif dur < Rational (0):
582 # backup element, reset measure position
584 measure_position += dur
585 if measure_position < 0:
586 # backup went beyond the measure start => reset to 0
587 now -= measure_position
590 last_measure_position = measure_position
591 if n._name == 'note':
592 instrument = n.get_maybe_exist_named_child ('instrument')
594 n.instrument_name = part_list.get_instrument (instrument.id)
596 # Incomplete first measures are not padded, but registered as partial
598 is_first_measure = False
599 # upbeats are marked as implicit measures
600 if attributes_object and m.is_implicit ():
601 length = attributes_object.get_measure_length ()
602 measure_end = measure_start_moment + length
603 if measure_end <> now:
607 # modify attributes so that only those applying to the given staff remain
608 def extract_attributes_for_staff (part, attr, staff):
609 attributes = copy.copy (attr)
610 attributes._children = copy.copy (attr._children)
611 attributes._dict = attr._dict.copy ()
612 for c in attributes._children:
613 if hasattr (c, 'number') and c.number != staff:
614 attributes._children.remove (c)
617 def extract_voices (part):
619 measures = part.get_typed_children (Measure)
623 elements.append (Partial (m.partial))
624 elements.extend (m.get_all_children ())
625 # make sure we know all voices already so that dynamics, clefs, etc.
626 # can be assigned to the correct voices
627 voice_to_staff_dict = {}
629 voice_id = n.get_maybe_exist_named_child (u'voice')
632 vid = voice_id.get_text ()
634 staff_id = n.get_maybe_exist_named_child (u'staff')
637 sid = staff_id.get_text ()
640 if vid and not voices.has_key (vid):
641 voices[vid] = Musicxml_voice()
642 if vid and sid and not n.get_maybe_exist_typed_child (Grace):
643 if not voice_to_staff_dict.has_key (vid):
644 voice_to_staff_dict[vid] = sid
645 # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
646 # need to assign staff-assigned objects like clefs, times, etc. to
647 # all the correct voices. This will never work entirely correct due
648 # to staff-switches, but that's the best we can do!
649 staff_to_voice_dict = {}
650 for (v,s) in voice_to_staff_dict.items ():
651 if not staff_to_voice_dict.has_key (s):
652 staff_to_voice_dict[s] = [v]
654 staff_to_voice_dict[s].append (v)
658 assign_to_next_note = []
661 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
663 if not (voice_id or isinstance (n, Attributes) or
664 isinstance (n, Direction) or isinstance (n, Partial) or
665 isinstance (n, Barline) or isinstance (n, Harmony) or
666 isinstance (n, FiguredBass) ):
669 if isinstance (n, Attributes) and not start_attr:
673 if isinstance (n, Attributes):
674 # assign these only to the voices they really belongs to!
675 for (s, vids) in staff_to_voice_dict.items ():
676 staff_attributes = part.extract_attributes_for_staff (n, s)
678 voices[v].add_element (staff_attributes)
681 if isinstance (n, Partial) or isinstance (n, Barline):
682 for v in voices.keys ():
683 voices[v].add_element (n)
686 if isinstance (n, Direction):
687 staff_id = n.get_maybe_exist_named_child (u'staff')
689 staff_id = staff_id.get_text ()
691 dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
693 dir_voices = voices.keys ()
695 voices[v].add_element (n)
698 if isinstance (n, Harmony) or isinstance (n, FiguredBass):
699 # store the harmony or figured bass element until we encounter
700 # the next note and assign it only to that one voice.
701 assign_to_next_note.append (n)
704 id = voice_id.get_text ()
705 if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
709 for i in assign_to_next_note:
710 voices[id].add_element (i)
711 assign_to_next_note = []
712 voices[id].add_element (n)
714 # Assign all remaining elements from assign_to_next_note to the voice
715 # of the previous note:
716 for i in assign_to_next_note:
717 voices[id].add_element (i)
718 assign_to_next_note = []
721 for (s, vids) in staff_to_voice_dict.items ():
722 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
723 staff_attributes.read_self ()
724 part._staff_attributes_dict[s] = staff_attributes
726 voices[v].insert (0, staff_attributes)
727 voices[v]._elements[0].read_self()
729 part._voices = voices
731 def get_voices (self):
733 def get_staff_attributes (self):
734 return self._staff_attributes_dict
736 class Notations (Music_xml_node):
738 ts = self.get_named_children ('tied')
739 starts = [t for t in ts if t.type == 'start']
745 def get_tuplets (self):
746 return self.get_typed_children (Tuplet)
748 class Time_modification(Music_xml_node):
749 def get_fraction (self):
750 b = self.get_maybe_exist_named_child ('actual-notes')
751 a = self.get_maybe_exist_named_child ('normal-notes')
752 return (int(a.get_text ()), int (b.get_text ()))
754 class Accidental (Music_xml_node):
756 Music_xml_node.__init__ (self)
757 self.editorial = False
758 self.cautionary = False
760 class Music_xml_spanner (Music_xml_node):
762 if hasattr (self, 'type'):
767 if hasattr (self, 'size'):
768 return string.atoi (self.size)
772 class Wedge (Music_xml_spanner):
775 class Tuplet (Music_xml_spanner):
778 class Bracket (Music_xml_spanner):
781 class Dashes (Music_xml_spanner):
784 class Slur (Music_xml_spanner):
788 class Beam (Music_xml_spanner):
790 return self.get_text ()
791 def is_primary (self):
792 return self.number == "1"
794 class Wavy_line (Music_xml_spanner):
797 class Pedal (Music_xml_spanner):
800 class Glissando (Music_xml_spanner):
803 class Slide (Music_xml_spanner):
806 class Octave_shift (Music_xml_spanner):
807 # default is 8 for the octave-shift!
809 if hasattr (self, 'size'):
810 return string.atoi (self.size)
814 class Chord (Music_xml_node):
817 class Dot (Music_xml_node):
820 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
821 # for the inner <rest> element, not the whole rest block.
822 class Rest (Music_xml_node):
824 Music_xml_node.__init__ (self)
825 self._is_whole_measure = False
826 def is_whole_measure (self):
827 return self._is_whole_measure
829 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
831 step = ch.get_text ().strip ()
835 def get_octave (self):
836 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
838 step = ch.get_text ().strip ()
843 class Type (Music_xml_node):
845 class Grace (Music_xml_node):
847 class Staff (Music_xml_node):
850 class Direction (Music_xml_node):
852 class DirType (Music_xml_node):
855 class Bend (Music_xml_node):
856 def bend_alter (self):
857 alter = self.get_maybe_exist_named_child ('bend-alter')
859 return alter.get_text()
863 class Words (Music_xml_node):
866 class Harmony (Music_xml_node):
869 class Frame (Music_xml_node):
870 def get_frets (self):
871 return self.get_named_child_value_number ('frame-frets', 4)
872 def get_strings (self):
873 return self.get_named_child_value_number ('frame-strings', 6)
874 def get_first_fret (self):
875 return self.get_named_child_value_number ('first-fret', 1)
876 class Frame_Note (Music_xml_node):
877 def get_string (self):
878 return self.get_named_child_value_number ('string', 1)
880 return self.get_named_child_value_number ('fret', 0)
881 def get_fingering (self):
882 return self.get_named_child_value_number ('fingering', -1)
883 def get_barre (self):
884 n = self.get_maybe_exist_named_child ('barre')
886 return getattr (n, 'type', '')
890 class FiguredBass (Music_xml_node):
895 ## need this, not all classes are instantiated
896 ## for every input file. Only add those classes, that are either directly
897 ## used by class name or extend Music_xml_node in some way!
899 '#comment': Hash_comment,
901 'accidental': Accidental,
902 'attributes': Attributes,
904 'bar-style': BarStyle,
911 'direction': Direction,
912 'direction-type': DirType,
913 'duration': Duration,
915 'frame-note': Frame_Note,
916 'figured-bass': FiguredBass,
917 'glissando': Glissando,
920 'identification': Identification,
923 'notations': Notations,
925 'octave-shift': Octave_shift,
927 'part-group': Part_group,
928 'part-list': Part_list,
932 'score-part': Score_part,
936 'syllabic': Syllabic,
938 'time-modification': Time_modification,
941 'unpitched': Unpitched,
942 'wavy-line': Wavy_line,
948 def name2class_name (name):
949 name = name.replace ('-', '_')
950 name = name.replace ('#', 'hash_')
951 name = name[0].upper() + name[1:].lower()
955 def get_class (name):
956 classname = class_dict.get (name)
960 class_name = name2class_name (name)
961 klass = new.classobj (class_name, (Music_xml_node,) , {})
962 class_dict[name] = klass
965 def lxml_demarshal_node (node):
968 # Ignore comment nodes, which are also returned by the etree parser!
969 if name is None or node.__class__.__name__ == "_Comment":
971 klass = get_class (name)
974 py_node._original = node
976 py_node._data = node.text
977 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
978 py_node._children = filter (lambda x: x, py_node._children)
980 for c in py_node._children:
983 for (k,v) in node.items ():
984 py_node.__dict__[k] = v
985 py_node._attribute_dict[k] = v
989 def minidom_demarshal_node (node):
992 klass = get_class (name)
995 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
996 for c in py_node._children:
1000 for (nm, value) in node.attributes.items():
1001 py_node.__dict__[nm] = value
1002 py_node._attribute_dict[nm] = value
1004 py_node._data = None
1005 if node.nodeType == node.TEXT_NODE and node.data:
1006 py_node._data = node.data
1008 py_node._original = node
1012 if __name__ == '__main__':
1015 tree = lxml.etree.parse ('beethoven.xml')
1016 mxl_tree = lxml_demarshal_node (tree.getroot ())
1017 ks = class_dict.keys()
1019 print '\n'.join (ks)