]> git.donarmstrong.com Git - lilypond.git/blob - python/musicxml.py
MusicXML: Add support for unpitched elements.
[lilypond.git] / python / musicxml.py
1 # -*- coding: utf-8 -*-
2 import new
3 import string
4 from rational import *
5 import re
6 import sys
7 import copy
8
9 def escape_ly_output_string (input_string):
10     return_string = input_string
11     needs_quotes = not re.match (u"^[a-zA-ZäöüÜÄÖßñ]*$", return_string);
12     if needs_quotes:
13         return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
14     return return_string
15
16
17 class Xml_node:
18     def __init__ (self):
19         self._children = []
20         self._data = None
21         self._original = None
22         self._name = 'xml_node'
23         self._parent = None
24         self._attribute_dict = {}
25         
26     def get_parent (self):
27         return self._parent
28     
29     def is_first (self):
30         return self._parent.get_typed_children (self.__class__)[0] == self
31
32     def original (self):
33         return self._original 
34     def get_name (self):
35         return self._name
36
37     def get_text (self):
38         if self._data:
39             return self._data
40
41         if not self._children:
42             return ''
43
44         return ''.join ([c.get_text () for c in self._children])
45
46     def message (self, msg):
47         sys.stderr.write (msg+'\n')
48
49         p = self
50         while p:
51             sys.stderr.write ('  In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()])))
52             p = p.get_parent ()
53         
54     def get_typed_children (self, klass):
55         if not klass:
56             return []
57         else:
58             return [c for c in self._children if isinstance(c, klass)]
59
60     def get_named_children (self, nm):
61         return self.get_typed_children (get_class (nm))
62
63     def get_named_child (self, nm):
64         return self.get_maybe_exist_named_child (nm)
65
66     def get_children (self, predicate):
67         return [c for c in self._children if predicate(c)]
68
69     def get_all_children (self):
70         return self._children
71
72     def get_maybe_exist_named_child (self, name):
73         return self.get_maybe_exist_typed_child (get_class (name))
74
75     def get_maybe_exist_typed_child (self, klass):
76         cn = self.get_typed_children (klass)
77         if len (cn)==0:
78             return None
79         elif len (cn) == 1:
80             return cn[0]
81         else:
82             raise "More than 1 child", klass
83
84     def get_unique_typed_child (self, klass):
85         cn = self.get_typed_children(klass)
86         if len (cn) <> 1:
87             sys.stderr.write (self.__dict__ + '\n')
88             raise 'Child is not unique for', (klass, 'found', cn)
89
90         return cn[0]
91
92     def get_named_child_value_number (self, name, default):
93         n = self.get_maybe_exist_named_child (name)
94         if n:
95             return string.atoi (n.get_text())
96         else:
97             return default
98
99
100 class Music_xml_node (Xml_node):
101     def __init__ (self):
102         Xml_node.__init__ (self)
103         self.duration = Rational (0)
104         self.start = Rational (0)
105
106 class Work (Xml_node):
107     def get_work_information (self, tag):
108         wt = self.get_maybe_exist_named_child (tag)
109         if wt:
110             return wt.get_text ()
111         else:
112             return ''
113       
114     def get_work_title (self):
115         return self.get_work_information ('work-title')
116     def get_work_number (self):
117         return self.get_work_information ('work-number')
118     def get_opus (self):
119         return self.get_work_information ('opus')
120
121 class Identification (Xml_node):
122     def get_rights (self):
123         rights = self.get_maybe_exist_named_child ('rights')
124         if rights:
125             return rights.get_text ()
126         else:
127             return ''
128
129     def get_creator (self, type):
130         creators = self.get_named_children ('creator')
131         # return the first creator tag that has the particular type
132         for i in creators:
133             if hasattr (i, 'type') and i.type == type:
134                 return i.get_text ()
135         return None
136
137     def get_composer (self):
138         c = self.get_creator ('composer')
139         if c:
140             return c
141         creators = self.get_named_children ('creator')
142         # return the first creator tag that has no type at all
143         for i in creators:
144             if not hasattr (i, 'type'):
145                 return i.get_text ()
146         return None
147     def get_arranger (self):
148         return self.get_creator ('arranger')
149     def get_editor (self):
150         return self.get_creator ('editor')
151     def get_poet (self):
152         v = self.get_creator ('lyricist')
153         if v:
154             return v
155         v = self.get_creator ('poet')
156         return v
157     
158     def get_encoding_information (self, type):
159         enc = self.get_named_children ('encoding')
160         if enc:
161             children = enc[0].get_named_children (type)
162             if children:
163                 return children[0].get_text ()
164         else:
165             return None
166       
167     def get_encoding_software (self):
168         return self.get_encoding_information ('software')
169     def get_encoding_date (self):
170         return self.get_encoding_information ('encoding-date')
171     def get_encoding_person (self):
172         return self.get_encoding_information ('encoder')
173     def get_encoding_description (self):
174         return self.get_encoding_information ('encoding-description')
175
176
177 class Duration (Music_xml_node):
178     def get_length (self):
179         dur = int (self.get_text ()) * Rational (1,4)
180         return dur
181
182 class Hash_comment (Music_xml_node):
183     pass
184 class Hash_text (Music_xml_node):
185     pass
186
187 class Pitch (Music_xml_node):
188     def get_step (self):
189         ch = self.get_unique_typed_child (get_class (u'step'))
190         step = ch.get_text ().strip ()
191         return step
192     def get_octave (self):
193         ch = self.get_unique_typed_child (get_class (u'octave'))
194
195         step = ch.get_text ().strip ()
196         return int (step)
197
198     def get_alteration (self):
199         ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
200         alter = 0
201         if ch:
202             alter = int (ch.get_text ().strip ())
203         return alter
204
205 class Unpitched (Music_xml_node):
206     def get_step (self):
207         ch = self.get_unique_typed_child (get_class (u'display-step'))
208         step = ch.get_text ().strip ()
209         return step
210
211     def get_octave (self):
212         ch = self.get_unique_typed_child (get_class (u'display-octave'))
213
214         if ch:
215             octave = ch.get_text ().strip ()
216             return int (octave)
217         else:
218             return None
219
220 class Measure_element (Music_xml_node):
221     def get_voice_id (self):
222         voice_id = self.get_maybe_exist_named_child ('voice')
223         if voice_id:
224             return voice_id.get_text ()
225         else:
226             return None
227
228     def is_first (self):
229         cn = self._parent.get_typed_children (self.__class__)
230         cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
231         return cn[0] == self
232
233 class Attributes (Measure_element):
234     def __init__ (self):
235         Measure_element.__init__ (self)
236         self._dict = {}
237
238     def set_attributes_from_previous (self, dict):
239         self._dict.update (dict)
240         
241     def read_self (self):
242         for c in self.get_all_children ():
243             self._dict[c.get_name()] = c
244
245     def get_named_attribute (self, name):
246         return self._dict.get (name)
247
248     def get_measure_length (self):
249         (n,d) = self.get_time_signature ()
250         return Rational (n,d)
251         
252     def get_time_signature (self):
253         "return time sig as a (beat, beat-type) tuple"
254
255         try:
256             mxl = self.get_named_attribute ('time')
257             if mxl:
258                 beats = mxl.get_maybe_exist_named_child ('beats')
259                 type = mxl.get_maybe_exist_named_child ('beat-type')
260                 return (int (beats.get_text ()),
261                         int (type.get_text ()))
262             else:
263                 return (4, 4)
264         except KeyError:
265             sys.stderr.write ('error: requested time signature, but time sig unknown\n')
266             return (4, 4)
267
268     # returns clef information in the form ("cleftype", position, octave-shift)
269     def get_clef_information (self):
270         clefinfo = ['G', 2, 0]
271         mxl = self.get_named_attribute ('clef')
272         if not mxl:
273             return clefinfo
274         sign = mxl.get_maybe_exist_named_child ('sign')
275         if sign:
276             clefinfo[0] = sign.get_text()
277         line = mxl.get_maybe_exist_named_child ('line')
278         if line:
279             clefinfo[1] = string.atoi (line.get_text ())
280         octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
281         if octave:
282             clefinfo[2] = string.atoi (octave.get_text ())
283         return clefinfo
284
285     def get_key_signature (self):
286         "return (fifths, mode) tuple"
287
288         key = self.get_named_attribute ('key')
289         mode_node = key.get_maybe_exist_named_child ('mode')
290         mode = 'major'
291         if mode_node:
292             mode = mode_node.get_text ()
293
294         fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
295         return (fifths, mode)
296
297 class Barline (Measure_element):
298     pass
299 class BarStyle (Music_xml_node):
300     pass
301 class Partial (Measure_element):
302     def __init__ (self, partial):
303         Measure_element.__init__ (self)
304         self.partial = partial
305
306 class Note (Measure_element):
307     def __init__ (self):
308         Measure_element.__init__ (self)
309         self.instrument_name = ''
310         
311     def get_duration_log (self):
312         ch = self.get_maybe_exist_named_child (u'type')
313
314         if ch:
315             log = ch.get_text ().strip()
316             return {'256th': 8,
317                     '128th': 7,
318                     '64th': 6,
319                     '32nd': 5,
320                     '16th': 4,
321                     'eighth': 3,
322                     'quarter': 2,
323                     'half': 1,
324                     'whole': 0,
325                     'breve': -1,
326                     'long': -2}.get (log, 0)
327         else:
328             self.message ("Encountered note at %s with %s duration (no <type> element):" % (self.start, self.duration) )
329             return 0
330
331     def get_factor (self):
332         return 1
333
334     def get_pitches (self):
335         return self.get_typed_children (get_class (u'pitch'))
336
337 class Part_list (Music_xml_node):
338     def __init__ (self):
339         Music_xml_node.__init__ (self)
340         self._id_instrument_name_dict = {}
341         
342     def generate_id_instrument_dict (self):
343
344         ## not empty to make sure this happens only once.
345         mapping = {1: 1}
346         for score_part in self.get_named_children ('score-part'):
347             for instr in score_part.get_named_children ('score-instrument'):
348                 id = instr.id
349                 name = instr.get_named_child ("instrument-name")
350                 mapping[id] = name.get_text ()
351
352         self._id_instrument_name_dict = mapping
353
354     def get_instrument (self, id):
355         if not self._id_instrument_name_dict:
356             self.generate_id_instrument_dict()
357
358         instrument_name = self._id_instrument_name_dict.get (id)
359         if instrument_name:
360             return instrument_name
361         else:
362             sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
363             return "Grand Piano"
364
365 class Part_group (Music_xml_node):
366     pass
367 class Score_part (Music_xml_node):
368     pass
369         
370 class Measure (Music_xml_node):
371     def __init__ (self):
372         Music_xml_node.__init__ (self)
373         self.partial = 0
374     def is_implicit (self):
375         return hasattr (self, 'implicit') and self.implicit == 'yes'
376     def get_notes (self):
377         return self.get_typed_children (get_class (u'note'))
378
379 class Syllabic (Music_xml_node):
380     def continued (self):
381         text = self.get_text()
382         return (text == "begin") or (text == "middle")
383 class Text (Music_xml_node):
384     pass
385
386 class Lyric (Music_xml_node):
387     def get_number (self):
388         if hasattr (self, 'number'):
389             return self.number
390         else:
391             return -1
392
393     def lyric_to_text (self):
394         continued = False
395         syllabic = self.get_maybe_exist_typed_child (Syllabic)
396         if syllabic:
397             continued = syllabic.continued ()
398         text = self.get_maybe_exist_typed_child (Text)
399         
400         if text:
401             text = text.get_text()
402             # We need to convert soft hyphens to -, otherwise the ascii codec as well
403             # as lilypond will barf on that character
404             text = string.replace( text, u'\xad', '-' )
405         
406         if text == "-" and continued:
407             return "--"
408         elif text == "_" and continued:
409             return "__"
410         elif continued and text:
411             return escape_ly_output_string (text) + " --"
412         elif continued:
413             return "--"
414         elif text:
415             return escape_ly_output_string (text)
416         else:
417             return ""
418
419 class Musicxml_voice:
420     def __init__ (self):
421         self._elements = []
422         self._staves = {}
423         self._start_staff = None
424         self._lyrics = []
425         self._has_lyrics = False
426
427     def add_element (self, e):
428         self._elements.append (e)
429         if (isinstance (e, Note)
430             and e.get_maybe_exist_typed_child (Staff)):
431             name = e.get_maybe_exist_typed_child (Staff).get_text ()
432
433             if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
434                 self._start_staff = name
435             self._staves[name] = True
436
437         lyrics = e.get_typed_children (Lyric)
438         if not self._has_lyrics:
439           self.has_lyrics = len (lyrics) > 0
440
441         for l in lyrics:
442             nr = l.get_number()
443             if (nr > 0) and not (nr in self._lyrics):
444                 self._lyrics.append (nr)
445
446     def insert (self, idx, e):
447         self._elements.insert (idx, e)
448
449     def get_lyrics_numbers (self):
450         if (len (self._lyrics) == 0) and self._has_lyrics:
451             #only happens if none of the <lyric> tags has a number attribute
452             return [1]
453         else:
454             return self._lyrics
455
456
457 class Part (Music_xml_node):
458     def __init__ (self):
459         Music_xml_node.__init__ (self)
460         self._voices = {}
461         self._staff_attributes_dict = {}
462
463     def get_part_list (self):
464         n = self
465         while n and n.get_name() != 'score-partwise':
466             n = n._parent
467
468         return n.get_named_child ('part-list')
469         
470     def interpret (self):
471         """Set durations and starting points."""
472         """The starting point of the very first note is 0!"""
473         
474         part_list = self.get_part_list ()
475         
476         now = Rational (0)
477         factor = Rational (1)
478         attributes_dict = {}
479         attributes_object = None
480         measures = self.get_typed_children (Measure)
481         last_moment = Rational (-1)
482         last_measure_position = Rational (-1)
483         measure_position = Rational (0)
484         measure_start_moment = now
485         is_first_measure = True
486         previous_measure = None
487         for m in measures:
488             # implicit measures are used for artificial measures, e.g. when
489             # a repeat bar line splits a bar into two halves. In this case,
490             # don't reset the measure position to 0. They are also used for
491             # upbeats (initial value of 0 fits these, too).
492             # Also, don't reset the measure position at the end of the loop,
493             # but rather when starting the next measure (since only then do we
494             # know if the next measure is implicit and continues that measure)
495             if not m.is_implicit ():
496                 # Warn about possibly overfull measures and reset the position
497                 if attributes_object and previous_measure and previous_measure.partial == 0:
498                     length = attributes_object.get_measure_length ()
499                     new_now = measure_start_moment + length
500                     if now <> new_now:
501                         problem = 'incomplete'
502                         if now > new_now:
503                             problem = 'overfull'
504                         ## only for verbose operation.
505                         if problem <> 'incomplete' and previous_measure:
506                             previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
507                     now = new_now
508                 measure_start_moment = now
509                 measure_position = Rational (0)
510
511             for n in m.get_all_children ():
512                 if isinstance (n, Hash_text):
513                     continue
514                 dur = Rational (0)
515
516                 if n.__class__ == Attributes:
517                     n.set_attributes_from_previous (attributes_dict)
518                     n.read_self ()
519                     attributes_dict = n._dict.copy ()
520                     attributes_object = n
521                     
522                     factor = Rational (1,
523                                        int (attributes_dict.get ('divisions').get_text ()))
524
525                 
526                 if (n.get_maybe_exist_typed_child (Duration)):
527                     mxl_dur = n.get_maybe_exist_typed_child (Duration)
528                     dur = mxl_dur.get_length () * factor
529                     
530                     if n.get_name() == 'backup':
531                         dur = - dur
532                     if n.get_maybe_exist_typed_child (Grace):
533                         dur = Rational (0)
534
535                     rest = n.get_maybe_exist_typed_child (Rest)
536                     if (rest
537                         and attributes_object
538                         and attributes_object.get_measure_length () == dur):
539
540                         rest._is_whole_measure = True
541
542                 if (dur > Rational (0) 
543                     and n.get_maybe_exist_typed_child (Chord)):
544                     now = last_moment
545                     measure_position = last_measure_position
546
547                 n._when = now
548                 n._measure_position = measure_position
549                 n._duration = dur
550                 if dur > Rational (0):
551                     last_moment = now
552                     last_measure_position = measure_position
553                     now += dur
554                     measure_position += dur
555                 elif dur < Rational (0):
556                     # backup element, reset measure position
557                     now += dur
558                     measure_position += dur
559                     if measure_position < 0:
560                         # backup went beyond the measure start => reset to 0
561                         now -= measure_position
562                         measure_position = 0
563                     last_moment = now
564                     last_measure_position = measure_position
565                 if n._name == 'note':
566                     instrument = n.get_maybe_exist_named_child ('instrument')
567                     if instrument:
568                         n.instrument_name = part_list.get_instrument (instrument.id)
569
570             # Incomplete first measures are not padded, but registered as partial
571             if is_first_measure:
572                 is_first_measure = False
573                 # upbeats are marked as implicit measures
574                 if attributes_object and m.is_implicit ():
575                     length = attributes_object.get_measure_length ()
576                     measure_end = measure_start_moment + length
577                     if measure_end <> now:
578                         m.partial = now
579             previous_measure = m
580
581     # modify attributes so that only those applying to the given staff remain
582     def extract_attributes_for_staff (part, attr, staff):
583         attributes = copy.copy (attr)
584         attributes._children = copy.copy (attr._children)
585         attributes._dict = attr._dict.copy ()
586         for c in attributes._children:
587             if hasattr (c, 'number') and c.number != staff:
588                 attributes._children.remove (c)
589         return attributes
590
591     def extract_voices (part):
592         voices = {}
593         measures = part.get_typed_children (Measure)
594         elements = []
595         for m in measures:
596             if m.partial > 0:
597                 elements.append (Partial (m.partial))
598             elements.extend (m.get_all_children ())
599         # make sure we know all voices already so that dynamics, clefs, etc.
600         # can be assigned to the correct voices
601         voice_to_staff_dict = {}
602         for n in elements:
603             voice_id = n.get_maybe_exist_named_child (u'voice')
604             vid = None
605             if voice_id:
606                 vid = voice_id.get_text ()
607
608             staff_id = n.get_maybe_exist_named_child (u'staff')
609             sid = None
610             if staff_id:
611                 sid = staff_id.get_text ()
612             else:
613                 sid = "None"
614             if vid and not voices.has_key (vid):
615                 voices[vid] = Musicxml_voice()
616             if vid and sid and not n.get_maybe_exist_typed_child (Grace):
617                 if not voice_to_staff_dict.has_key (vid):
618                     voice_to_staff_dict[vid] = sid
619         # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
620         # need to assign staff-assigned objects like clefs, times, etc. to
621         # all the correct voices. This will never work entirely correct due
622         # to staff-switches, but that's the best we can do!
623         staff_to_voice_dict = {}
624         for (v,s) in voice_to_staff_dict.items ():
625             if not staff_to_voice_dict.has_key (s):
626                 staff_to_voice_dict[s] = [v]
627             else:
628                 staff_to_voice_dict[s].append (v)
629
630
631         start_attr = None
632         assign_to_next_note = []
633         id = None
634         for n in elements:
635             voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
636
637             if not (voice_id or isinstance (n, Attributes) or
638                     isinstance (n, Direction) or isinstance (n, Partial) or
639                     isinstance (n, Barline) or isinstance (n, Harmony) ):
640                 continue
641
642             if isinstance (n, Attributes) and not start_attr:
643                 start_attr = n
644                 continue
645
646             if isinstance (n, Attributes):
647                 # assign these only to the voices they really belongs to!
648                 for (s, vids) in staff_to_voice_dict.items ():
649                     staff_attributes = part.extract_attributes_for_staff (n, s)
650                     for v in vids:
651                         voices[v].add_element (staff_attributes)
652                 continue
653
654             if isinstance (n, Partial) or isinstance (n, Barline):
655                 for v in voices.keys ():
656                     voices[v].add_element (n)
657                 continue
658
659             if isinstance (n, Direction):
660                 staff_id = n.get_maybe_exist_named_child (u'staff')
661                 if staff_id:
662                     staff_id = staff_id.get_text ()
663                 if staff_id:
664                     dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
665                 else:
666                     dir_voices = voices.keys ()
667                 for v in dir_voices:
668                     voices[v].add_element (n)
669                 continue
670
671             if isinstance (n, Harmony):
672                 # store the harmony element until we encounter the next note
673                 # and assign it only to that one voice.
674                 assign_to_next_note.append (n)
675                 continue
676
677             id = voice_id.get_text ()
678             if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
679                 #Skip this note. 
680                 pass
681             else:
682                 for i in assign_to_next_note:
683                     voices[id].add_element (i)
684                 assign_to_next_note = []
685                 voices[id].add_element (n)
686
687         # Assign all remaining elements from assign_to_next_note to the voice
688         # of the previous note:
689         for i in assign_to_next_note:
690             voices[id].add_element (i)
691         assign_to_next_note = []
692
693         if start_attr:
694             for (s, vids) in staff_to_voice_dict.items ():
695                 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
696                 staff_attributes.read_self ()
697                 part._staff_attributes_dict[s] = staff_attributes
698                 for v in vids:
699                     voices[v].insert (0, staff_attributes)
700                     voices[v]._elements[0].read_self()
701
702         part._voices = voices
703
704     def get_voices (self):
705         return self._voices
706     def get_staff_attributes (self):
707         return self._staff_attributes_dict
708
709 class Notations (Music_xml_node):
710     def get_tie (self):
711         ts = self.get_named_children ('tied')
712         starts = [t for t in ts if t.type == 'start']
713         if starts:
714             return starts[0]
715         else:
716             return None
717
718     def get_tuplets (self):
719         return self.get_typed_children (Tuplet)
720
721 class Time_modification(Music_xml_node):
722     def get_fraction (self):
723         b = self.get_maybe_exist_named_child ('actual-notes')
724         a = self.get_maybe_exist_named_child ('normal-notes')
725         return (int(a.get_text ()), int (b.get_text ()))
726
727 class Accidental (Music_xml_node):
728     def __init__ (self):
729         Music_xml_node.__init__ (self)
730         self.editorial = False
731         self.cautionary = False
732
733 class Music_xml_spanner (Music_xml_node):
734     def get_type (self):
735         if hasattr (self, 'type'):
736             return self.type
737         else:
738             return 0
739     def get_size (self):
740         if hasattr (self, 'size'):
741             return string.atoi (self.size)
742         else:
743             return 0
744
745 class Wedge (Music_xml_spanner):
746     pass
747
748 class Tuplet (Music_xml_spanner):
749     pass
750
751 class Slur (Music_xml_spanner):
752     def get_type (self):
753         return self.type
754
755 class Beam (Music_xml_spanner):
756     def get_type (self):
757         return self.get_text ()
758     def is_primary (self):
759         return self.number == "1"
760
761 class Wavy_line (Music_xml_spanner):
762     pass
763     
764 class Pedal (Music_xml_spanner):
765     pass
766
767 class Glissando (Music_xml_spanner):
768     pass
769
770 class Octave_shift (Music_xml_spanner):
771     # default is 8 for the octave-shift!
772     def get_size (self):
773         if hasattr (self, 'size'):
774             return string.atoi (self.size)
775         else:
776             return 8
777
778 class Chord (Music_xml_node):
779     pass
780
781 class Dot (Music_xml_node):
782     pass
783
784 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
785 # for the inner <rest> element, not the whole rest block.
786 class Rest (Music_xml_node):
787     def __init__ (self):
788         Music_xml_node.__init__ (self)
789         self._is_whole_measure = False
790     def is_whole_measure (self):
791         return self._is_whole_measure
792     def get_step (self):
793         ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
794         if ch:
795             step = ch.get_text ().strip ()
796             return step
797         else:
798             return None
799     def get_octave (self):
800         ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
801         if ch:
802             step = ch.get_text ().strip ()
803             return int (step)
804         else:
805             return None
806
807 class Type (Music_xml_node):
808     pass
809 class Grace (Music_xml_node):
810     pass
811 class Staff (Music_xml_node):
812     pass
813
814 class Direction (Music_xml_node):
815     pass
816 class DirType (Music_xml_node):
817     pass
818
819 class Bend (Music_xml_node):
820     def bend_alter (self):
821         alter = self.get_maybe_exist_named_child ('bend-alter')
822         if alter:
823             return alter.get_text()
824         else:
825             return 0
826
827 class Words (Music_xml_node):
828     pass
829
830 class Harmony (Music_xml_node):
831     pass
832
833 class Frame (Music_xml_node):
834     def get_frets (self):
835         return self.get_named_child_value_number ('frame-frets', 4)
836     def get_strings (self):
837         return self.get_named_child_value_number ('frame-strings', 6)
838     def get_first_fret (self):
839         return self.get_named_child_value_number ('first-fret', 1)
840 class Frame_Note (Music_xml_node):
841     def get_string (self):
842         return self.get_named_child_value_number ('string', 1)
843     def get_fret (self):
844         return self.get_named_child_value_number ('fret', 0)
845     def get_fingering (self):
846         return self.get_named_child_value_number ('fingering', -1)
847     def get_barre (self):
848         n = self.get_maybe_exist_named_child ('barre')
849         if n:
850             return getattr (n, 'type', '')
851         else:
852             return ''
853
854
855 ## need this, not all classes are instantiated
856 ## for every input file. Only add those classes, that are either directly
857 ## used by class name or extend Music_xml_node in some way!
858 class_dict = {
859         '#comment': Hash_comment,
860         '#text': Hash_text,
861         'accidental': Accidental,
862         'attributes': Attributes,
863         'barline': Barline,
864         'bar-style': BarStyle,
865         'beam' : Beam,
866         'bend' : Bend,
867         'chord': Chord,
868         'dot': Dot,
869         'direction': Direction,
870         'direction-type': DirType,
871         'duration': Duration,
872         'frame': Frame,
873         'frame-note': Frame_Note,
874         'glissando': Glissando,
875         'grace': Grace,
876         'harmony': Harmony,
877         'identification': Identification,
878         'lyric': Lyric,
879         'measure': Measure,
880         'notations': Notations,
881         'note': Note,
882         'octave-shift': Octave_shift,
883         'part': Part,
884     'part-group': Part_group,
885         'part-list': Part_list,
886         'pedal': Pedal,
887         'pitch': Pitch,
888         'rest': Rest,
889     'score-part': Score_part,
890         'slur': Slur,
891         'staff': Staff,
892         'syllabic': Syllabic,
893         'text': Text,
894         'time-modification': Time_modification,
895         'tuplet': Tuplet,
896         'type': Type,
897         'unpitched': Unpitched,
898         'wavy-line': Wavy_line,
899         'wedge': Wedge,
900         'words': Words,
901         'work': Work,
902 }
903
904 def name2class_name (name):
905     name = name.replace ('-', '_')
906     name = name.replace ('#', 'hash_')
907     name = name[0].upper() + name[1:].lower()
908
909     return str (name)
910
911 def get_class (name):
912     classname = class_dict.get (name)
913     if classname:
914         return classname
915     else:
916         class_name = name2class_name (name)
917         klass = new.classobj (class_name, (Music_xml_node,) , {})
918         class_dict[name] = klass
919         return klass
920         
921 def lxml_demarshal_node (node):
922     name = node.tag
923
924     if name is None:
925         return None
926     klass = get_class (name)
927     py_node = klass()
928     
929     py_node._original = node
930     py_node._name = name
931     py_node._data = node.text
932     py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
933     py_node._children = filter (lambda x: x, py_node._children)
934     
935     for c in py_node._children:
936         c._parent = py_node
937
938     for (k,v) in node.items ():
939         py_node.__dict__[k] = v
940         py_node._attribute_dict[k] = v
941
942     return py_node
943
944 def minidom_demarshal_node (node):
945     name = node.nodeName
946
947     klass = get_class (name)
948     py_node = klass()
949     py_node._name = name
950     py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
951     for c in py_node._children:
952         c._parent = py_node
953
954     if node.attributes:
955         for (nm, value) in node.attributes.items():
956             py_node.__dict__[nm] = value
957             py_node._attribute_dict[nm] = value
958             
959     py_node._data = None
960     if node.nodeType == node.TEXT_NODE and node.data:
961         py_node._data = node.data 
962
963     py_node._original = node
964     return py_node
965
966
967 if __name__  == '__main__':
968         import lxml.etree
969         
970         tree = lxml.etree.parse ('beethoven.xml')
971         mxl_tree = lxml_demarshal_node (tree.getroot ())
972         ks = class_dict.keys()
973         ks.sort()
974         print '\n'.join (ks)