7 def escape_ly_output_string (input_string):
8 return_string = input_string
9 needs_quotes = not re.match (u"^[a-zA-ZäöüÜÄÖßñ]*$", return_string);
11 return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
20 self._name = 'xml_node'
22 self._attribute_dict = {}
24 def get_parent (self):
28 return self._parent.get_typed_children (self.__class__)[0] == self
39 if not self._children:
42 return ''.join ([c.get_text () for c in self._children])
44 def message (self, msg):
45 sys.stderr.write (msg+'\n')
49 sys.stderr.write (' In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()])))
52 def get_typed_children (self, klass):
56 return [c for c in self._children if isinstance(c, klass)]
58 def get_named_children (self, nm):
59 return self.get_typed_children (get_class (nm))
61 def get_named_child (self, nm):
62 return self.get_maybe_exist_named_child (nm)
64 def get_children (self, predicate):
65 return [c for c in self._children if predicate(c)]
67 def get_all_children (self):
70 def get_maybe_exist_named_child (self, name):
71 return self.get_maybe_exist_typed_child (get_class (name))
73 def get_maybe_exist_typed_child (self, klass):
74 cn = self.get_typed_children (klass)
80 raise "More than 1 child", klass
82 def get_unique_typed_child (self, klass):
83 cn = self.get_typed_children(klass)
85 sys.stderr.write (self.__dict__ + '\n')
86 raise 'Child is not unique for', (klass, 'found', cn)
90 class Music_xml_node (Xml_node):
92 Xml_node.__init__ (self)
93 self.duration = Rational (0)
94 self.start = Rational (0)
96 class Work (Xml_node):
97 def get_work_information (self, tag):
98 wt = self.get_maybe_exist_named_child (tag)
100 return wt.get_text ()
104 def get_work_title (self):
105 return self.get_work_information ('work-title')
106 def get_work_number (self):
107 return self.get_work_information ('work-number')
109 return self.get_work_information ('opus')
111 class Identification (Xml_node):
112 def get_rights (self):
113 rights = self.get_maybe_exist_named_child ('rights')
115 return rights.get_text ()
119 def get_creator (self, type):
120 creators = self.get_named_children ('creator')
121 # return the first creator tag that has the particular type
123 if hasattr (i, 'type') and i.type == type:
127 def get_composer (self):
128 c = self.get_creator ('composer')
131 creators = self.get_named_children ('creator')
132 # return the first creator tag that has no type at all
134 if not hasattr (i, 'type'):
137 def get_arranger (self):
138 return self.get_creator ('arranger')
139 def get_editor (self):
140 return self.get_creator ('editor')
142 v = self.get_creator ('lyricist')
145 v = self.get_creator ('poet')
148 def get_encoding_information (self, type):
149 enc = self.get_named_children ('encoding')
151 children = enc[0].get_named_children (type)
153 return children[0].get_text ()
157 def get_encoding_software (self):
158 return self.get_encoding_information ('software')
159 def get_encoding_date (self):
160 return self.get_encoding_information ('encoding-date')
161 def get_encoding_person (self):
162 return self.get_encoding_information ('encoder')
163 def get_encoding_description (self):
164 return self.get_encoding_information ('encoding-description')
167 class Duration (Music_xml_node):
168 def get_length (self):
169 dur = int (self.get_text ()) * Rational (1,4)
172 class Hash_comment (Music_xml_node):
174 class Hash_text (Music_xml_node):
177 class Pitch (Music_xml_node):
179 ch = self.get_unique_typed_child (get_class (u'step'))
180 step = ch.get_text ().strip ()
182 def get_octave (self):
183 ch = self.get_unique_typed_child (get_class (u'octave'))
185 step = ch.get_text ().strip ()
188 def get_alteration (self):
189 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
192 alter = int (ch.get_text ().strip ())
195 class Measure_element (Music_xml_node):
196 def get_voice_id (self):
197 voice_id = self.get_maybe_exist_named_child ('voice')
199 return voice_id.get_text ()
204 cn = self._parent.get_typed_children (self.__class__)
205 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
208 class Attributes (Measure_element):
210 Measure_element.__init__ (self)
213 def set_attributes_from_previous (self, dict):
214 self._dict.update (dict)
216 def read_self (self):
217 for c in self.get_all_children ():
218 self._dict[c.get_name()] = c
220 def get_named_attribute (self, name):
221 return self._dict.get (name)
223 def get_measure_length (self):
224 (n,d) = self.get_time_signature ()
225 return Rational (n,d)
227 def get_time_signature (self):
228 "return time sig as a (beat, beat-type) tuple"
231 mxl = self.get_named_attribute ('time')
233 beats = mxl.get_maybe_exist_named_child ('beats')
234 type = mxl.get_maybe_exist_named_child ('beat-type')
235 return (int (beats.get_text ()),
236 int (type.get_text ()))
240 sys.stderr.write ('error: requested time signature, but time sig unknown\n')
243 # returns clef information in the form ("cleftype", position, octave-shift)
244 def get_clef_information (self):
245 clefinfo = ['G', 2, 0]
246 mxl = self.get_named_attribute ('clef')
249 sign = mxl.get_maybe_exist_named_child ('sign')
251 clefinfo[0] = sign.get_text()
252 line = mxl.get_maybe_exist_named_child ('line')
254 clefinfo[1] = string.atoi (line.get_text ())
255 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
257 clefinfo[2] = string.atoi (octave.get_text ())
260 def get_key_signature (self):
261 "return (fifths, mode) tuple"
263 key = self.get_named_attribute ('key')
264 mode_node = key.get_maybe_exist_named_child ('mode')
267 mode = mode_node.get_text ()
269 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
270 return (fifths, mode)
273 class Note (Measure_element):
275 Measure_element.__init__ (self)
276 self.instrument_name = ''
278 def get_duration_log (self):
279 ch = self.get_maybe_exist_typed_child (get_class (u'type'))
282 log = ch.get_text ().strip()
293 'long': -2}.get (log, 0)
295 sys.stderr.write ("Encountered note without duration (no <type> element): %s\n" % self)
298 def get_factor (self):
301 def get_pitches (self):
302 return self.get_typed_children (get_class (u'pitch'))
304 class Part_list (Music_xml_node):
306 Music_xml_node.__init__ (self)
307 self._id_instrument_name_dict = {}
309 def generate_id_instrument_dict (self):
311 ## not empty to make sure this happens only once.
313 for score_part in self.get_named_children ('score-part'):
314 for instr in score_part.get_named_children ('score-instrument'):
316 name = instr.get_named_child ("instrument-name")
317 mapping[id] = name.get_text ()
319 self._id_instrument_name_dict = mapping
321 def get_instrument (self, id):
322 if not self._id_instrument_name_dict:
323 self.generate_id_instrument_dict()
325 instrument_name = self._id_instrument_name_dict.get (id)
327 return instrument_name
329 sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
332 class Measure (Music_xml_node):
333 def get_notes (self):
334 return self.get_typed_children (get_class (u'note'))
336 class Syllabic (Music_xml_node):
337 def continued (self):
338 text = self.get_text()
339 return (text == "begin") or (text == "middle")
340 class Text (Music_xml_node):
343 class Lyric (Music_xml_node):
344 def get_number (self):
345 if hasattr (self, 'number'):
350 def lyric_to_text (self):
352 syllabic = self.get_maybe_exist_typed_child (Syllabic)
354 continued = syllabic.continued ()
355 text = self.get_maybe_exist_typed_child (Text)
358 text = text.get_text()
359 # We need to convert soft hyphens to -, otherwise the ascii codec as well
360 # as lilypond will barf on that character
361 text = string.replace( text, u'\xad', '-' )
363 if text == "-" and continued:
365 elif text == "_" and continued:
367 elif continued and text:
368 return escape_ly_output_string (text) + " --"
372 return escape_ly_output_string (text)
376 class Musicxml_voice:
380 self._start_staff = None
382 self._has_lyrics = False
384 def add_element (self, e):
385 self._elements.append (e)
386 if (isinstance (e, Note)
387 and e.get_maybe_exist_typed_child (Staff)):
388 name = e.get_maybe_exist_typed_child (Staff).get_text ()
390 if not self._start_staff:
391 self._start_staff = name
392 self._staves[name] = True
394 lyrics = e.get_typed_children (Lyric)
395 if not self._has_lyrics:
396 self.has_lyrics = len (lyrics) > 0
400 if (nr > 0) and not (nr in self._lyrics):
401 self._lyrics.append (nr)
403 def insert (self, idx, e):
404 self._elements.insert (idx, e)
406 def get_lyrics_numbers (self):
407 if (len (self._lyrics) == 0) and self._has_lyrics:
408 #only happens if none of the <lyric> tags has a number attribute
415 class Part (Music_xml_node):
417 Music_xml_node.__init__ (self)
420 def get_part_list (self):
422 while n and n.get_name() != 'score-partwise':
425 return n.get_named_child ('part-list')
427 def interpret (self):
428 """Set durations and starting points."""
430 part_list = self.get_part_list ()
433 factor = Rational (1)
435 attributes_object = None
436 measures = self.get_typed_children (Measure)
437 last_moment = Rational (-1)
438 last_measure_position = Rational (-1)
440 measure_start_moment = now
441 measure_position = Rational (0)
442 for n in m.get_all_children ():
443 if isinstance (n, Hash_text):
447 if n.__class__ == Attributes:
448 n.set_attributes_from_previous (attributes_dict)
450 attributes_dict = n._dict.copy ()
451 attributes_object = n
453 factor = Rational (1,
454 int (attributes_dict.get ('divisions').get_text ()))
457 if (n.get_maybe_exist_typed_child (Duration)):
458 mxl_dur = n.get_maybe_exist_typed_child (Duration)
459 dur = mxl_dur.get_length () * factor
461 if n.get_name() == 'backup':
463 if n.get_maybe_exist_typed_child (Grace):
466 rest = n.get_maybe_exist_typed_child (Rest)
468 and attributes_object
469 and attributes_object.get_measure_length () == dur):
471 rest._is_whole_measure = True
473 if (dur > Rational (0)
474 and n.get_maybe_exist_typed_child (Chord)):
476 measure_position = last_measure_position
479 n._measure_position = measure_position
481 if dur > Rational (0):
483 last_measure_position = measure_position
485 measure_position += dur
486 elif dur < Rational (0):
487 # backup element, reset measure position
489 measure_position += dur
490 if measure_position < 0:
491 # backup went beyond the measure start => reset to 0
492 now -= measure_position
495 last_measure_position = measure_position
496 if n._name == 'note':
497 instrument = n.get_maybe_exist_named_child ('instrument')
499 n.instrument_name = part_list.get_instrument (instrument.id)
501 if attributes_object:
502 length = attributes_object.get_measure_length ()
503 new_now = measure_start_moment + length
506 problem = 'incomplete'
510 ## only for verbose operation.
511 if problem <> 'incomplete':
512 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
516 def extract_voices (part):
518 measures = part.get_typed_children (Measure)
521 elements.extend (m.get_all_children ())
525 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
527 # TODO: If the first element of a voice is a dynamics entry,
528 # then voice_id is not yet set! Thus it will currently be ignored
529 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
532 if isinstance (n, Attributes) and not start_attr:
536 if isinstance (n, Attributes) or isinstance (n, Direction):
537 for v in voices.values ():
541 id = voice_id.get_text ()
542 if not voices.has_key (id):
543 voices[id] = Musicxml_voice()
545 voices[id].add_element (n)
548 for (k,v) in voices.items ():
549 v.insert (0, start_attr)
551 part._voices = voices
553 def get_voices (self):
556 class Notations (Music_xml_node):
558 ts = self.get_named_children ('tied')
559 starts = [t for t in ts if t.type == 'start']
565 def get_tuplet (self):
566 return self.get_maybe_exist_typed_child (Tuplet)
568 class Time_modification(Music_xml_node):
569 def get_fraction (self):
570 b = self.get_maybe_exist_named_child ('actual-notes')
571 a = self.get_maybe_exist_named_child ('normal-notes')
572 return (int(a.get_text ()), int (b.get_text ()))
574 class Accidental (Music_xml_node):
576 Music_xml_node.__init__ (self)
577 self.editorial = False
578 self.cautionary = False
580 class Music_xml_spanner (Music_xml_node):
582 if hasattr (self, 'type'):
587 if hasattr (self, 'size'):
588 return string.atoi (self.size)
592 class Wedge (Music_xml_spanner):
595 class Tuplet (Music_xml_spanner):
598 class Slur (Music_xml_spanner):
602 class Beam (Music_xml_spanner):
604 return self.get_text ()
605 def is_primary (self):
606 return self.number == "1"
608 class Wavy_line (Music_xml_spanner):
611 class Pedal (Music_xml_spanner):
614 class Glissando (Music_xml_spanner):
617 class Octave_shift (Music_xml_spanner):
618 # default is 8 for the octave-shift!
620 if hasattr (self, 'size'):
621 return string.atoi (self.size)
625 class Chord (Music_xml_node):
628 class Dot (Music_xml_node):
631 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
632 # for the inner <rest> element, not the whole rest block.
633 class Rest (Music_xml_node):
635 Music_xml_node.__init__ (self)
636 self._is_whole_measure = False
637 def is_whole_measure (self):
638 return self._is_whole_measure
640 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
642 step = ch.get_text ().strip ()
646 def get_octave (self):
647 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
649 step = ch.get_text ().strip ()
654 class Type (Music_xml_node):
656 class Grace (Music_xml_node):
658 class Staff (Music_xml_node):
661 class Direction (Music_xml_node):
663 class DirType (Music_xml_node):
666 class Bend (Music_xml_node):
667 def bend_alter (self):
668 alter = self.get_maybe_exist_named_child ('bend-alter')
670 return alter.get_text()
676 ## need this, not all classes are instantiated
677 ## for every input file. Only add those classes, that are either directly
678 ## used by class name or extend Music_xml_node in some way!
680 '#comment': Hash_comment,
682 'accidental': Accidental,
683 'attributes': Attributes,
688 'direction': Direction,
689 'direction-type': DirType,
690 'duration': Duration,
691 'glissando': Glissando,
693 'identification': Identification,
696 'notations': Notations,
698 'octave-shift': Octave_shift,
700 'part-list': Part_list,
706 'syllabic': Syllabic,
708 'time-modification': Time_modification,
711 'wavy-line': Wavy_line,
716 def name2class_name (name):
717 name = name.replace ('-', '_')
718 name = name.replace ('#', 'hash_')
719 name = name[0].upper() + name[1:].lower()
723 def get_class (name):
724 classname = class_dict.get (name)
728 class_name = name2class_name (name)
729 klass = new.classobj (class_name, (Music_xml_node,) , {})
730 class_dict[name] = klass
733 def lxml_demarshal_node (node):
738 klass = get_class (name)
741 py_node._original = node
743 py_node._data = node.text
744 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
745 py_node._children = filter (lambda x: x, py_node._children)
747 for c in py_node._children:
750 for (k,v) in node.items ():
751 py_node.__dict__[k] = v
752 py_node._attribute_dict[k] = v
756 def minidom_demarshal_node (node):
759 klass = get_class (name)
762 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
763 for c in py_node._children:
767 for (nm, value) in node.attributes.items():
768 py_node.__dict__[nm] = value
769 py_node._attribute_dict[nm] = value
772 if node.nodeType == node.TEXT_NODE and node.data:
773 py_node._data = node.data
775 py_node._original = node
779 if __name__ == '__main__':
782 tree = lxml.etree.parse ('beethoven.xml')
783 mxl_tree = lxml_demarshal_node (tree.getroot ())
784 ks = class_dict.keys()