9 self._name = 'xml_node'
11 self._attribute_dict = {}
13 def get_parent (self):
17 return self._parent.get_typed_children (self.__class__)[0] == self
28 if not self._children:
31 return ''.join ([c.get_text () for c in self._children])
33 def message (self, msg):
38 print ' In: <%s %s>' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()]))
41 def get_typed_children (self, klass):
45 return [c for c in self._children if isinstance(c, klass)]
47 def get_named_children (self, nm):
48 return self.get_typed_children (class_dict.get (nm))
50 def get_named_child (self, nm):
51 return self.get_maybe_exist_named_child (nm)
53 def get_children (self, predicate):
54 return [c for c in self._children if predicate(c)]
56 def get_all_children (self):
59 def get_maybe_exist_named_child (self, name):
60 return self.get_maybe_exist_typed_child (class_dict.get (name))
62 def get_maybe_exist_typed_child (self, klass):
63 cn = self.get_typed_children (klass)
69 raise "More than 1 child", klass
71 def get_unique_typed_child (self, klass):
72 cn = self.get_typed_children(klass)
75 raise 'Child is not unique for', (klass, 'found', cn)
79 class Music_xml_node (Xml_node):
81 Xml_node.__init__ (self)
82 self.duration = Rational (0)
83 self.start = Rational (0)
85 class Work (Xml_node):
86 def get_work_information (self, tag):
87 wt = self.get_maybe_exist_named_child (tag)
93 def get_work_title (self):
94 return self.get_work_information ('work-title')
95 def get_work_number (self):
96 return self.get_work_information ('work-number')
98 return self.get_work_information ('opus')
100 class Identification (Xml_node):
101 def get_rights (self):
102 rights = self.get_maybe_exist_named_child ('rights')
104 return rights.get_text ()
108 def get_creator (self, type):
109 creators = self.get_named_children ('creator')
110 # return the first creator tag that has type 'editor'
112 if hasattr (i, 'type') and i.type == type:
117 def get_composer (self):
118 c = self.get_creator ('composer')
121 creators = self.get_named_children ('creator')
122 # return the first creator tag that has no type at all
124 if not hasattr (i, 'type'):
127 def get_arranger (self):
128 return self.get_creator ('arranger')
129 def get_editor (self):
130 return self.get_creator ('editor')
132 return self.get_creator ('poet')
134 def get_encoding_information (self, type):
135 enc = self.get_named_children ('encoding')
137 children = enc[0].get_named_children (type)
139 return children[0].get_text ()
143 def get_encoding_software (self):
144 return self.get_encoding_information ('software')
145 def get_encoding_date (self):
146 return self.get_encoding_information ('encoding-date')
147 def get_encoding_person (self):
148 return self.get_encoding_information ('encoder')
149 def get_encoding_description (self):
150 return self.get_encoding_information ('encoding-description')
154 class Duration (Music_xml_node):
155 def get_length (self):
156 dur = int (self.get_text ()) * Rational (1,4)
159 class Hash_comment (Music_xml_node):
162 class Pitch (Music_xml_node):
164 ch = self.get_unique_typed_child (class_dict.get (u'step'))
165 step = ch.get_text ().strip ()
167 def get_octave (self):
168 ch = self.get_unique_typed_child (class_dict.get (u'octave'))
170 step = ch.get_text ().strip ()
173 def get_alteration (self):
174 ch = self.get_maybe_exist_typed_child (class_dict.get (u'alter'))
177 alter = int (ch.get_text ().strip ())
180 class Measure_element (Music_xml_node):
181 def get_voice_id (self):
182 voice_id = self.get_maybe_exist_named_child ('voice')
184 return voice_id.get_text ()
189 cn = self._parent.get_typed_children (self.__class__)
190 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
193 class Attributes (Measure_element):
195 Measure_element.__init__ (self)
198 def set_attributes_from_previous (self, dict):
199 self._dict.update (dict)
201 def read_self (self):
202 for c in self.get_all_children ():
203 self._dict[c.get_name()] = c
205 def get_named_attribute (self, name):
206 return self._dict.get (name)
208 def get_measure_length (self):
209 (n,d) = self.get_time_signature ()
210 return Rational (n,d)
212 def get_time_signature (self):
213 "return time sig as a (beat, beat-type) tuple"
216 mxl = self.get_named_attribute ('time')
218 beats = mxl.get_maybe_exist_named_child ('beats')
219 type = mxl.get_maybe_exist_named_child ('beat-type')
220 return (int (beats.get_text ()),
221 int (type.get_text ()))
223 print 'error: requested time signature, but time sig unknown'
226 def get_clef_sign (self):
227 mxl = self.get_named_attribute ('clef')
228 sign = mxl.get_maybe_exist_named_child ('sign')
230 return sign.get_text ()
232 print 'clef requested, but unknow'
235 def get_key_signature (self):
236 "return (fifths, mode) tuple"
238 key = self.get_named_attribute ('key')
239 mode_node = key.get_maybe_exist_named_child ('mode')
242 mode = mode_node.get_text ()
244 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
245 return (fifths, mode)
248 class Note (Measure_element):
250 Measure_element.__init__ (self)
251 self.instrument_name = ''
253 def get_duration_log (self):
254 ch = self.get_maybe_exist_typed_child (class_dict.get (u'type'))
257 log = ch.get_text ().strip()
265 'whole': 0}.get (log)
269 def get_factor (self):
272 def get_pitches (self):
273 return self.get_typed_children (class_dict.get (u'pitch'))
275 class Part_list (Music_xml_node):
277 Music_xml_node.__init__ (self)
278 self._id_instrument_name_dict = {}
280 def generate_id_instrument_dict (self):
282 ## not empty to make sure this happens only once.
284 for score_part in self.get_named_children ('score-part'):
285 for instr in score_part.get_named_children ('score-instrument'):
287 name = instr.get_named_child ("instrument-name")
288 mapping[id] = name.get_text ()
290 self._id_instrument_name_dict = mapping
292 def get_instrument (self, id):
293 if not self._id_instrument_name_dict:
294 self.generate_id_instrument_dict()
296 instrument_name = self._id_instrument_name_dict.get (id)
298 return instrument_name
300 print "Opps, couldn't find instrument for ID=", id
303 class Measure(Music_xml_node):
304 def get_notes (self):
305 return self.get_typed_children (class_dict.get (u'note'))
308 class Musicxml_voice:
312 self._start_staff = None
314 def add_element (self, e):
315 self._elements.append (e)
316 if (isinstance (e, Note)
317 and e.get_maybe_exist_typed_child (Staff)):
318 name = e.get_maybe_exist_typed_child (Staff).get_text ()
320 if not self._start_staff:
321 self._start_staff = name
322 self._staves[name] = True
324 def insert (self, idx, e):
325 self._elements.insert (idx, e)
329 class Part (Music_xml_node):
331 Music_xml_node.__init__ (self)
334 def get_part_list (self):
336 while n and n.get_name() != 'score-partwise':
339 return n.get_named_child ('part-list')
341 def interpret (self):
342 """Set durations and starting points."""
344 part_list = self.get_part_list ()
347 factor = Rational (1)
349 attributes_object = None
350 measures = self.get_typed_children (Measure)
351 last_moment = Rational (-1)
352 last_measure_position = Rational (-1)
354 measure_start_moment = now
355 measure_position = Rational (0)
356 for n in m.get_all_children ():
359 if n.__class__ == Attributes:
360 n.set_attributes_from_previous (attributes_dict)
362 attributes_dict = n._dict.copy ()
363 attributes_object = n
365 factor = Rational (1,
366 int (attributes_dict.get ('divisions').get_text ()))
369 if (n.get_maybe_exist_typed_child (Duration)):
370 mxl_dur = n.get_maybe_exist_typed_child (Duration)
371 dur = mxl_dur.get_length () * factor
373 if n.get_name() == 'backup':
375 if n.get_maybe_exist_typed_child (Grace):
378 rest = n.get_maybe_exist_typed_child (Rest)
380 and attributes_object
381 and attributes_object.get_measure_length () == dur):
383 rest._is_whole_measure = True
385 if (dur > Rational (0)
386 and n.get_maybe_exist_typed_child (Chord)):
388 measure_position = last_measure_position
391 last_measure_position = measure_position
394 n._measure_position = measure_position
397 measure_position += dur
398 if n._name == 'note':
399 instrument = n.get_maybe_exist_named_child ('instrument')
401 n.instrument_name = part_list.get_instrument (instrument.id)
403 if attributes_object:
404 length = attributes_object.get_measure_length ()
405 new_now = measure_start_moment + length
408 problem = 'incomplete'
412 ## only for verbose operation.
413 if problem <> 'incomplete':
414 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
418 def extract_voices (part):
420 measures = part.get_typed_children (Measure)
423 elements.extend (m.get_all_children ())
427 voice_id = n.get_maybe_exist_typed_child (class_dict.get ('voice'))
429 # TODO: If the first element of a voice is a dynamics entry,
430 # then voice_id is not yet set! Thus it will currently be ignored
431 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
434 if isinstance (n, Attributes) and not start_attr:
438 if isinstance (n, Attributes) or isinstance (n, Direction):
439 for v in voices.values ():
443 id = voice_id.get_text ()
444 if not voices.has_key (id):
445 voices[id] = Musicxml_voice()
447 voices[id].add_element (n)
450 for (k,v) in voices.items ():
451 v.insert (0, start_attr)
453 part._voices = voices
455 def get_voices (self):
458 class Notations (Music_xml_node):
460 ts = self.get_named_children ('tied')
461 starts = [t for t in ts if t.type == 'start']
467 def get_tuplet (self):
468 return self.get_maybe_exist_typed_child (Tuplet)
470 class Time_modification(Music_xml_node):
471 def get_fraction (self):
472 b = self.get_maybe_exist_typed_child (class_dict.get ('actual-notes'))
473 a = self.get_maybe_exist_typed_child (class_dict.get ('normal-notes'))
474 return (int(a.get_text ()), int (b.get_text ()))
476 class Accidental (Music_xml_node):
478 Music_xml_node.__init__ (self)
479 self.editorial = False
480 self.cautionary = False
483 class Tuplet(Music_xml_node):
486 class Slur (Music_xml_node):
490 class Beam (Music_xml_node):
492 return self.get_text ()
493 def is_primary (self):
494 return self.number == "1"
496 class Chord (Music_xml_node):
499 class Dot (Music_xml_node):
502 class Alter (Music_xml_node):
505 class Rest (Music_xml_node):
507 Music_xml_node.__init__ (self)
508 self._is_whole_measure = False
509 def is_whole_measure (self):
510 return self._is_whole_measure
512 class Mode (Music_xml_node):
514 class Tied (Music_xml_node):
517 class Type (Music_xml_node):
519 class Grace (Music_xml_node):
521 class Staff (Music_xml_node):
524 class Instrument (Music_xml_node):
527 class Fermata (Music_xml_node):
529 class Dynamics (Music_xml_node):
531 class Articulations (Music_xml_node):
533 class Accent (Music_xml_node):
535 class Staccato (Music_xml_node):
537 class Tenuto (Music_xml_node):
539 class Tremolo (Music_xml_node):
541 class Technical (Music_xml_node):
543 class Ornaments (Music_xml_node):
547 class Direction (Music_xml_node):
549 class DirType (Music_xml_node):
551 class Wedge (Music_xml_node):
554 class Creator (Music_xml_node):
556 class Rights (Music_xml_node):
558 class Encoding (Music_xml_node):
560 class WorkTitle (Music_xml_node):
563 ## need this, not all classes are instantiated
564 ## for every input file.
566 '#comment': Hash_comment,
567 'accidental': Accidental,
569 'attributes': Attributes,
573 'duration': Duration,
575 'instrument': Instrument,
578 'notations': Notations,
585 'time-modification': Time_modification,
588 'part-list': Part_list,
591 'articulations': Articulations,
593 'staccato': Staccato,
596 'technical': Technical,
597 'ornaments': Ornaments,
598 'direction': Direction,
599 'direction-type': DirType,
600 'dynamics': Dynamics,
603 'identification': Identification,
606 'encoding': Encoding,
608 'work-title': WorkTitle
612 def name2class_name (name):
613 name = name.replace ('-', '_')
614 name = name.replace ('#', 'hash_')
615 name = name[0].upper() + name[1:].lower()
619 def get_class (name):
620 classname = class_dict.get (name)
624 class_name = name2class_name (name)
625 klass = new.classobj (class_name, (Music_xml_node,) , {})
626 class_dict[name] = klass
629 def lxml_demarshal_node (node):
634 klass = get_class (name)
637 py_node._original = node
639 py_node._data = node.text
640 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
641 py_node._children = filter (lambda x: x, py_node._children)
643 for c in py_node._children:
646 for (k,v) in node.items ():
647 py_node.__dict__[k] = v
648 py_node._attribute_dict[k] = v
652 def minidom_demarshal_node (node):
655 klass = get_class (name)
658 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
659 for c in py_node._children:
663 for (nm, value) in node.attributes.items():
664 py_node.__dict__[nm] = value
665 py_node._attribute_dict[nm] = value
668 if node.nodeType == node.TEXT_NODE and node.data:
669 py_node._data = node.data
671 py_node._original = node
675 if __name__ == '__main__':
678 tree = lxml.etree.parse ('beethoven.xml')
679 mxl_tree = lxml_demarshal_node (tree.getroot ())
680 ks = class_dict.keys()