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):
171 class Hash_text (Music_xml_node):
174 class Pitch (Music_xml_node):
176 ch = self.get_unique_typed_child (get_class (u'step'))
177 step = ch.get_text ().strip ()
179 def get_octave (self):
180 ch = self.get_unique_typed_child (get_class (u'octave'))
182 step = ch.get_text ().strip ()
185 def get_alteration (self):
186 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
189 alter = int (ch.get_text ().strip ())
192 class Measure_element (Music_xml_node):
193 def get_voice_id (self):
194 voice_id = self.get_maybe_exist_named_child ('voice')
196 return voice_id.get_text ()
201 cn = self._parent.get_typed_children (self.__class__)
202 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
205 class Attributes (Measure_element):
207 Measure_element.__init__ (self)
210 def set_attributes_from_previous (self, dict):
211 self._dict.update (dict)
213 def read_self (self):
214 for c in self.get_all_children ():
215 self._dict[c.get_name()] = c
217 def get_named_attribute (self, name):
218 return self._dict.get (name)
220 def get_measure_length (self):
221 (n,d) = self.get_time_signature ()
222 return Rational (n,d)
224 def get_time_signature (self):
225 "return time sig as a (beat, beat-type) tuple"
228 mxl = self.get_named_attribute ('time')
230 beats = mxl.get_maybe_exist_named_child ('beats')
231 type = mxl.get_maybe_exist_named_child ('beat-type')
232 return (int (beats.get_text ()),
233 int (type.get_text ()))
235 print 'error: requested time signature, but time sig unknown'
238 # returns clef information in the form ("cleftype", position, octave-shift)
239 def get_clef_information (self):
240 clefinfo = ['G', 2, 0]
241 mxl = self.get_named_attribute ('clef')
244 sign = mxl.get_maybe_exist_named_child ('sign')
246 clefinfo[0] = sign.get_text()
247 line = mxl.get_maybe_exist_named_child ('line')
249 clefinfo[1] = string.atoi (line.get_text ())
250 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
252 clefinfo[2] = string.atoi (octave.get_text ())
255 def get_key_signature (self):
256 "return (fifths, mode) tuple"
258 key = self.get_named_attribute ('key')
259 mode_node = key.get_maybe_exist_named_child ('mode')
262 mode = mode_node.get_text ()
264 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
265 return (fifths, mode)
268 class Note (Measure_element):
270 Measure_element.__init__ (self)
271 self.instrument_name = ''
273 def get_duration_log (self):
274 ch = self.get_maybe_exist_typed_child (get_class (u'type'))
277 log = ch.get_text ().strip()
285 'whole': 0}.get (log)
289 def get_factor (self):
292 def get_pitches (self):
293 return self.get_typed_children (get_class (u'pitch'))
295 class Part_list (Music_xml_node):
297 Music_xml_node.__init__ (self)
298 self._id_instrument_name_dict = {}
300 def generate_id_instrument_dict (self):
302 ## not empty to make sure this happens only once.
304 for score_part in self.get_named_children ('score-part'):
305 for instr in score_part.get_named_children ('score-instrument'):
307 name = instr.get_named_child ("instrument-name")
308 mapping[id] = name.get_text ()
310 self._id_instrument_name_dict = mapping
312 def get_instrument (self, id):
313 if not self._id_instrument_name_dict:
314 self.generate_id_instrument_dict()
316 instrument_name = self._id_instrument_name_dict.get (id)
318 return instrument_name
320 print "Opps, couldn't find instrument for ID=", id
323 class Measure (Music_xml_node):
324 def get_notes (self):
325 return self.get_typed_children (get_class (u'note'))
327 class Syllabic (Music_xml_node):
328 def continued (self):
329 text = self.get_text()
330 return (text == "begin") or (text == "middle")
331 class Text (Music_xml_node):
334 class Lyric (Music_xml_node):
335 def get_number (self):
336 if hasattr (self, 'number'):
341 def lyric_to_text (self):
343 syllabic = self.get_maybe_exist_typed_child (Syllabic)
345 continued = syllabic.continued ()
346 text = self.get_maybe_exist_typed_child (Text)
349 text = text.get_text()
350 # We need to convert soft hyphens to -, otherwise the ascii codec as well
351 # as lilypond will barf on that character
352 text = string.replace( text, u'\xad', '-' )
354 if text == "-" and continued:
356 elif text == "_" and continued:
358 elif continued and text:
359 return escape_ly_output_string (text) + " --"
363 return escape_ly_output_string (text)
367 class Musicxml_voice:
371 self._start_staff = None
373 self._has_lyrics = False
375 def add_element (self, e):
376 self._elements.append (e)
377 if (isinstance (e, Note)
378 and e.get_maybe_exist_typed_child (Staff)):
379 name = e.get_maybe_exist_typed_child (Staff).get_text ()
381 if not self._start_staff:
382 self._start_staff = name
383 self._staves[name] = True
385 lyrics = e.get_typed_children (Lyric)
386 if not self._has_lyrics:
387 self.has_lyrics = len (lyrics) > 0
391 if (nr > 0) and not (nr in self._lyrics):
392 self._lyrics.append (nr)
394 def insert (self, idx, e):
395 self._elements.insert (idx, e)
397 def get_lyrics_numbers (self):
398 if (len (self._lyrics) == 0) and self._has_lyrics:
399 #only happens if none of the <lyric> tags has a number attribute
406 class Part (Music_xml_node):
408 Music_xml_node.__init__ (self)
411 def get_part_list (self):
413 while n and n.get_name() != 'score-partwise':
416 return n.get_named_child ('part-list')
418 def interpret (self):
419 """Set durations and starting points."""
421 part_list = self.get_part_list ()
424 factor = Rational (1)
426 attributes_object = None
427 measures = self.get_typed_children (Measure)
428 last_moment = Rational (-1)
429 last_measure_position = Rational (-1)
431 measure_start_moment = now
432 measure_position = Rational (0)
433 for n in m.get_all_children ():
434 if isinstance (n, Hash_text):
438 if n.__class__ == Attributes:
439 n.set_attributes_from_previous (attributes_dict)
441 attributes_dict = n._dict.copy ()
442 attributes_object = n
444 factor = Rational (1,
445 int (attributes_dict.get ('divisions').get_text ()))
448 if (n.get_maybe_exist_typed_child (Duration)):
449 mxl_dur = n.get_maybe_exist_typed_child (Duration)
450 dur = mxl_dur.get_length () * factor
452 if n.get_name() == 'backup':
454 if n.get_maybe_exist_typed_child (Grace):
457 rest = n.get_maybe_exist_typed_child (Rest)
459 and attributes_object
460 and attributes_object.get_measure_length () == dur):
462 rest._is_whole_measure = True
464 if (dur > Rational (0)
465 and n.get_maybe_exist_typed_child (Chord)):
467 measure_position = last_measure_position
470 last_measure_position = measure_position
473 n._measure_position = measure_position
476 measure_position += dur
477 if n._name == 'note':
478 instrument = n.get_maybe_exist_named_child ('instrument')
480 n.instrument_name = part_list.get_instrument (instrument.id)
482 if attributes_object:
483 length = attributes_object.get_measure_length ()
484 new_now = measure_start_moment + length
487 problem = 'incomplete'
491 ## only for verbose operation.
492 if problem <> 'incomplete':
493 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
497 def extract_voices (part):
499 measures = part.get_typed_children (Measure)
502 elements.extend (m.get_all_children ())
506 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
508 # TODO: If the first element of a voice is a dynamics entry,
509 # then voice_id is not yet set! Thus it will currently be ignored
510 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
513 if isinstance (n, Attributes) and not start_attr:
517 if isinstance (n, Attributes) or isinstance (n, Direction):
518 for v in voices.values ():
522 id = voice_id.get_text ()
523 if not voices.has_key (id):
524 voices[id] = Musicxml_voice()
526 voices[id].add_element (n)
529 for (k,v) in voices.items ():
530 v.insert (0, start_attr)
532 part._voices = voices
534 def get_voices (self):
537 class Notations (Music_xml_node):
539 ts = self.get_named_children ('tied')
540 starts = [t for t in ts if t.type == 'start']
546 def get_tuplet (self):
547 return self.get_maybe_exist_typed_child (Tuplet)
549 class Time_modification(Music_xml_node):
550 def get_fraction (self):
551 b = self.get_maybe_exist_named_child ('actual-notes')
552 a = self.get_maybe_exist_named_child ('normal-notes')
553 return (int(a.get_text ()), int (b.get_text ()))
555 class Accidental (Music_xml_node):
557 Music_xml_node.__init__ (self)
558 self.editorial = False
559 self.cautionary = False
561 class Music_xml_spanner (Music_xml_node):
563 if hasattr (self, 'type'):
568 if hasattr (self, 'size'):
569 return string.atoi (self.size)
573 class Tuplet(Music_xml_spanner):
576 class Slur (Music_xml_spanner):
580 class Beam (Music_xml_spanner):
582 return self.get_text ()
583 def is_primary (self):
584 return self.number == "1"
586 class Wavy_line (Music_xml_spanner):
589 class Pedal (Music_xml_spanner):
592 class Glissando (Music_xml_spanner):
595 class Octave_shift (Music_xml_spanner):
596 # default is 8 for the octave-shift!
598 if hasattr (self, 'size'):
599 return string.atoi (self.size)
603 class Chord (Music_xml_node):
606 class Dot (Music_xml_node):
609 class Rest (Music_xml_node):
611 Music_xml_node.__init__ (self)
612 self._is_whole_measure = False
613 def is_whole_measure (self):
614 return self._is_whole_measure
616 class Type (Music_xml_node):
618 class Grace (Music_xml_node):
620 class Staff (Music_xml_node):
623 class Direction (Music_xml_node):
625 class DirType (Music_xml_node):
628 class Bend (Music_xml_node):
629 def bend_alter (self):
630 alter = self.get_maybe_exist_named_child ('bend-alter')
632 return alter.get_text()
638 ## need this, not all classes are instantiated
639 ## for every input file. Only add those classes, that are either directly
640 ## used by class name or extend Music_xml_node in some way!
642 '#comment': Hash_comment,
644 'accidental': Accidental,
645 'attributes': Attributes,
650 'direction': Direction,
651 'direction-type': DirType,
652 'duration': Duration,
653 'glissando': Glissando,
655 'identification': Identification,
658 'notations': Notations,
660 'octave-shift': Octave_shift,
662 'part-list': Part_list,
667 'syllabic': Syllabic,
669 'time-modification': Time_modification,
672 'wavy-line': Wavy_line,
676 def name2class_name (name):
677 name = name.replace ('-', '_')
678 name = name.replace ('#', 'hash_')
679 name = name[0].upper() + name[1:].lower()
683 def get_class (name):
684 classname = class_dict.get (name)
688 class_name = name2class_name (name)
689 klass = new.classobj (class_name, (Music_xml_node,) , {})
690 class_dict[name] = klass
693 def lxml_demarshal_node (node):
698 klass = get_class (name)
701 py_node._original = node
703 py_node._data = node.text
704 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
705 py_node._children = filter (lambda x: x, py_node._children)
707 for c in py_node._children:
710 for (k,v) in node.items ():
711 py_node.__dict__[k] = v
712 py_node._attribute_dict[k] = v
716 def minidom_demarshal_node (node):
719 klass = get_class (name)
722 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
723 for c in py_node._children:
727 for (nm, value) in node.attributes.items():
728 py_node.__dict__[nm] = value
729 py_node._attribute_dict[nm] = value
732 if node.nodeType == node.TEXT_NODE and node.data:
733 py_node._data = node.data
735 py_node._original = node
739 if __name__ == '__main__':
742 tree = lxml.etree.parse ('beethoven.xml')
743 mxl_tree = lxml_demarshal_node (tree.getroot ())
744 ks = class_dict.keys()