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 Measure_element (Music_xml_node):
206 def get_voice_id (self):
207 voice_id = self.get_maybe_exist_named_child ('voice')
209 return voice_id.get_text ()
214 cn = self._parent.get_typed_children (self.__class__)
215 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
218 class Attributes (Measure_element):
220 Measure_element.__init__ (self)
223 def set_attributes_from_previous (self, dict):
224 self._dict.update (dict)
226 def read_self (self):
227 for c in self.get_all_children ():
228 self._dict[c.get_name()] = c
230 def get_named_attribute (self, name):
231 return self._dict.get (name)
233 def get_measure_length (self):
234 (n,d) = self.get_time_signature ()
235 return Rational (n,d)
237 def get_time_signature (self):
238 "return time sig as a (beat, beat-type) tuple"
241 mxl = self.get_named_attribute ('time')
243 beats = mxl.get_maybe_exist_named_child ('beats')
244 type = mxl.get_maybe_exist_named_child ('beat-type')
245 return (int (beats.get_text ()),
246 int (type.get_text ()))
250 sys.stderr.write ('error: requested time signature, but time sig unknown\n')
253 # returns clef information in the form ("cleftype", position, octave-shift)
254 def get_clef_information (self):
255 clefinfo = ['G', 2, 0]
256 mxl = self.get_named_attribute ('clef')
259 sign = mxl.get_maybe_exist_named_child ('sign')
261 clefinfo[0] = sign.get_text()
262 line = mxl.get_maybe_exist_named_child ('line')
264 clefinfo[1] = string.atoi (line.get_text ())
265 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
267 clefinfo[2] = string.atoi (octave.get_text ())
270 def get_key_signature (self):
271 "return (fifths, mode) tuple"
273 key = self.get_named_attribute ('key')
274 mode_node = key.get_maybe_exist_named_child ('mode')
277 mode = mode_node.get_text ()
279 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
280 return (fifths, mode)
282 class Barline (Measure_element):
284 class BarStyle (Music_xml_node):
286 class Partial (Measure_element):
287 def __init__ (self, partial):
288 Measure_element.__init__ (self)
289 self.partial = partial
291 class Note (Measure_element):
293 Measure_element.__init__ (self)
294 self.instrument_name = ''
296 def get_duration_log (self):
297 ch = self.get_maybe_exist_named_child (u'type')
300 log = ch.get_text ().strip()
311 'long': -2}.get (log, 0)
313 self.message ("Encountered note at %s without %s duration (no <type> element):" % (self.start, self.duration) )
316 def get_factor (self):
319 def get_pitches (self):
320 return self.get_typed_children (get_class (u'pitch'))
322 class Part_list (Music_xml_node):
324 Music_xml_node.__init__ (self)
325 self._id_instrument_name_dict = {}
327 def generate_id_instrument_dict (self):
329 ## not empty to make sure this happens only once.
331 for score_part in self.get_named_children ('score-part'):
332 for instr in score_part.get_named_children ('score-instrument'):
334 name = instr.get_named_child ("instrument-name")
335 mapping[id] = name.get_text ()
337 self._id_instrument_name_dict = mapping
339 def get_instrument (self, id):
340 if not self._id_instrument_name_dict:
341 self.generate_id_instrument_dict()
343 instrument_name = self._id_instrument_name_dict.get (id)
345 return instrument_name
347 sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
350 class Part_group (Music_xml_node):
352 class Score_part (Music_xml_node):
355 class Measure (Music_xml_node):
357 Music_xml_node.__init__ (self)
359 def is_implicit (self):
360 return hasattr (self, 'implicit') and self.implicit == 'yes'
361 def get_notes (self):
362 return self.get_typed_children (get_class (u'note'))
364 class Syllabic (Music_xml_node):
365 def continued (self):
366 text = self.get_text()
367 return (text == "begin") or (text == "middle")
368 class Text (Music_xml_node):
371 class Lyric (Music_xml_node):
372 def get_number (self):
373 if hasattr (self, 'number'):
378 def lyric_to_text (self):
380 syllabic = self.get_maybe_exist_typed_child (Syllabic)
382 continued = syllabic.continued ()
383 text = self.get_maybe_exist_typed_child (Text)
386 text = text.get_text()
387 # We need to convert soft hyphens to -, otherwise the ascii codec as well
388 # as lilypond will barf on that character
389 text = string.replace( text, u'\xad', '-' )
391 if text == "-" and continued:
393 elif text == "_" and continued:
395 elif continued and text:
396 return escape_ly_output_string (text) + " --"
400 return escape_ly_output_string (text)
404 class Musicxml_voice:
408 self._start_staff = None
410 self._has_lyrics = False
412 def add_element (self, e):
413 self._elements.append (e)
414 if (isinstance (e, Note)
415 and e.get_maybe_exist_typed_child (Staff)):
416 name = e.get_maybe_exist_typed_child (Staff).get_text ()
418 if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
419 self._start_staff = name
420 self._staves[name] = True
422 lyrics = e.get_typed_children (Lyric)
423 if not self._has_lyrics:
424 self.has_lyrics = len (lyrics) > 0
428 if (nr > 0) and not (nr in self._lyrics):
429 self._lyrics.append (nr)
431 def insert (self, idx, e):
432 self._elements.insert (idx, e)
434 def get_lyrics_numbers (self):
435 if (len (self._lyrics) == 0) and self._has_lyrics:
436 #only happens if none of the <lyric> tags has a number attribute
443 class Part (Music_xml_node):
445 Music_xml_node.__init__ (self)
448 def get_part_list (self):
450 while n and n.get_name() != 'score-partwise':
453 return n.get_named_child ('part-list')
455 def interpret (self):
456 """Set durations and starting points."""
458 part_list = self.get_part_list ()
461 factor = Rational (1)
463 attributes_object = None
464 measures = self.get_typed_children (Measure)
465 last_moment = Rational (-1)
466 last_measure_position = Rational (-1)
467 measure_position = Rational (0)
468 measure_start_moment = now
469 is_first_measure = True
470 prvious_measure = None
472 # implicit measures are used for artificial measures, e.g. when
473 # a repeat bar line splits a bar into two halves. In this case,
474 # don't reset the measure position to 0. They are also used for
475 # upbeats (initial value of 0 fits these, too).
476 # Also, don't reset the measure position at the end of the loop,
477 # but rather when starting the next measure (since only then do we
478 # know if the next measure is implicit and continues that measure)
479 if not m.is_implicit ():
480 # Warn about possibly overfull measures and reset the position
481 if attributes_object:
482 length = attributes_object.get_measure_length ()
483 new_now = measure_start_moment + length
485 problem = 'incomplete'
488 ## only for verbose operation.
489 if problem <> 'incomplete' and previous_measure:
490 previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
492 measure_start_moment = now
493 measure_position = Rational (0)
495 for n in m.get_all_children ():
496 if isinstance (n, Hash_text):
500 if n.__class__ == Attributes:
501 n.set_attributes_from_previous (attributes_dict)
503 attributes_dict = n._dict.copy ()
504 attributes_object = n
506 factor = Rational (1,
507 int (attributes_dict.get ('divisions').get_text ()))
510 if (n.get_maybe_exist_typed_child (Duration)):
511 mxl_dur = n.get_maybe_exist_typed_child (Duration)
512 dur = mxl_dur.get_length () * factor
514 if n.get_name() == 'backup':
516 if n.get_maybe_exist_typed_child (Grace):
519 rest = n.get_maybe_exist_typed_child (Rest)
521 and attributes_object
522 and attributes_object.get_measure_length () == dur):
524 rest._is_whole_measure = True
526 if (dur > Rational (0)
527 and n.get_maybe_exist_typed_child (Chord)):
529 measure_position = last_measure_position
532 n._measure_position = measure_position
534 if dur > Rational (0):
536 last_measure_position = measure_position
538 measure_position += dur
539 elif dur < Rational (0):
540 # backup element, reset measure position
542 measure_position += dur
543 if measure_position < 0:
544 # backup went beyond the measure start => reset to 0
545 now -= measure_position
548 last_measure_position = measure_position
549 if n._name == 'note':
550 instrument = n.get_maybe_exist_named_child ('instrument')
552 n.instrument_name = part_list.get_instrument (instrument.id)
554 # Incomplete first measures are not padded, but registered as partial
556 is_first_measure = False
557 # upbeats are marked as implicit measures
558 if attributes_object and m.is_implicit ():
559 length = attributes_object.get_measure_length ()
560 measure_end = measure_start_moment + length
561 if measure_end <> now:
565 # modify attributes so that only those applying to the given staff remain
566 def extract_attributes_for_staff (part, attr, staff):
567 attributes = copy.copy (attr)
568 attributes._children = copy.copy (attr._children)
569 attributes._dict = attr._dict.copy ()
570 for c in attributes._children:
571 if hasattr (c, 'number') and c.number != staff:
572 attributes._children.remove (c)
575 def extract_voices (part):
577 measures = part.get_typed_children (Measure)
581 elements.append (Partial (m.partial))
582 elements.extend (m.get_all_children ())
583 # make sure we know all voices already so that dynamics, clefs, etc.
584 # can be assigned to the correct voices
585 voice_to_staff_dict = {}
587 voice_id = n.get_maybe_exist_named_child (u'voice')
590 vid = voice_id.get_text ()
592 staff_id = n.get_maybe_exist_named_child (u'staff')
595 sid = staff_id.get_text ()
598 if vid and not voices.has_key (vid):
599 voices[vid] = Musicxml_voice()
600 if vid and sid and not n.get_maybe_exist_typed_child (Grace):
601 if not voice_to_staff_dict.has_key (vid):
602 voice_to_staff_dict[vid] = sid
603 # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
604 # need to assign staff-assigned objects like clefs, times, etc. to
605 # all the correct voices. This will never work entirely correct due
606 # to staff-switches, but that's the best we can do!
607 staff_to_voice_dict = {}
608 for (v,s) in voice_to_staff_dict.items ():
609 if not staff_to_voice_dict.has_key (s):
610 staff_to_voice_dict[s] = [v]
612 staff_to_voice_dict[s].append (v)
617 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
619 if not (voice_id or isinstance (n, Attributes) or
620 isinstance (n, Direction) or isinstance (n, Partial) or
621 isinstance (n, Barline) or isinstance (n, Harmony) ):
624 if isinstance (n, Attributes) and not start_attr:
628 if isinstance (n, Attributes):
629 # assign these only to the voices they really belongs to!
630 for (s, vids) in staff_to_voice_dict.items ():
631 staff_attributes = part.extract_attributes_for_staff (n, s)
633 voices[v].add_element (staff_attributes)
636 if isinstance (n, Partial) or isinstance (n, Barline):
637 for v in voices.keys ():
638 voices[v].add_element (n)
641 if isinstance (n, Direction) or isinstance (n, Harmony):
642 staff_id = n.get_maybe_exist_named_child (u'staff')
644 staff_id = staff_id.get_text ()
646 dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
648 dir_voices = voices.keys ()
649 # assign only to first voice, otherwise we'll have duplicates!
651 voices[dir_voices[0]].add_element (n)
652 #for v in dir_voices:
653 #voices[v].add_element (n)
656 id = voice_id.get_text ()
657 if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
661 voices[id].add_element (n)
664 for (s, vids) in staff_to_voice_dict.items ():
665 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
666 staff_attributes.read_self ()
668 voices[v].insert (0, staff_attributes)
669 voices[v]._elements[0].read_self()
671 part._voices = voices
673 def get_voices (self):
676 class Notations (Music_xml_node):
678 ts = self.get_named_children ('tied')
679 starts = [t for t in ts if t.type == 'start']
685 def get_tuplet (self):
686 return self.get_maybe_exist_typed_child (Tuplet)
688 class Time_modification(Music_xml_node):
689 def get_fraction (self):
690 b = self.get_maybe_exist_named_child ('actual-notes')
691 a = self.get_maybe_exist_named_child ('normal-notes')
692 return (int(a.get_text ()), int (b.get_text ()))
694 class Accidental (Music_xml_node):
696 Music_xml_node.__init__ (self)
697 self.editorial = False
698 self.cautionary = False
700 class Music_xml_spanner (Music_xml_node):
702 if hasattr (self, 'type'):
707 if hasattr (self, 'size'):
708 return string.atoi (self.size)
712 class Wedge (Music_xml_spanner):
715 class Tuplet (Music_xml_spanner):
718 class Slur (Music_xml_spanner):
722 class Beam (Music_xml_spanner):
724 return self.get_text ()
725 def is_primary (self):
726 return self.number == "1"
728 class Wavy_line (Music_xml_spanner):
731 class Pedal (Music_xml_spanner):
734 class Glissando (Music_xml_spanner):
737 class Octave_shift (Music_xml_spanner):
738 # default is 8 for the octave-shift!
740 if hasattr (self, 'size'):
741 return string.atoi (self.size)
745 class Chord (Music_xml_node):
748 class Dot (Music_xml_node):
751 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
752 # for the inner <rest> element, not the whole rest block.
753 class Rest (Music_xml_node):
755 Music_xml_node.__init__ (self)
756 self._is_whole_measure = False
757 def is_whole_measure (self):
758 return self._is_whole_measure
760 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
762 step = ch.get_text ().strip ()
766 def get_octave (self):
767 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
769 step = ch.get_text ().strip ()
774 class Type (Music_xml_node):
776 class Grace (Music_xml_node):
778 class Staff (Music_xml_node):
781 class Direction (Music_xml_node):
783 class DirType (Music_xml_node):
786 class Bend (Music_xml_node):
787 def bend_alter (self):
788 alter = self.get_maybe_exist_named_child ('bend-alter')
790 return alter.get_text()
794 class Words (Music_xml_node):
797 class Harmony (Music_xml_node):
800 class Frame (Music_xml_node):
801 def get_frets (self):
802 return self.get_named_child_value_number ('frame-frets', 4)
803 def get_strings (self):
804 return self.get_named_child_value_number ('frame-strings', 6)
805 def get_first_fret (self):
806 return self.get_named_child_value_number ('first-fret', 1)
807 class Frame_Note (Music_xml_node):
808 def get_string (self):
809 return self.get_named_child_value_number ('string', 1)
811 return self.get_named_child_value_number ('fret', 0)
812 def get_fingering (self):
813 return self.get_named_child_value_number ('fingering', -1)
814 def get_barre (self):
815 n = self.get_maybe_exist_named_child ('barre')
817 return getattr (n, 'type', '')
822 ## need this, not all classes are instantiated
823 ## for every input file. Only add those classes, that are either directly
824 ## used by class name or extend Music_xml_node in some way!
826 '#comment': Hash_comment,
828 'accidental': Accidental,
829 'attributes': Attributes,
831 'bar-style': BarStyle,
836 'direction': Direction,
837 'direction-type': DirType,
838 'duration': Duration,
840 'frame-note': Frame_Note,
841 'glissando': Glissando,
844 'identification': Identification,
847 'notations': Notations,
849 'octave-shift': Octave_shift,
851 'part-group': Part_group,
852 'part-list': Part_list,
856 'score-part': Score_part,
859 'syllabic': Syllabic,
861 'time-modification': Time_modification,
864 'wavy-line': Wavy_line,
870 def name2class_name (name):
871 name = name.replace ('-', '_')
872 name = name.replace ('#', 'hash_')
873 name = name[0].upper() + name[1:].lower()
877 def get_class (name):
878 classname = class_dict.get (name)
882 class_name = name2class_name (name)
883 klass = new.classobj (class_name, (Music_xml_node,) , {})
884 class_dict[name] = klass
887 def lxml_demarshal_node (node):
892 klass = get_class (name)
895 py_node._original = node
897 py_node._data = node.text
898 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
899 py_node._children = filter (lambda x: x, py_node._children)
901 for c in py_node._children:
904 for (k,v) in node.items ():
905 py_node.__dict__[k] = v
906 py_node._attribute_dict[k] = v
910 def minidom_demarshal_node (node):
913 klass = get_class (name)
916 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
917 for c in py_node._children:
921 for (nm, value) in node.attributes.items():
922 py_node.__dict__[nm] = value
923 py_node._attribute_dict[nm] = value
926 if node.nodeType == node.TEXT_NODE and node.data:
927 py_node._data = node.data
929 py_node._original = node
933 if __name__ == '__main__':
936 tree = lxml.etree.parse ('beethoven.xml')
937 mxl_tree = lxml_demarshal_node (tree.getroot ())
938 ks = class_dict.keys()