6 def escape_ly_output_string (input_string):
7 return_string = input_string
8 needs_quotes = not re.match ("^[a-zA-ZäöüÜÄÖßñ]*$", return_string);
10 return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
19 self._name = 'xml_node'
21 self._attribute_dict = {}
23 def get_parent (self):
27 return self._parent.get_typed_children (self.__class__)[0] == self
38 if not self._children:
41 return ''.join ([c.get_text () for c in self._children])
43 def message (self, msg):
48 print ' In: <%s %s>' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()]))
51 def get_typed_children (self, klass):
55 return [c for c in self._children if isinstance(c, klass)]
57 def get_named_children (self, nm):
58 return self.get_typed_children (get_class (nm))
60 def get_named_child (self, nm):
61 return self.get_maybe_exist_named_child (nm)
63 def get_children (self, predicate):
64 return [c for c in self._children if predicate(c)]
66 def get_all_children (self):
69 def get_maybe_exist_named_child (self, name):
70 return self.get_maybe_exist_typed_child (get_class (name))
72 def get_maybe_exist_typed_child (self, klass):
73 cn = self.get_typed_children (klass)
79 raise "More than 1 child", klass
81 def get_unique_typed_child (self, klass):
82 cn = self.get_typed_children(klass)
85 raise 'Child is not unique for', (klass, 'found', cn)
89 class Music_xml_node (Xml_node):
91 Xml_node.__init__ (self)
92 self.duration = Rational (0)
93 self.start = Rational (0)
95 class Work (Xml_node):
96 def get_work_information (self, tag):
97 wt = self.get_maybe_exist_named_child (tag)
103 def get_work_title (self):
104 return self.get_work_information ('work-title')
105 def get_work_number (self):
106 return self.get_work_information ('work-number')
108 return self.get_work_information ('opus')
110 class Identification (Xml_node):
111 def get_rights (self):
112 rights = self.get_maybe_exist_named_child ('rights')
114 return rights.get_text ()
118 def get_creator (self, type):
119 creators = self.get_named_children ('creator')
120 # return the first creator tag that has the particular type
122 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 return self.get_creator ('poet')
144 def get_encoding_information (self, type):
145 enc = self.get_named_children ('encoding')
147 children = enc[0].get_named_children (type)
149 return children[0].get_text ()
153 def get_encoding_software (self):
154 return self.get_encoding_information ('software')
155 def get_encoding_date (self):
156 return self.get_encoding_information ('encoding-date')
157 def get_encoding_person (self):
158 return self.get_encoding_information ('encoder')
159 def get_encoding_description (self):
160 return self.get_encoding_information ('encoding-description')
163 class Duration (Music_xml_node):
164 def get_length (self):
165 dur = int (self.get_text ()) * Rational (1,4)
168 class Hash_comment (Music_xml_node):
170 class Hash_text (Music_xml_node):
173 class Pitch (Music_xml_node):
175 ch = self.get_unique_typed_child (get_class (u'step'))
176 step = ch.get_text ().strip ()
178 def get_octave (self):
179 ch = self.get_unique_typed_child (get_class (u'octave'))
181 step = ch.get_text ().strip ()
184 def get_alteration (self):
185 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
188 alter = int (ch.get_text ().strip ())
191 class Measure_element (Music_xml_node):
192 def get_voice_id (self):
193 voice_id = self.get_maybe_exist_named_child ('voice')
195 return voice_id.get_text ()
200 cn = self._parent.get_typed_children (self.__class__)
201 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
204 class Attributes (Measure_element):
206 Measure_element.__init__ (self)
209 def set_attributes_from_previous (self, dict):
210 self._dict.update (dict)
212 def read_self (self):
213 for c in self.get_all_children ():
214 self._dict[c.get_name()] = c
216 def get_named_attribute (self, name):
217 return self._dict.get (name)
219 def get_measure_length (self):
220 (n,d) = self.get_time_signature ()
221 return Rational (n,d)
223 def get_time_signature (self):
224 "return time sig as a (beat, beat-type) tuple"
227 mxl = self.get_named_attribute ('time')
229 beats = mxl.get_maybe_exist_named_child ('beats')
230 type = mxl.get_maybe_exist_named_child ('beat-type')
231 return (int (beats.get_text ()),
232 int (type.get_text ()))
234 print 'error: requested time signature, but time sig unknown'
237 # returns clef information in the form ("cleftype", position, octave-shift)
238 def get_clef_information (self):
239 clefinfo = ['G', 2, 0]
240 mxl = self.get_named_attribute ('clef')
243 sign = mxl.get_maybe_exist_named_child ('sign')
245 clefinfo[0] = sign.get_text()
246 line = mxl.get_maybe_exist_named_child ('line')
248 clefinfo[1] = string.atoi (line.get_text ())
249 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
251 clefinfo[2] = string.atoi (octave.get_text ())
254 def get_key_signature (self):
255 "return (fifths, mode) tuple"
257 key = self.get_named_attribute ('key')
258 mode_node = key.get_maybe_exist_named_child ('mode')
261 mode = mode_node.get_text ()
263 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
264 return (fifths, mode)
267 class Note (Measure_element):
269 Measure_element.__init__ (self)
270 self.instrument_name = ''
272 def get_duration_log (self):
273 ch = self.get_maybe_exist_typed_child (get_class (u'type'))
276 log = ch.get_text ().strip()
287 'long': -2}.get (log, 0)
289 sys.stderr.write ("Encountered note without duration (no <type> element): %s\n" % self)
292 def get_factor (self):
295 def get_pitches (self):
296 return self.get_typed_children (get_class (u'pitch'))
298 class Part_list (Music_xml_node):
300 Music_xml_node.__init__ (self)
301 self._id_instrument_name_dict = {}
303 def generate_id_instrument_dict (self):
305 ## not empty to make sure this happens only once.
307 for score_part in self.get_named_children ('score-part'):
308 for instr in score_part.get_named_children ('score-instrument'):
310 name = instr.get_named_child ("instrument-name")
311 mapping[id] = name.get_text ()
313 self._id_instrument_name_dict = mapping
315 def get_instrument (self, id):
316 if not self._id_instrument_name_dict:
317 self.generate_id_instrument_dict()
319 instrument_name = self._id_instrument_name_dict.get (id)
321 return instrument_name
323 print "Opps, couldn't find instrument for ID=", id
326 class Measure (Music_xml_node):
327 def get_notes (self):
328 return self.get_typed_children (get_class (u'note'))
330 class Syllabic (Music_xml_node):
331 def continued (self):
332 text = self.get_text()
333 return (text == "begin") or (text == "middle")
334 class Text (Music_xml_node):
337 class Lyric (Music_xml_node):
338 def get_number (self):
339 if hasattr (self, 'number'):
344 def lyric_to_text (self):
346 syllabic = self.get_maybe_exist_typed_child (Syllabic)
348 continued = syllabic.continued ()
349 text = self.get_maybe_exist_typed_child (Text)
352 text = text.get_text()
353 # We need to convert soft hyphens to -, otherwise the ascii codec as well
354 # as lilypond will barf on that character
355 text = string.replace( text, u'\xad', '-' )
357 if text == "-" and continued:
359 elif text == "_" and continued:
361 elif continued and text:
362 return escape_ly_output_string (text) + " --"
366 return escape_ly_output_string (text)
370 class Musicxml_voice:
374 self._start_staff = None
376 self._has_lyrics = False
378 def add_element (self, e):
379 self._elements.append (e)
380 if (isinstance (e, Note)
381 and e.get_maybe_exist_typed_child (Staff)):
382 name = e.get_maybe_exist_typed_child (Staff).get_text ()
384 if not self._start_staff:
385 self._start_staff = name
386 self._staves[name] = True
388 lyrics = e.get_typed_children (Lyric)
389 if not self._has_lyrics:
390 self.has_lyrics = len (lyrics) > 0
394 if (nr > 0) and not (nr in self._lyrics):
395 self._lyrics.append (nr)
397 def insert (self, idx, e):
398 self._elements.insert (idx, e)
400 def get_lyrics_numbers (self):
401 if (len (self._lyrics) == 0) and self._has_lyrics:
402 #only happens if none of the <lyric> tags has a number attribute
409 class Part (Music_xml_node):
411 Music_xml_node.__init__ (self)
414 def get_part_list (self):
416 while n and n.get_name() != 'score-partwise':
419 return n.get_named_child ('part-list')
421 def interpret (self):
422 """Set durations and starting points."""
424 part_list = self.get_part_list ()
427 factor = Rational (1)
429 attributes_object = None
430 measures = self.get_typed_children (Measure)
431 last_moment = Rational (-1)
432 last_measure_position = Rational (-1)
434 measure_start_moment = now
435 measure_position = Rational (0)
436 for n in m.get_all_children ():
437 if isinstance (n, Hash_text):
441 if n.__class__ == Attributes:
442 n.set_attributes_from_previous (attributes_dict)
444 attributes_dict = n._dict.copy ()
445 attributes_object = n
447 factor = Rational (1,
448 int (attributes_dict.get ('divisions').get_text ()))
451 if (n.get_maybe_exist_typed_child (Duration)):
452 mxl_dur = n.get_maybe_exist_typed_child (Duration)
453 dur = mxl_dur.get_length () * factor
455 if n.get_name() == 'backup':
457 if n.get_maybe_exist_typed_child (Grace):
460 rest = n.get_maybe_exist_typed_child (Rest)
462 and attributes_object
463 and attributes_object.get_measure_length () == dur):
465 rest._is_whole_measure = True
467 if (dur > Rational (0)
468 and n.get_maybe_exist_typed_child (Chord)):
470 measure_position = last_measure_position
473 n._measure_position = measure_position
475 if dur > Rational (0):
477 last_measure_position = measure_position
479 measure_position += dur
480 if n._name == 'note':
481 instrument = n.get_maybe_exist_named_child ('instrument')
483 n.instrument_name = part_list.get_instrument (instrument.id)
485 if attributes_object:
486 length = attributes_object.get_measure_length ()
487 new_now = measure_start_moment + length
490 problem = 'incomplete'
494 ## only for verbose operation.
495 if problem <> 'incomplete':
496 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
500 def extract_voices (part):
502 measures = part.get_typed_children (Measure)
505 elements.extend (m.get_all_children ())
509 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
511 # TODO: If the first element of a voice is a dynamics entry,
512 # then voice_id is not yet set! Thus it will currently be ignored
513 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
516 if isinstance (n, Attributes) and not start_attr:
520 if isinstance (n, Attributes) or isinstance (n, Direction):
521 for v in voices.values ():
525 id = voice_id.get_text ()
526 if not voices.has_key (id):
527 voices[id] = Musicxml_voice()
529 voices[id].add_element (n)
532 for (k,v) in voices.items ():
533 v.insert (0, start_attr)
535 part._voices = voices
537 def get_voices (self):
540 class Notations (Music_xml_node):
542 ts = self.get_named_children ('tied')
543 starts = [t for t in ts if t.type == 'start']
549 def get_tuplet (self):
550 return self.get_maybe_exist_typed_child (Tuplet)
552 class Time_modification(Music_xml_node):
553 def get_fraction (self):
554 b = self.get_maybe_exist_named_child ('actual-notes')
555 a = self.get_maybe_exist_named_child ('normal-notes')
556 return (int(a.get_text ()), int (b.get_text ()))
558 class Accidental (Music_xml_node):
560 Music_xml_node.__init__ (self)
561 self.editorial = False
562 self.cautionary = False
564 class Music_xml_spanner (Music_xml_node):
566 if hasattr (self, 'type'):
571 if hasattr (self, 'size'):
572 return string.atoi (self.size)
576 class Wedge (Music_xml_spanner):
579 class Tuplet (Music_xml_spanner):
582 class Slur (Music_xml_spanner):
586 class Beam (Music_xml_spanner):
588 return self.get_text ()
589 def is_primary (self):
590 return self.number == "1"
592 class Wavy_line (Music_xml_spanner):
595 class Pedal (Music_xml_spanner):
598 class Glissando (Music_xml_spanner):
601 class Octave_shift (Music_xml_spanner):
602 # default is 8 for the octave-shift!
604 if hasattr (self, 'size'):
605 return string.atoi (self.size)
609 class Chord (Music_xml_node):
612 class Dot (Music_xml_node):
615 class Rest (Music_xml_node):
617 Music_xml_node.__init__ (self)
618 self._is_whole_measure = False
619 def is_whole_measure (self):
620 return self._is_whole_measure
622 class Type (Music_xml_node):
624 class Grace (Music_xml_node):
626 class Staff (Music_xml_node):
629 class Direction (Music_xml_node):
631 class DirType (Music_xml_node):
634 class Bend (Music_xml_node):
635 def bend_alter (self):
636 alter = self.get_maybe_exist_named_child ('bend-alter')
638 return alter.get_text()
644 ## need this, not all classes are instantiated
645 ## for every input file. Only add those classes, that are either directly
646 ## used by class name or extend Music_xml_node in some way!
648 '#comment': Hash_comment,
650 'accidental': Accidental,
651 'attributes': Attributes,
656 'direction': Direction,
657 'direction-type': DirType,
658 'duration': Duration,
659 'glissando': Glissando,
661 'identification': Identification,
664 'notations': Notations,
666 'octave-shift': Octave_shift,
668 'part-list': Part_list,
674 'syllabic': Syllabic,
676 'time-modification': Time_modification,
679 'wavy-line': Wavy_line,
684 def name2class_name (name):
685 name = name.replace ('-', '_')
686 name = name.replace ('#', 'hash_')
687 name = name[0].upper() + name[1:].lower()
691 def get_class (name):
692 classname = class_dict.get (name)
696 class_name = name2class_name (name)
697 klass = new.classobj (class_name, (Music_xml_node,) , {})
698 class_dict[name] = klass
701 def lxml_demarshal_node (node):
706 klass = get_class (name)
709 py_node._original = node
711 py_node._data = node.text
712 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
713 py_node._children = filter (lambda x: x, py_node._children)
715 for c in py_node._children:
718 for (k,v) in node.items ():
719 py_node.__dict__[k] = v
720 py_node._attribute_dict[k] = v
724 def minidom_demarshal_node (node):
727 klass = get_class (name)
730 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
731 for c in py_node._children:
735 for (nm, value) in node.attributes.items():
736 py_node.__dict__[nm] = value
737 py_node._attribute_dict[nm] = value
740 if node.nodeType == node.TEXT_NODE and node.data:
741 py_node._data = node.data
743 py_node._original = node
747 if __name__ == '__main__':
750 tree = lxml.etree.parse ('beethoven.xml')
751 mxl_tree = lxml_demarshal_node (tree.getroot ())
752 ks = class_dict.keys()