6 def escape_ly_output_string (input_string):
7 return_string = input_string
8 needs_quotes = re.search ("[0-9\" ,.]", return_string);
9 return_string = string.replace (return_string, "\"", "\\\"")
11 return_string = "\"" + 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):
49 print ' In: <%s %s>' % (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)
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:
128 def get_composer (self):
129 c = self.get_creator ('composer')
132 creators = self.get_named_children ('creator')
133 # return the first creator tag that has no type at all
135 if not hasattr (i, 'type'):
138 def get_arranger (self):
139 return self.get_creator ('arranger')
140 def get_editor (self):
141 return self.get_creator ('editor')
143 return self.get_creator ('poet')
145 def get_encoding_information (self, type):
146 enc = self.get_named_children ('encoding')
148 children = enc[0].get_named_children (type)
150 return children[0].get_text ()
154 def get_encoding_software (self):
155 return self.get_encoding_information ('software')
156 def get_encoding_date (self):
157 return self.get_encoding_information ('encoding-date')
158 def get_encoding_person (self):
159 return self.get_encoding_information ('encoder')
160 def get_encoding_description (self):
161 return self.get_encoding_information ('encoding-description')
164 class Duration (Music_xml_node):
165 def get_length (self):
166 dur = int (self.get_text ()) * Rational (1,4)
169 class Hash_comment (Music_xml_node):
172 class Pitch (Music_xml_node):
174 ch = self.get_unique_typed_child (get_class (u'step'))
175 step = ch.get_text ().strip ()
177 def get_octave (self):
178 ch = self.get_unique_typed_child (get_class (u'octave'))
180 step = ch.get_text ().strip ()
183 def get_alteration (self):
184 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
187 alter = int (ch.get_text ().strip ())
190 class Measure_element (Music_xml_node):
191 def get_voice_id (self):
192 voice_id = self.get_maybe_exist_named_child ('voice')
194 return voice_id.get_text ()
199 cn = self._parent.get_typed_children (self.__class__)
200 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
203 class Attributes (Measure_element):
205 Measure_element.__init__ (self)
208 def set_attributes_from_previous (self, dict):
209 self._dict.update (dict)
211 def read_self (self):
212 for c in self.get_all_children ():
213 self._dict[c.get_name()] = c
215 def get_named_attribute (self, name):
216 return self._dict.get (name)
218 def get_measure_length (self):
219 (n,d) = self.get_time_signature ()
220 return Rational (n,d)
222 def get_time_signature (self):
223 "return time sig as a (beat, beat-type) tuple"
226 mxl = self.get_named_attribute ('time')
228 beats = mxl.get_maybe_exist_named_child ('beats')
229 type = mxl.get_maybe_exist_named_child ('beat-type')
230 return (int (beats.get_text ()),
231 int (type.get_text ()))
233 print 'error: requested time signature, but time sig unknown'
236 # returns clef information in the form ("cleftype", position, octave-shift)
237 def get_clef_information (self):
238 clefinfo = ['G', 2, 0]
239 mxl = self.get_named_attribute ('clef')
242 sign = mxl.get_maybe_exist_named_child ('sign')
244 clefinfo[0] = sign.get_text()
245 line = mxl.get_maybe_exist_named_child ('line')
247 clefinfo[1] = string.atoi (line.get_text ())
248 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
250 clefinfo[2] = string.atoi (octave.get_text ())
253 def get_key_signature (self):
254 "return (fifths, mode) tuple"
256 key = self.get_named_attribute ('key')
257 mode_node = key.get_maybe_exist_named_child ('mode')
260 mode = mode_node.get_text ()
262 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
263 return (fifths, mode)
266 class Note (Measure_element):
268 Measure_element.__init__ (self)
269 self.instrument_name = ''
271 def get_duration_log (self):
272 ch = self.get_maybe_exist_typed_child (get_class (u'type'))
275 log = ch.get_text ().strip()
283 'whole': 0}.get (log)
287 def get_factor (self):
290 def get_pitches (self):
291 return self.get_typed_children (get_class (u'pitch'))
293 class Part_list (Music_xml_node):
295 Music_xml_node.__init__ (self)
296 self._id_instrument_name_dict = {}
298 def generate_id_instrument_dict (self):
300 ## not empty to make sure this happens only once.
302 for score_part in self.get_named_children ('score-part'):
303 for instr in score_part.get_named_children ('score-instrument'):
305 name = instr.get_named_child ("instrument-name")
306 mapping[id] = name.get_text ()
308 self._id_instrument_name_dict = mapping
310 def get_instrument (self, id):
311 if not self._id_instrument_name_dict:
312 self.generate_id_instrument_dict()
314 instrument_name = self._id_instrument_name_dict.get (id)
316 return instrument_name
318 print "Opps, couldn't find instrument for ID=", id
321 class Measure (Music_xml_node):
322 def get_notes (self):
323 return self.get_typed_children (get_class (u'note'))
325 class Syllabic (Music_xml_node):
326 def continued (self):
327 text = self.get_text()
328 return (text == "begin") or (text == "middle")
329 class Text (Music_xml_node):
332 class Lyric (Music_xml_node):
333 def get_number (self):
334 if hasattr (self, 'number'):
339 def lyric_to_text (self):
341 syllabic = self.get_maybe_exist_typed_child (Syllabic)
343 continued = syllabic.continued ()
344 text = self.get_maybe_exist_typed_child (Text)
347 text = text.get_text()
348 # We need to convert soft hyphens to -, otherwise the ascii codec as well
349 # as lilypond will barf on that character
350 text = string.replace( text, u'\xad', '-' )
352 if text == "-" and continued:
354 elif text == "_" and continued:
356 elif continued and text:
357 return escape_ly_output_string (text) + " --"
361 return escape_ly_output_string (text)
365 class Musicxml_voice:
369 self._start_staff = None
371 self._has_lyrics = False
373 def add_element (self, e):
374 self._elements.append (e)
375 if (isinstance (e, Note)
376 and e.get_maybe_exist_typed_child (Staff)):
377 name = e.get_maybe_exist_typed_child (Staff).get_text ()
379 if not self._start_staff:
380 self._start_staff = name
381 self._staves[name] = True
383 lyrics = e.get_typed_children (Lyric)
384 if not self._has_lyrics:
385 self.has_lyrics = len (lyrics) > 0
389 if (nr > 0) and not (nr in self._lyrics):
390 self._lyrics.append (nr)
392 def insert (self, idx, e):
393 self._elements.insert (idx, e)
395 def get_lyrics_numbers (self):
396 if (len (self._lyrics) == 0) and self._has_lyrics:
397 #only happens if none of the <lyric> tags has a number attribute
404 class Part (Music_xml_node):
406 Music_xml_node.__init__ (self)
409 def get_part_list (self):
411 while n and n.get_name() != 'score-partwise':
414 return n.get_named_child ('part-list')
416 def interpret (self):
417 """Set durations and starting points."""
419 part_list = self.get_part_list ()
422 factor = Rational (1)
424 attributes_object = None
425 measures = self.get_typed_children (Measure)
426 last_moment = Rational (-1)
427 last_measure_position = Rational (-1)
429 measure_start_moment = now
430 measure_position = Rational (0)
431 for n in m.get_all_children ():
434 if n.__class__ == Attributes:
435 n.set_attributes_from_previous (attributes_dict)
437 attributes_dict = n._dict.copy ()
438 attributes_object = n
440 factor = Rational (1,
441 int (attributes_dict.get ('divisions').get_text ()))
444 if (n.get_maybe_exist_typed_child (Duration)):
445 mxl_dur = n.get_maybe_exist_typed_child (Duration)
446 dur = mxl_dur.get_length () * factor
448 if n.get_name() == 'backup':
450 if n.get_maybe_exist_typed_child (Grace):
453 rest = n.get_maybe_exist_typed_child (Rest)
455 and attributes_object
456 and attributes_object.get_measure_length () == dur):
458 rest._is_whole_measure = True
460 if (dur > Rational (0)
461 and n.get_maybe_exist_typed_child (Chord)):
463 measure_position = last_measure_position
466 last_measure_position = measure_position
469 n._measure_position = measure_position
472 measure_position += dur
473 if n._name == 'note':
474 instrument = n.get_maybe_exist_named_child ('instrument')
476 n.instrument_name = part_list.get_instrument (instrument.id)
478 if attributes_object:
479 length = attributes_object.get_measure_length ()
480 new_now = measure_start_moment + length
483 problem = 'incomplete'
487 ## only for verbose operation.
488 if problem <> 'incomplete':
489 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
493 def extract_voices (part):
495 measures = part.get_typed_children (Measure)
498 elements.extend (m.get_all_children ())
502 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
504 # TODO: If the first element of a voice is a dynamics entry,
505 # then voice_id is not yet set! Thus it will currently be ignored
506 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
509 if isinstance (n, Attributes) and not start_attr:
513 if isinstance (n, Attributes) or isinstance (n, Direction):
514 for v in voices.values ():
518 id = voice_id.get_text ()
519 if not voices.has_key (id):
520 voices[id] = Musicxml_voice()
522 voices[id].add_element (n)
525 for (k,v) in voices.items ():
526 v.insert (0, start_attr)
528 part._voices = voices
530 def get_voices (self):
533 class Notations (Music_xml_node):
535 ts = self.get_named_children ('tied')
536 starts = [t for t in ts if t.type == 'start']
542 def get_tuplet (self):
543 return self.get_maybe_exist_typed_child (Tuplet)
545 class Time_modification(Music_xml_node):
546 def get_fraction (self):
547 b = self.get_maybe_exist_named_child ('actual-notes')
548 a = self.get_maybe_exist_named_child ('normal-notes')
549 return (int(a.get_text ()), int (b.get_text ()))
551 class Accidental (Music_xml_node):
553 Music_xml_node.__init__ (self)
554 self.editorial = False
555 self.cautionary = False
557 class Music_xml_spanner (Music_xml_node):
559 if hasattr (self, 'type'):
564 if hasattr (self, 'size'):
565 return string.atoi (self.size)
569 class Tuplet(Music_xml_spanner):
572 class Slur (Music_xml_spanner):
576 class Beam (Music_xml_spanner):
578 return self.get_text ()
579 def is_primary (self):
580 return self.number == "1"
582 class Wavy_line (Music_xml_spanner):
585 class Pedal (Music_xml_spanner):
588 class Glissando (Music_xml_spanner):
591 class Octave_shift (Music_xml_spanner):
592 # default is 8 for the octave-shift!
594 if hasattr (self, 'size'):
595 return string.atoi (self.size)
599 class Chord (Music_xml_node):
602 class Dot (Music_xml_node):
605 class Rest (Music_xml_node):
607 Music_xml_node.__init__ (self)
608 self._is_whole_measure = False
609 def is_whole_measure (self):
610 return self._is_whole_measure
612 class Type (Music_xml_node):
614 class Grace (Music_xml_node):
616 class Staff (Music_xml_node):
619 class Direction (Music_xml_node):
621 class DirType (Music_xml_node):
624 class Bend (Music_xml_node):
625 def bend_alter (self):
626 alter = self.get_maybe_exist_named_child ('bend-alter')
628 return alter.get_text()
634 ## need this, not all classes are instantiated
635 ## for every input file. Only add those classes, that are either directly
636 ## used by class name or extend Music_xml_node in some way!
638 '#comment': Hash_comment,
639 'accidental': Accidental,
640 'attributes': Attributes,
645 'direction': Direction,
646 'direction-type': DirType,
647 'duration': Duration,
648 'glissando': Glissando,
650 'identification': Identification,
653 'notations': Notations,
655 'octave-shift': Octave_shift,
657 'part-list': Part_list,
662 'syllabic': Syllabic,
664 'time-modification': Time_modification,
667 'wavy-line': Wavy_line,
671 def name2class_name (name):
672 name = name.replace ('-', '_')
673 name = name.replace ('#', 'hash_')
674 name = name[0].upper() + name[1:].lower()
678 def get_class (name):
679 classname = class_dict.get (name)
683 class_name = name2class_name (name)
684 klass = new.classobj (class_name, (Music_xml_node,) , {})
685 class_dict[name] = klass
688 def lxml_demarshal_node (node):
693 klass = get_class (name)
696 py_node._original = node
698 py_node._data = node.text
699 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
700 py_node._children = filter (lambda x: x, py_node._children)
702 for c in py_node._children:
705 for (k,v) in node.items ():
706 py_node.__dict__[k] = v
707 py_node._attribute_dict[k] = v
711 def minidom_demarshal_node (node):
714 klass = get_class (name)
717 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
718 for c in py_node._children:
722 for (nm, value) in node.attributes.items():
723 py_node.__dict__[nm] = value
724 py_node._attribute_dict[nm] = value
727 if node.nodeType == node.TEXT_NODE and node.data:
728 py_node._data = node.data
730 py_node._original = node
734 if __name__ == '__main__':
737 tree = lxml.etree.parse ('beethoven.xml')
738 mxl_tree = lxml_demarshal_node (tree.getroot ())
739 ks = class_dict.keys()