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 lilylib.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 'long': -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 lilylib.stderr_write (_ ("Unable to find 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 if isinstance (n, Hash_text):
536 if n.__class__ == Attributes:
537 n.set_attributes_from_previous (attributes_dict)
539 attributes_dict = n._dict.copy ()
540 attributes_object = n
542 factor = Rational (1,
543 int (attributes_dict.get ('divisions').get_text ()))
546 if (n.get_maybe_exist_typed_child (Duration)):
547 mxl_dur = n.get_maybe_exist_typed_child (Duration)
548 dur = mxl_dur.get_length () * factor
550 if n.get_name() == 'backup':
552 if n.get_maybe_exist_typed_child (Grace):
555 rest = n.get_maybe_exist_typed_child (Rest)
557 and attributes_object
558 and attributes_object.get_measure_length () == dur):
560 rest._is_whole_measure = True
562 if (dur > Rational (0)
563 and n.get_maybe_exist_typed_child (Chord)):
565 measure_position = last_measure_position
568 n._measure_position = measure_position
570 if dur > Rational (0):
572 last_measure_position = measure_position
574 measure_position += dur
575 elif dur < Rational (0):
576 # backup element, reset measure position
578 measure_position += dur
579 if measure_position < 0:
580 # backup went beyond the measure start => reset to 0
581 now -= measure_position
584 last_measure_position = measure_position
585 if n._name == 'note':
586 instrument = n.get_maybe_exist_named_child ('instrument')
588 n.instrument_name = part_list.get_instrument (instrument.id)
590 # Incomplete first measures are not padded, but registered as partial
592 is_first_measure = False
593 # upbeats are marked as implicit measures
594 if attributes_object and m.is_implicit ():
595 length = attributes_object.get_measure_length ()
596 measure_end = measure_start_moment + length
597 if measure_end <> now:
601 # modify attributes so that only those applying to the given staff remain
602 def extract_attributes_for_staff (part, attr, staff):
603 attributes = copy.copy (attr)
604 attributes._children = copy.copy (attr._children)
605 attributes._dict = attr._dict.copy ()
606 for c in attributes._children:
607 if hasattr (c, 'number') and c.number != staff:
608 attributes._children.remove (c)
611 def extract_voices (part):
613 measures = part.get_typed_children (Measure)
617 elements.append (Partial (m.partial))
618 elements.extend (m.get_all_children ())
619 # make sure we know all voices already so that dynamics, clefs, etc.
620 # can be assigned to the correct voices
621 voice_to_staff_dict = {}
623 voice_id = n.get_maybe_exist_named_child (u'voice')
626 vid = voice_id.get_text ()
628 staff_id = n.get_maybe_exist_named_child (u'staff')
631 sid = staff_id.get_text ()
634 if vid and not voices.has_key (vid):
635 voices[vid] = Musicxml_voice()
636 if vid and sid and not n.get_maybe_exist_typed_child (Grace):
637 if not voice_to_staff_dict.has_key (vid):
638 voice_to_staff_dict[vid] = sid
639 # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
640 # need to assign staff-assigned objects like clefs, times, etc. to
641 # all the correct voices. This will never work entirely correct due
642 # to staff-switches, but that's the best we can do!
643 staff_to_voice_dict = {}
644 for (v,s) in voice_to_staff_dict.items ():
645 if not staff_to_voice_dict.has_key (s):
646 staff_to_voice_dict[s] = [v]
648 staff_to_voice_dict[s].append (v)
652 assign_to_next_note = []
655 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
657 if not (voice_id or isinstance (n, Attributes) or
658 isinstance (n, Direction) or isinstance (n, Partial) or
659 isinstance (n, Barline) or isinstance (n, Harmony) ):
662 if isinstance (n, Attributes) and not start_attr:
666 if isinstance (n, Attributes):
667 # assign these only to the voices they really belongs to!
668 for (s, vids) in staff_to_voice_dict.items ():
669 staff_attributes = part.extract_attributes_for_staff (n, s)
671 voices[v].add_element (staff_attributes)
674 if isinstance (n, Partial) or isinstance (n, Barline):
675 for v in voices.keys ():
676 voices[v].add_element (n)
679 if isinstance (n, Direction):
680 staff_id = n.get_maybe_exist_named_child (u'staff')
682 staff_id = staff_id.get_text ()
684 dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
686 dir_voices = voices.keys ()
688 voices[v].add_element (n)
691 if isinstance (n, Harmony):
692 # store the harmony element until we encounter the next note
693 # and assign it only to that one voice.
694 assign_to_next_note.append (n)
697 id = voice_id.get_text ()
698 if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
702 for i in assign_to_next_note:
703 voices[id].add_element (i)
704 assign_to_next_note = []
705 voices[id].add_element (n)
707 # Assign all remaining elements from assign_to_next_note to the voice
708 # of the previous note:
709 for i in assign_to_next_note:
710 voices[id].add_element (i)
711 assign_to_next_note = []
714 for (s, vids) in staff_to_voice_dict.items ():
715 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
716 staff_attributes.read_self ()
717 part._staff_attributes_dict[s] = staff_attributes
719 voices[v].insert (0, staff_attributes)
720 voices[v]._elements[0].read_self()
722 part._voices = voices
724 def get_voices (self):
726 def get_staff_attributes (self):
727 return self._staff_attributes_dict
729 class Notations (Music_xml_node):
731 ts = self.get_named_children ('tied')
732 starts = [t for t in ts if t.type == 'start']
738 def get_tuplets (self):
739 return self.get_typed_children (Tuplet)
741 class Time_modification(Music_xml_node):
742 def get_fraction (self):
743 b = self.get_maybe_exist_named_child ('actual-notes')
744 a = self.get_maybe_exist_named_child ('normal-notes')
745 return (int(a.get_text ()), int (b.get_text ()))
747 class Accidental (Music_xml_node):
749 Music_xml_node.__init__ (self)
750 self.editorial = False
751 self.cautionary = False
753 class Music_xml_spanner (Music_xml_node):
755 if hasattr (self, 'type'):
760 if hasattr (self, 'size'):
761 return string.atoi (self.size)
765 class Wedge (Music_xml_spanner):
768 class Tuplet (Music_xml_spanner):
771 class Bracket (Music_xml_spanner):
774 class Dashes (Music_xml_spanner):
777 class Slur (Music_xml_spanner):
781 class Beam (Music_xml_spanner):
783 return self.get_text ()
784 def is_primary (self):
785 return self.number == "1"
787 class Wavy_line (Music_xml_spanner):
790 class Pedal (Music_xml_spanner):
793 class Glissando (Music_xml_spanner):
796 class Slide (Music_xml_spanner):
799 class Octave_shift (Music_xml_spanner):
800 # default is 8 for the octave-shift!
802 if hasattr (self, 'size'):
803 return string.atoi (self.size)
807 class Chord (Music_xml_node):
810 class Dot (Music_xml_node):
813 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
814 # for the inner <rest> element, not the whole rest block.
815 class Rest (Music_xml_node):
817 Music_xml_node.__init__ (self)
818 self._is_whole_measure = False
819 def is_whole_measure (self):
820 return self._is_whole_measure
822 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
824 step = ch.get_text ().strip ()
828 def get_octave (self):
829 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
831 step = ch.get_text ().strip ()
836 class Type (Music_xml_node):
838 class Grace (Music_xml_node):
840 class Staff (Music_xml_node):
843 class Direction (Music_xml_node):
845 class DirType (Music_xml_node):
848 class Bend (Music_xml_node):
849 def bend_alter (self):
850 alter = self.get_maybe_exist_named_child ('bend-alter')
852 return alter.get_text()
856 class Words (Music_xml_node):
859 class Harmony (Music_xml_node):
862 class Frame (Music_xml_node):
863 def get_frets (self):
864 return self.get_named_child_value_number ('frame-frets', 4)
865 def get_strings (self):
866 return self.get_named_child_value_number ('frame-strings', 6)
867 def get_first_fret (self):
868 return self.get_named_child_value_number ('first-fret', 1)
869 class Frame_Note (Music_xml_node):
870 def get_string (self):
871 return self.get_named_child_value_number ('string', 1)
873 return self.get_named_child_value_number ('fret', 0)
874 def get_fingering (self):
875 return self.get_named_child_value_number ('fingering', -1)
876 def get_barre (self):
877 n = self.get_maybe_exist_named_child ('barre')
879 return getattr (n, 'type', '')
884 ## need this, not all classes are instantiated
885 ## for every input file. Only add those classes, that are either directly
886 ## used by class name or extend Music_xml_node in some way!
888 '#comment': Hash_comment,
890 'accidental': Accidental,
891 'attributes': Attributes,
893 'bar-style': BarStyle,
900 'direction': Direction,
901 'direction-type': DirType,
902 'duration': Duration,
904 'frame-note': Frame_Note,
905 'glissando': Glissando,
908 'identification': Identification,
911 'notations': Notations,
913 'octave-shift': Octave_shift,
915 'part-group': Part_group,
916 'part-list': Part_list,
920 'score-part': Score_part,
924 'syllabic': Syllabic,
926 'time-modification': Time_modification,
929 'unpitched': Unpitched,
930 'wavy-line': Wavy_line,
936 def name2class_name (name):
937 name = name.replace ('-', '_')
938 name = name.replace ('#', 'hash_')
939 name = name[0].upper() + name[1:].lower()
943 def get_class (name):
944 classname = class_dict.get (name)
948 class_name = name2class_name (name)
949 klass = new.classobj (class_name, (Music_xml_node,) , {})
950 class_dict[name] = klass
953 def lxml_demarshal_node (node):
958 klass = get_class (name)
961 py_node._original = node
963 py_node._data = node.text
964 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
965 py_node._children = filter (lambda x: x, py_node._children)
967 for c in py_node._children:
970 for (k,v) in node.items ():
971 py_node.__dict__[k] = v
972 py_node._attribute_dict[k] = v
976 def minidom_demarshal_node (node):
979 klass = get_class (name)
982 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
983 for c in py_node._children:
987 for (nm, value) in node.attributes.items():
988 py_node.__dict__[nm] = value
989 py_node._attribute_dict[nm] = value
992 if node.nodeType == node.TEXT_NODE and node.data:
993 py_node._data = node.data
995 py_node._original = node
999 if __name__ == '__main__':
1002 tree = lxml.etree.parse ('beethoven.xml')
1003 mxl_tree = lxml_demarshal_node (tree.getroot ())
1004 ks = class_dict.keys()
1006 print '\n'.join (ks)