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 sys.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')
184 class Duration (Music_xml_node):
185 def get_length (self):
186 dur = int (self.get_text ()) * Rational (1,4)
189 class Hash_comment (Music_xml_node):
191 class Hash_text (Music_xml_node):
194 class Pitch (Music_xml_node):
196 ch = self.get_unique_typed_child (get_class (u'step'))
197 step = ch.get_text ().strip ()
199 def get_octave (self):
200 ch = self.get_unique_typed_child (get_class (u'octave'))
202 step = ch.get_text ().strip ()
205 def get_alteration (self):
206 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
209 alter = int (ch.get_text ().strip ())
212 class Unpitched (Music_xml_node):
214 ch = self.get_unique_typed_child (get_class (u'display-step'))
215 step = ch.get_text ().strip ()
218 def get_octave (self):
219 ch = self.get_unique_typed_child (get_class (u'display-octave'))
222 octave = ch.get_text ().strip ()
227 class Measure_element (Music_xml_node):
228 def get_voice_id (self):
229 voice_id = self.get_maybe_exist_named_child ('voice')
231 return voice_id.get_text ()
236 cn = self._parent.get_typed_children (self.__class__)
237 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
240 class Attributes (Measure_element):
242 Measure_element.__init__ (self)
245 def set_attributes_from_previous (self, dict):
246 self._dict.update (dict)
248 def read_self (self):
249 for c in self.get_all_children ():
250 self._dict[c.get_name()] = c
252 def get_named_attribute (self, name):
253 return self._dict.get (name)
255 def get_measure_length (self):
256 (n,d) = self.get_time_signature ()
257 return Rational (n,d)
259 def get_time_signature (self):
260 "return time sig as a (beat, beat-type) tuple"
263 mxl = self.get_named_attribute ('time')
265 beats = mxl.get_maybe_exist_named_child ('beats')
266 type = mxl.get_maybe_exist_named_child ('beat-type')
267 return (int (beats.get_text ()),
268 int (type.get_text ()))
272 error (_ ("requested time signature, but time sig is unknown"))
275 # returns clef information in the form ("cleftype", position, octave-shift)
276 def get_clef_information (self):
277 clefinfo = ['G', 2, 0]
278 mxl = self.get_named_attribute ('clef')
281 sign = mxl.get_maybe_exist_named_child ('sign')
283 clefinfo[0] = sign.get_text()
284 line = mxl.get_maybe_exist_named_child ('line')
286 clefinfo[1] = string.atoi (line.get_text ())
287 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
289 clefinfo[2] = string.atoi (octave.get_text ())
292 def get_key_signature (self):
293 "return (fifths, mode) tuple"
295 key = self.get_named_attribute ('key')
296 mode_node = key.get_maybe_exist_named_child ('mode')
299 mode = mode_node.get_text ()
301 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
302 return (fifths, mode)
304 class Barline (Measure_element):
306 class BarStyle (Music_xml_node):
308 class Partial (Measure_element):
309 def __init__ (self, partial):
310 Measure_element.__init__ (self)
311 self.partial = partial
313 class Note (Measure_element):
315 Measure_element.__init__ (self)
316 self.instrument_name = ''
318 def get_duration_log (self):
319 ch = self.get_maybe_exist_named_child (u'type')
322 log = ch.get_text ().strip()
333 'long': -2}.get (log, 0)
334 elif self.get_maybe_exist_named_child (u'grace'):
335 # FIXME: is it ok to default to eight note for grace notes?
338 self.message (_ ("Encountered note at %s with %s duration (no <type> element):") % (self.start, self.duration) )
341 def get_factor (self):
344 def get_pitches (self):
345 return self.get_typed_children (get_class (u'pitch'))
347 class Part_list (Music_xml_node):
349 Music_xml_node.__init__ (self)
350 self._id_instrument_name_dict = {}
352 def generate_id_instrument_dict (self):
354 ## not empty to make sure this happens only once.
356 for score_part in self.get_named_children ('score-part'):
357 for instr in score_part.get_named_children ('score-instrument'):
359 name = instr.get_named_child ("instrument-name")
360 mapping[id] = name.get_text ()
362 self._id_instrument_name_dict = mapping
364 def get_instrument (self, id):
365 if not self._id_instrument_name_dict:
366 self.generate_id_instrument_dict()
368 instrument_name = self._id_instrument_name_dict.get (id)
370 return instrument_name
372 lilylib.stderr_write (_ ("Unable to find find instrument for ID=%s\n") % id)
375 class Part_group (Music_xml_node):
377 class Score_part (Music_xml_node):
380 class Measure (Music_xml_node):
382 Music_xml_node.__init__ (self)
384 def is_implicit (self):
385 return hasattr (self, 'implicit') and self.implicit == 'yes'
386 def get_notes (self):
387 return self.get_typed_children (get_class (u'note'))
389 class Syllabic (Music_xml_node):
390 def continued (self):
391 text = self.get_text()
392 return (text == "begin") or (text == "middle")
393 class Text (Music_xml_node):
396 class Lyric (Music_xml_node):
397 def get_number (self):
398 if hasattr (self, 'number'):
403 def lyric_to_text (self):
405 syllabic = self.get_maybe_exist_typed_child (Syllabic)
407 continued = syllabic.continued ()
408 text = self.get_maybe_exist_typed_child (Text)
411 text = text.get_text()
412 # We need to convert soft hyphens to -, otherwise the ascii codec as well
413 # as lilypond will barf on that character
414 text = string.replace( text, u'\xad', '-' )
416 if text == "-" and continued:
418 elif text == "_" and continued:
420 elif continued and text:
421 return escape_ly_output_string (text) + " --"
425 return escape_ly_output_string (text)
429 class Musicxml_voice:
433 self._start_staff = None
435 self._has_lyrics = False
437 def add_element (self, e):
438 self._elements.append (e)
439 if (isinstance (e, Note)
440 and e.get_maybe_exist_typed_child (Staff)):
441 name = e.get_maybe_exist_typed_child (Staff).get_text ()
443 if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
444 self._start_staff = name
445 self._staves[name] = True
447 lyrics = e.get_typed_children (Lyric)
448 if not self._has_lyrics:
449 self.has_lyrics = len (lyrics) > 0
453 if (nr > 0) and not (nr in self._lyrics):
454 self._lyrics.append (nr)
456 def insert (self, idx, e):
457 self._elements.insert (idx, e)
459 def get_lyrics_numbers (self):
460 if (len (self._lyrics) == 0) and self._has_lyrics:
461 #only happens if none of the <lyric> tags has a number attribute
467 class Part (Music_xml_node):
469 Music_xml_node.__init__ (self)
471 self._staff_attributes_dict = {}
473 def get_part_list (self):
475 while n and n.get_name() != 'score-partwise':
478 return n.get_named_child ('part-list')
480 def interpret (self):
481 """Set durations and starting points."""
482 """The starting point of the very first note is 0!"""
484 part_list = self.get_part_list ()
487 factor = Rational (1)
489 attributes_object = None
490 measures = self.get_typed_children (Measure)
491 last_moment = Rational (-1)
492 last_measure_position = Rational (-1)
493 measure_position = Rational (0)
494 measure_start_moment = now
495 is_first_measure = True
496 previous_measure = None
498 # implicit measures are used for artificial measures, e.g. when
499 # a repeat bar line splits a bar into two halves. In this case,
500 # don't reset the measure position to 0. They are also used for
501 # upbeats (initial value of 0 fits these, too).
502 # Also, don't reset the measure position at the end of the loop,
503 # but rather when starting the next measure (since only then do we
504 # know if the next measure is implicit and continues that measure)
505 if not m.is_implicit ():
506 # Warn about possibly overfull measures and reset the position
507 if attributes_object and previous_measure and previous_measure.partial == 0:
508 length = attributes_object.get_measure_length ()
509 new_now = measure_start_moment + length
511 problem = 'incomplete'
514 ## only for verbose operation.
515 if problem <> 'incomplete' and previous_measure:
516 previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
518 measure_start_moment = now
519 measure_position = Rational (0)
521 for n in m.get_all_children ():
522 if isinstance (n, Hash_text):
526 if n.__class__ == Attributes:
527 n.set_attributes_from_previous (attributes_dict)
529 attributes_dict = n._dict.copy ()
530 attributes_object = n
532 factor = Rational (1,
533 int (attributes_dict.get ('divisions').get_text ()))
536 if (n.get_maybe_exist_typed_child (Duration)):
537 mxl_dur = n.get_maybe_exist_typed_child (Duration)
538 dur = mxl_dur.get_length () * factor
540 if n.get_name() == 'backup':
542 if n.get_maybe_exist_typed_child (Grace):
545 rest = n.get_maybe_exist_typed_child (Rest)
547 and attributes_object
548 and attributes_object.get_measure_length () == dur):
550 rest._is_whole_measure = True
552 if (dur > Rational (0)
553 and n.get_maybe_exist_typed_child (Chord)):
555 measure_position = last_measure_position
558 n._measure_position = measure_position
560 if dur > Rational (0):
562 last_measure_position = measure_position
564 measure_position += dur
565 elif dur < Rational (0):
566 # backup element, reset measure position
568 measure_position += dur
569 if measure_position < 0:
570 # backup went beyond the measure start => reset to 0
571 now -= measure_position
574 last_measure_position = measure_position
575 if n._name == 'note':
576 instrument = n.get_maybe_exist_named_child ('instrument')
578 n.instrument_name = part_list.get_instrument (instrument.id)
580 # Incomplete first measures are not padded, but registered as partial
582 is_first_measure = False
583 # upbeats are marked as implicit measures
584 if attributes_object and m.is_implicit ():
585 length = attributes_object.get_measure_length ()
586 measure_end = measure_start_moment + length
587 if measure_end <> now:
591 # modify attributes so that only those applying to the given staff remain
592 def extract_attributes_for_staff (part, attr, staff):
593 attributes = copy.copy (attr)
594 attributes._children = copy.copy (attr._children)
595 attributes._dict = attr._dict.copy ()
596 for c in attributes._children:
597 if hasattr (c, 'number') and c.number != staff:
598 attributes._children.remove (c)
601 def extract_voices (part):
603 measures = part.get_typed_children (Measure)
607 elements.append (Partial (m.partial))
608 elements.extend (m.get_all_children ())
609 # make sure we know all voices already so that dynamics, clefs, etc.
610 # can be assigned to the correct voices
611 voice_to_staff_dict = {}
613 voice_id = n.get_maybe_exist_named_child (u'voice')
616 vid = voice_id.get_text ()
618 staff_id = n.get_maybe_exist_named_child (u'staff')
621 sid = staff_id.get_text ()
624 if vid and not voices.has_key (vid):
625 voices[vid] = Musicxml_voice()
626 if vid and sid and not n.get_maybe_exist_typed_child (Grace):
627 if not voice_to_staff_dict.has_key (vid):
628 voice_to_staff_dict[vid] = sid
629 # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
630 # need to assign staff-assigned objects like clefs, times, etc. to
631 # all the correct voices. This will never work entirely correct due
632 # to staff-switches, but that's the best we can do!
633 staff_to_voice_dict = {}
634 for (v,s) in voice_to_staff_dict.items ():
635 if not staff_to_voice_dict.has_key (s):
636 staff_to_voice_dict[s] = [v]
638 staff_to_voice_dict[s].append (v)
642 assign_to_next_note = []
645 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
647 if not (voice_id or isinstance (n, Attributes) or
648 isinstance (n, Direction) or isinstance (n, Partial) or
649 isinstance (n, Barline) or isinstance (n, Harmony) ):
652 if isinstance (n, Attributes) and not start_attr:
656 if isinstance (n, Attributes):
657 # assign these only to the voices they really belongs to!
658 for (s, vids) in staff_to_voice_dict.items ():
659 staff_attributes = part.extract_attributes_for_staff (n, s)
661 voices[v].add_element (staff_attributes)
664 if isinstance (n, Partial) or isinstance (n, Barline):
665 for v in voices.keys ():
666 voices[v].add_element (n)
669 if isinstance (n, Direction):
670 staff_id = n.get_maybe_exist_named_child (u'staff')
672 staff_id = staff_id.get_text ()
674 dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
676 dir_voices = voices.keys ()
678 voices[v].add_element (n)
681 if isinstance (n, Harmony):
682 # store the harmony element until we encounter the next note
683 # and assign it only to that one voice.
684 assign_to_next_note.append (n)
687 id = voice_id.get_text ()
688 if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
692 for i in assign_to_next_note:
693 voices[id].add_element (i)
694 assign_to_next_note = []
695 voices[id].add_element (n)
697 # Assign all remaining elements from assign_to_next_note to the voice
698 # of the previous note:
699 for i in assign_to_next_note:
700 voices[id].add_element (i)
701 assign_to_next_note = []
704 for (s, vids) in staff_to_voice_dict.items ():
705 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
706 staff_attributes.read_self ()
707 part._staff_attributes_dict[s] = staff_attributes
709 voices[v].insert (0, staff_attributes)
710 voices[v]._elements[0].read_self()
712 part._voices = voices
714 def get_voices (self):
716 def get_staff_attributes (self):
717 return self._staff_attributes_dict
719 class Notations (Music_xml_node):
721 ts = self.get_named_children ('tied')
722 starts = [t for t in ts if t.type == 'start']
728 def get_tuplets (self):
729 return self.get_typed_children (Tuplet)
731 class Time_modification(Music_xml_node):
732 def get_fraction (self):
733 b = self.get_maybe_exist_named_child ('actual-notes')
734 a = self.get_maybe_exist_named_child ('normal-notes')
735 return (int(a.get_text ()), int (b.get_text ()))
737 class Accidental (Music_xml_node):
739 Music_xml_node.__init__ (self)
740 self.editorial = False
741 self.cautionary = False
743 class Music_xml_spanner (Music_xml_node):
745 if hasattr (self, 'type'):
750 if hasattr (self, 'size'):
751 return string.atoi (self.size)
755 class Wedge (Music_xml_spanner):
758 class Tuplet (Music_xml_spanner):
761 class Bracket (Music_xml_spanner):
764 class Dashes (Music_xml_spanner):
767 class Slur (Music_xml_spanner):
771 class Beam (Music_xml_spanner):
773 return self.get_text ()
774 def is_primary (self):
775 return self.number == "1"
777 class Wavy_line (Music_xml_spanner):
780 class Pedal (Music_xml_spanner):
783 class Glissando (Music_xml_spanner):
786 class Slide (Music_xml_spanner):
789 class Octave_shift (Music_xml_spanner):
790 # default is 8 for the octave-shift!
792 if hasattr (self, 'size'):
793 return string.atoi (self.size)
797 class Chord (Music_xml_node):
800 class Dot (Music_xml_node):
803 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
804 # for the inner <rest> element, not the whole rest block.
805 class Rest (Music_xml_node):
807 Music_xml_node.__init__ (self)
808 self._is_whole_measure = False
809 def is_whole_measure (self):
810 return self._is_whole_measure
812 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
814 step = ch.get_text ().strip ()
818 def get_octave (self):
819 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
821 step = ch.get_text ().strip ()
826 class Type (Music_xml_node):
828 class Grace (Music_xml_node):
830 class Staff (Music_xml_node):
833 class Direction (Music_xml_node):
835 class DirType (Music_xml_node):
838 class Bend (Music_xml_node):
839 def bend_alter (self):
840 alter = self.get_maybe_exist_named_child ('bend-alter')
842 return alter.get_text()
846 class Words (Music_xml_node):
849 class Harmony (Music_xml_node):
852 class Frame (Music_xml_node):
853 def get_frets (self):
854 return self.get_named_child_value_number ('frame-frets', 4)
855 def get_strings (self):
856 return self.get_named_child_value_number ('frame-strings', 6)
857 def get_first_fret (self):
858 return self.get_named_child_value_number ('first-fret', 1)
859 class Frame_Note (Music_xml_node):
860 def get_string (self):
861 return self.get_named_child_value_number ('string', 1)
863 return self.get_named_child_value_number ('fret', 0)
864 def get_fingering (self):
865 return self.get_named_child_value_number ('fingering', -1)
866 def get_barre (self):
867 n = self.get_maybe_exist_named_child ('barre')
869 return getattr (n, 'type', '')
874 ## need this, not all classes are instantiated
875 ## for every input file. Only add those classes, that are either directly
876 ## used by class name or extend Music_xml_node in some way!
878 '#comment': Hash_comment,
880 'accidental': Accidental,
881 'attributes': Attributes,
883 'bar-style': BarStyle,
890 'direction': Direction,
891 'direction-type': DirType,
892 'duration': Duration,
894 'frame-note': Frame_Note,
895 'glissando': Glissando,
898 'identification': Identification,
901 'notations': Notations,
903 'octave-shift': Octave_shift,
905 'part-group': Part_group,
906 'part-list': Part_list,
910 'score-part': Score_part,
914 'syllabic': Syllabic,
916 'time-modification': Time_modification,
919 'unpitched': Unpitched,
920 'wavy-line': Wavy_line,
926 def name2class_name (name):
927 name = name.replace ('-', '_')
928 name = name.replace ('#', 'hash_')
929 name = name[0].upper() + name[1:].lower()
933 def get_class (name):
934 classname = class_dict.get (name)
938 class_name = name2class_name (name)
939 klass = new.classobj (class_name, (Music_xml_node,) , {})
940 class_dict[name] = klass
943 def lxml_demarshal_node (node):
948 klass = get_class (name)
951 py_node._original = node
953 py_node._data = node.text
954 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
955 py_node._children = filter (lambda x: x, py_node._children)
957 for c in py_node._children:
960 for (k,v) in node.items ():
961 py_node.__dict__[k] = v
962 py_node._attribute_dict[k] = v
966 def minidom_demarshal_node (node):
969 klass = get_class (name)
972 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
973 for c in py_node._children:
977 for (nm, value) in node.attributes.items():
978 py_node.__dict__[nm] = value
979 py_node._attribute_dict[nm] = value
982 if node.nodeType == node.TEXT_NODE and node.data:
983 py_node._data = node.data
985 py_node._original = node
989 if __name__ == '__main__':
992 tree = lxml.etree.parse ('beethoven.xml')
993 mxl_tree = lxml_demarshal_node (tree.getroot ())
994 ks = class_dict.keys()