7 def escape_ly_output_string (input_string):
8 return_string = input_string
9 needs_quotes = not re.match ("^[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)
49 sys.stderr.write (' 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)
85 sys.stderr.write (self.__dict__)
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 sys.stderr.write ('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()
288 'long': -2}.get (log, 0)
290 sys.stderr.write ("Encountered note without duration (no <type> element): %s\n" % self)
293 def get_factor (self):
296 def get_pitches (self):
297 return self.get_typed_children (get_class (u'pitch'))
299 class Part_list (Music_xml_node):
301 Music_xml_node.__init__ (self)
302 self._id_instrument_name_dict = {}
304 def generate_id_instrument_dict (self):
306 ## not empty to make sure this happens only once.
308 for score_part in self.get_named_children ('score-part'):
309 for instr in score_part.get_named_children ('score-instrument'):
311 name = instr.get_named_child ("instrument-name")
312 mapping[id] = name.get_text ()
314 self._id_instrument_name_dict = mapping
316 def get_instrument (self, id):
317 if not self._id_instrument_name_dict:
318 self.generate_id_instrument_dict()
320 instrument_name = self._id_instrument_name_dict.get (id)
322 return instrument_name
324 sys.stderr.write ("Opps, couldn't find instrument for ID=%s" % id)
327 class Measure (Music_xml_node):
328 def get_notes (self):
329 return self.get_typed_children (get_class (u'note'))
331 class Syllabic (Music_xml_node):
332 def continued (self):
333 text = self.get_text()
334 return (text == "begin") or (text == "middle")
335 class Text (Music_xml_node):
338 class Lyric (Music_xml_node):
339 def get_number (self):
340 if hasattr (self, 'number'):
345 def lyric_to_text (self):
347 syllabic = self.get_maybe_exist_typed_child (Syllabic)
349 continued = syllabic.continued ()
350 text = self.get_maybe_exist_typed_child (Text)
353 text = text.get_text()
354 # We need to convert soft hyphens to -, otherwise the ascii codec as well
355 # as lilypond will barf on that character
356 text = string.replace( text, u'\xad', '-' )
358 if text == "-" and continued:
360 elif text == "_" and continued:
362 elif continued and text:
363 return escape_ly_output_string (text) + " --"
367 return escape_ly_output_string (text)
371 class Musicxml_voice:
375 self._start_staff = None
377 self._has_lyrics = False
379 def add_element (self, e):
380 self._elements.append (e)
381 if (isinstance (e, Note)
382 and e.get_maybe_exist_typed_child (Staff)):
383 name = e.get_maybe_exist_typed_child (Staff).get_text ()
385 if not self._start_staff:
386 self._start_staff = name
387 self._staves[name] = True
389 lyrics = e.get_typed_children (Lyric)
390 if not self._has_lyrics:
391 self.has_lyrics = len (lyrics) > 0
395 if (nr > 0) and not (nr in self._lyrics):
396 self._lyrics.append (nr)
398 def insert (self, idx, e):
399 self._elements.insert (idx, e)
401 def get_lyrics_numbers (self):
402 if (len (self._lyrics) == 0) and self._has_lyrics:
403 #only happens if none of the <lyric> tags has a number attribute
410 class Part (Music_xml_node):
412 Music_xml_node.__init__ (self)
415 def get_part_list (self):
417 while n and n.get_name() != 'score-partwise':
420 return n.get_named_child ('part-list')
422 def interpret (self):
423 """Set durations and starting points."""
425 part_list = self.get_part_list ()
428 factor = Rational (1)
430 attributes_object = None
431 measures = self.get_typed_children (Measure)
432 last_moment = Rational (-1)
433 last_measure_position = Rational (-1)
435 measure_start_moment = now
436 measure_position = Rational (0)
437 for n in m.get_all_children ():
438 if isinstance (n, Hash_text):
442 if n.__class__ == Attributes:
443 n.set_attributes_from_previous (attributes_dict)
445 attributes_dict = n._dict.copy ()
446 attributes_object = n
448 factor = Rational (1,
449 int (attributes_dict.get ('divisions').get_text ()))
452 if (n.get_maybe_exist_typed_child (Duration)):
453 mxl_dur = n.get_maybe_exist_typed_child (Duration)
454 dur = mxl_dur.get_length () * factor
456 if n.get_name() == 'backup':
458 if n.get_maybe_exist_typed_child (Grace):
461 rest = n.get_maybe_exist_typed_child (Rest)
463 and attributes_object
464 and attributes_object.get_measure_length () == dur):
466 rest._is_whole_measure = True
468 if (dur > Rational (0)
469 and n.get_maybe_exist_typed_child (Chord)):
471 measure_position = last_measure_position
474 n._measure_position = measure_position
476 if dur > Rational (0):
478 last_measure_position = measure_position
480 measure_position += dur
481 elif dur < Rational (0):
482 # backup element, reset measure position
484 measure_position += dur
485 if measure_position < 0:
486 # backup went beyond the measure start => reset to 0
487 now -= measure_position
490 last_measure_position = measure_position
491 if n._name == 'note':
492 instrument = n.get_maybe_exist_named_child ('instrument')
494 n.instrument_name = part_list.get_instrument (instrument.id)
496 if attributes_object:
497 length = attributes_object.get_measure_length ()
498 new_now = measure_start_moment + length
501 problem = 'incomplete'
505 ## only for verbose operation.
506 if problem <> 'incomplete':
507 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
511 def extract_voices (part):
513 measures = part.get_typed_children (Measure)
516 elements.extend (m.get_all_children ())
520 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
522 # TODO: If the first element of a voice is a dynamics entry,
523 # then voice_id is not yet set! Thus it will currently be ignored
524 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
527 if isinstance (n, Attributes) and not start_attr:
531 if isinstance (n, Attributes) or isinstance (n, Direction):
532 for v in voices.values ():
536 id = voice_id.get_text ()
537 if not voices.has_key (id):
538 voices[id] = Musicxml_voice()
540 voices[id].add_element (n)
543 for (k,v) in voices.items ():
544 v.insert (0, start_attr)
546 part._voices = voices
548 def get_voices (self):
551 class Notations (Music_xml_node):
553 ts = self.get_named_children ('tied')
554 starts = [t for t in ts if t.type == 'start']
560 def get_tuplet (self):
561 return self.get_maybe_exist_typed_child (Tuplet)
563 class Time_modification(Music_xml_node):
564 def get_fraction (self):
565 b = self.get_maybe_exist_named_child ('actual-notes')
566 a = self.get_maybe_exist_named_child ('normal-notes')
567 return (int(a.get_text ()), int (b.get_text ()))
569 class Accidental (Music_xml_node):
571 Music_xml_node.__init__ (self)
572 self.editorial = False
573 self.cautionary = False
575 class Music_xml_spanner (Music_xml_node):
577 if hasattr (self, 'type'):
582 if hasattr (self, 'size'):
583 return string.atoi (self.size)
587 class Wedge (Music_xml_spanner):
590 class Tuplet (Music_xml_spanner):
593 class Slur (Music_xml_spanner):
597 class Beam (Music_xml_spanner):
599 return self.get_text ()
600 def is_primary (self):
601 return self.number == "1"
603 class Wavy_line (Music_xml_spanner):
606 class Pedal (Music_xml_spanner):
609 class Glissando (Music_xml_spanner):
612 class Octave_shift (Music_xml_spanner):
613 # default is 8 for the octave-shift!
615 if hasattr (self, 'size'):
616 return string.atoi (self.size)
620 class Chord (Music_xml_node):
623 class Dot (Music_xml_node):
626 class Rest (Music_xml_node):
628 Music_xml_node.__init__ (self)
629 self._is_whole_measure = False
630 def is_whole_measure (self):
631 return self._is_whole_measure
633 class Type (Music_xml_node):
635 class Grace (Music_xml_node):
637 class Staff (Music_xml_node):
640 class Direction (Music_xml_node):
642 class DirType (Music_xml_node):
645 class Bend (Music_xml_node):
646 def bend_alter (self):
647 alter = self.get_maybe_exist_named_child ('bend-alter')
649 return alter.get_text()
655 ## need this, not all classes are instantiated
656 ## for every input file. Only add those classes, that are either directly
657 ## used by class name or extend Music_xml_node in some way!
659 '#comment': Hash_comment,
661 'accidental': Accidental,
662 'attributes': Attributes,
667 'direction': Direction,
668 'direction-type': DirType,
669 'duration': Duration,
670 'glissando': Glissando,
672 'identification': Identification,
675 'notations': Notations,
677 'octave-shift': Octave_shift,
679 'part-list': Part_list,
685 'syllabic': Syllabic,
687 'time-modification': Time_modification,
690 'wavy-line': Wavy_line,
695 def name2class_name (name):
696 name = name.replace ('-', '_')
697 name = name.replace ('#', 'hash_')
698 name = name[0].upper() + name[1:].lower()
702 def get_class (name):
703 classname = class_dict.get (name)
707 class_name = name2class_name (name)
708 klass = new.classobj (class_name, (Music_xml_node,) , {})
709 class_dict[name] = klass
712 def lxml_demarshal_node (node):
717 klass = get_class (name)
720 py_node._original = node
722 py_node._data = node.text
723 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
724 py_node._children = filter (lambda x: x, py_node._children)
726 for c in py_node._children:
729 for (k,v) in node.items ():
730 py_node.__dict__[k] = v
731 py_node._attribute_dict[k] = v
735 def minidom_demarshal_node (node):
738 klass = get_class (name)
741 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
742 for c in py_node._children:
746 for (nm, value) in node.attributes.items():
747 py_node.__dict__[nm] = value
748 py_node._attribute_dict[nm] = value
751 if node.nodeType == node.TEXT_NODE and node.data:
752 py_node._data = node.data
754 py_node._original = node
758 if __name__ == '__main__':
761 tree = lxml.etree.parse ('beethoven.xml')
762 mxl_tree = lxml_demarshal_node (tree.getroot ())
763 ks = class_dict.keys()