]> git.donarmstrong.com Git - lilypond.git/blob - python/musicxml.py
Merge branch 'master' of git://git.sv.gnu.org/lilypond
[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 is 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         elif self.get_maybe_exist_named_child (u'grace'):
328             # FIXME: is it ok to default to eight note for grace notes?
329             return 3
330         else:
331             self.message (_ ("Encountered note at %s with %s duration (no <type> element):") % (self.start, self.duration) )
332             return 0
333
334     def get_factor (self):
335         return 1
336
337     def get_pitches (self):
338         return self.get_typed_children (get_class (u'pitch'))
339
340 class Part_list (Music_xml_node):
341     def __init__ (self):
342         Music_xml_node.__init__ (self)
343         self._id_instrument_name_dict = {}
344         
345     def generate_id_instrument_dict (self):
346
347         ## not empty to make sure this happens only once.
348         mapping = {1: 1}
349         for score_part in self.get_named_children ('score-part'):
350             for instr in score_part.get_named_children ('score-instrument'):
351                 id = instr.id
352                 name = instr.get_named_child ("instrument-name")
353                 mapping[id] = name.get_text ()
354
355         self._id_instrument_name_dict = mapping
356
357     def get_instrument (self, id):
358         if not self._id_instrument_name_dict:
359             self.generate_id_instrument_dict()
360
361         instrument_name = self._id_instrument_name_dict.get (id)
362         if instrument_name:
363             return instrument_name
364         else:
365             sys.stderr.write (_ ("Unable to find find instrument for ID=%s\n") % id)
366             return "Grand Piano"
367
368 class Part_group (Music_xml_node):
369     pass
370 class Score_part (Music_xml_node):
371     pass
372         
373 class Measure (Music_xml_node):
374     def __init__ (self):
375         Music_xml_node.__init__ (self)
376         self.partial = 0
377     def is_implicit (self):
378         return hasattr (self, 'implicit') and self.implicit == 'yes'
379     def get_notes (self):
380         return self.get_typed_children (get_class (u'note'))
381
382 class Syllabic (Music_xml_node):
383     def continued (self):
384         text = self.get_text()
385         return (text == "begin") or (text == "middle")
386 class Text (Music_xml_node):
387     pass
388
389 class Lyric (Music_xml_node):
390     def get_number (self):
391         if hasattr (self, 'number'):
392             return self.number
393         else:
394             return -1
395
396     def lyric_to_text (self):
397         continued = False
398         syllabic = self.get_maybe_exist_typed_child (Syllabic)
399         if syllabic:
400             continued = syllabic.continued ()
401         text = self.get_maybe_exist_typed_child (Text)
402         
403         if text:
404             text = text.get_text()
405             # We need to convert soft hyphens to -, otherwise the ascii codec as well
406             # as lilypond will barf on that character
407             text = string.replace( text, u'\xad', '-' )
408         
409         if text == "-" and continued:
410             return "--"
411         elif text == "_" and continued:
412             return "__"
413         elif continued and text:
414             return escape_ly_output_string (text) + " --"
415         elif continued:
416             return "--"
417         elif text:
418             return escape_ly_output_string (text)
419         else:
420             return ""
421
422 class Musicxml_voice:
423     def __init__ (self):
424         self._elements = []
425         self._staves = {}
426         self._start_staff = None
427         self._lyrics = []
428         self._has_lyrics = False
429
430     def add_element (self, e):
431         self._elements.append (e)
432         if (isinstance (e, Note)
433             and e.get_maybe_exist_typed_child (Staff)):
434             name = e.get_maybe_exist_typed_child (Staff).get_text ()
435
436             if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
437                 self._start_staff = name
438             self._staves[name] = True
439
440         lyrics = e.get_typed_children (Lyric)
441         if not self._has_lyrics:
442           self.has_lyrics = len (lyrics) > 0
443
444         for l in lyrics:
445             nr = l.get_number()
446             if (nr > 0) and not (nr in self._lyrics):
447                 self._lyrics.append (nr)
448
449     def insert (self, idx, e):
450         self._elements.insert (idx, e)
451
452     def get_lyrics_numbers (self):
453         if (len (self._lyrics) == 0) and self._has_lyrics:
454             #only happens if none of the <lyric> tags has a number attribute
455             return [1]
456         else:
457             return self._lyrics
458
459
460 class Part (Music_xml_node):
461     def __init__ (self):
462         Music_xml_node.__init__ (self)
463         self._voices = {}
464         self._staff_attributes_dict = {}
465
466     def get_part_list (self):
467         n = self
468         while n and n.get_name() != 'score-partwise':
469             n = n._parent
470
471         return n.get_named_child ('part-list')
472         
473     def interpret (self):
474         """Set durations and starting points."""
475         """The starting point of the very first note is 0!"""
476         
477         part_list = self.get_part_list ()
478         
479         now = Rational (0)
480         factor = Rational (1)
481         attributes_dict = {}
482         attributes_object = None
483         measures = self.get_typed_children (Measure)
484         last_moment = Rational (-1)
485         last_measure_position = Rational (-1)
486         measure_position = Rational (0)
487         measure_start_moment = now
488         is_first_measure = True
489         previous_measure = None
490         for m in measures:
491             # implicit measures are used for artificial measures, e.g. when
492             # a repeat bar line splits a bar into two halves. In this case,
493             # don't reset the measure position to 0. They are also used for
494             # upbeats (initial value of 0 fits these, too).
495             # Also, don't reset the measure position at the end of the loop,
496             # but rather when starting the next measure (since only then do we
497             # know if the next measure is implicit and continues that measure)
498             if not m.is_implicit ():
499                 # Warn about possibly overfull measures and reset the position
500                 if attributes_object and previous_measure and previous_measure.partial == 0:
501                     length = attributes_object.get_measure_length ()
502                     new_now = measure_start_moment + length
503                     if now <> new_now:
504                         problem = 'incomplete'
505                         if now > new_now:
506                             problem = 'overfull'
507                         ## only for verbose operation.
508                         if problem <> 'incomplete' and previous_measure:
509                             previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
510                     now = new_now
511                 measure_start_moment = now
512                 measure_position = Rational (0)
513
514             for n in m.get_all_children ():
515                 if isinstance (n, Hash_text):
516                     continue
517                 dur = Rational (0)
518
519                 if n.__class__ == Attributes:
520                     n.set_attributes_from_previous (attributes_dict)
521                     n.read_self ()
522                     attributes_dict = n._dict.copy ()
523                     attributes_object = n
524                     
525                     factor = Rational (1,
526                                        int (attributes_dict.get ('divisions').get_text ()))
527
528                 
529                 if (n.get_maybe_exist_typed_child (Duration)):
530                     mxl_dur = n.get_maybe_exist_typed_child (Duration)
531                     dur = mxl_dur.get_length () * factor
532                     
533                     if n.get_name() == 'backup':
534                         dur = - dur
535                     if n.get_maybe_exist_typed_child (Grace):
536                         dur = Rational (0)
537
538                     rest = n.get_maybe_exist_typed_child (Rest)
539                     if (rest
540                         and attributes_object
541                         and attributes_object.get_measure_length () == dur):
542
543                         rest._is_whole_measure = True
544
545                 if (dur > Rational (0) 
546                     and n.get_maybe_exist_typed_child (Chord)):
547                     now = last_moment
548                     measure_position = last_measure_position
549
550                 n._when = now
551                 n._measure_position = measure_position
552                 n._duration = dur
553                 if dur > Rational (0):
554                     last_moment = now
555                     last_measure_position = measure_position
556                     now += dur
557                     measure_position += dur
558                 elif dur < Rational (0):
559                     # backup element, reset measure position
560                     now += dur
561                     measure_position += dur
562                     if measure_position < 0:
563                         # backup went beyond the measure start => reset to 0
564                         now -= measure_position
565                         measure_position = 0
566                     last_moment = now
567                     last_measure_position = measure_position
568                 if n._name == 'note':
569                     instrument = n.get_maybe_exist_named_child ('instrument')
570                     if instrument:
571                         n.instrument_name = part_list.get_instrument (instrument.id)
572
573             # Incomplete first measures are not padded, but registered as partial
574             if is_first_measure:
575                 is_first_measure = False
576                 # upbeats are marked as implicit measures
577                 if attributes_object and m.is_implicit ():
578                     length = attributes_object.get_measure_length ()
579                     measure_end = measure_start_moment + length
580                     if measure_end <> now:
581                         m.partial = now
582             previous_measure = m
583
584     # modify attributes so that only those applying to the given staff remain
585     def extract_attributes_for_staff (part, attr, staff):
586         attributes = copy.copy (attr)
587         attributes._children = copy.copy (attr._children)
588         attributes._dict = attr._dict.copy ()
589         for c in attributes._children:
590             if hasattr (c, 'number') and c.number != staff:
591                 attributes._children.remove (c)
592         return attributes
593
594     def extract_voices (part):
595         voices = {}
596         measures = part.get_typed_children (Measure)
597         elements = []
598         for m in measures:
599             if m.partial > 0:
600                 elements.append (Partial (m.partial))
601             elements.extend (m.get_all_children ())
602         # make sure we know all voices already so that dynamics, clefs, etc.
603         # can be assigned to the correct voices
604         voice_to_staff_dict = {}
605         for n in elements:
606             voice_id = n.get_maybe_exist_named_child (u'voice')
607             vid = None
608             if voice_id:
609                 vid = voice_id.get_text ()
610
611             staff_id = n.get_maybe_exist_named_child (u'staff')
612             sid = None
613             if staff_id:
614                 sid = staff_id.get_text ()
615             else:
616                 sid = "None"
617             if vid and not voices.has_key (vid):
618                 voices[vid] = Musicxml_voice()
619             if vid and sid and not n.get_maybe_exist_typed_child (Grace):
620                 if not voice_to_staff_dict.has_key (vid):
621                     voice_to_staff_dict[vid] = sid
622         # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
623         # need to assign staff-assigned objects like clefs, times, etc. to
624         # all the correct voices. This will never work entirely correct due
625         # to staff-switches, but that's the best we can do!
626         staff_to_voice_dict = {}
627         for (v,s) in voice_to_staff_dict.items ():
628             if not staff_to_voice_dict.has_key (s):
629                 staff_to_voice_dict[s] = [v]
630             else:
631                 staff_to_voice_dict[s].append (v)
632
633
634         start_attr = None
635         assign_to_next_note = []
636         id = None
637         for n in elements:
638             voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
639
640             if not (voice_id or isinstance (n, Attributes) or
641                     isinstance (n, Direction) or isinstance (n, Partial) or
642                     isinstance (n, Barline) or isinstance (n, Harmony) ):
643                 continue
644
645             if isinstance (n, Attributes) and not start_attr:
646                 start_attr = n
647                 continue
648
649             if isinstance (n, Attributes):
650                 # assign these only to the voices they really belongs to!
651                 for (s, vids) in staff_to_voice_dict.items ():
652                     staff_attributes = part.extract_attributes_for_staff (n, s)
653                     for v in vids:
654                         voices[v].add_element (staff_attributes)
655                 continue
656
657             if isinstance (n, Partial) or isinstance (n, Barline):
658                 for v in voices.keys ():
659                     voices[v].add_element (n)
660                 continue
661
662             if isinstance (n, Direction):
663                 staff_id = n.get_maybe_exist_named_child (u'staff')
664                 if staff_id:
665                     staff_id = staff_id.get_text ()
666                 if staff_id:
667                     dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
668                 else:
669                     dir_voices = voices.keys ()
670                 for v in dir_voices:
671                     voices[v].add_element (n)
672                 continue
673
674             if isinstance (n, Harmony):
675                 # store the harmony element until we encounter the next note
676                 # and assign it only to that one voice.
677                 assign_to_next_note.append (n)
678                 continue
679
680             id = voice_id.get_text ()
681             if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
682                 #Skip this note. 
683                 pass
684             else:
685                 for i in assign_to_next_note:
686                     voices[id].add_element (i)
687                 assign_to_next_note = []
688                 voices[id].add_element (n)
689
690         # Assign all remaining elements from assign_to_next_note to the voice
691         # of the previous note:
692         for i in assign_to_next_note:
693             voices[id].add_element (i)
694         assign_to_next_note = []
695
696         if start_attr:
697             for (s, vids) in staff_to_voice_dict.items ():
698                 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
699                 staff_attributes.read_self ()
700                 part._staff_attributes_dict[s] = staff_attributes
701                 for v in vids:
702                     voices[v].insert (0, staff_attributes)
703                     voices[v]._elements[0].read_self()
704
705         part._voices = voices
706
707     def get_voices (self):
708         return self._voices
709     def get_staff_attributes (self):
710         return self._staff_attributes_dict
711
712 class Notations (Music_xml_node):
713     def get_tie (self):
714         ts = self.get_named_children ('tied')
715         starts = [t for t in ts if t.type == 'start']
716         if starts:
717             return starts[0]
718         else:
719             return None
720
721     def get_tuplets (self):
722         return self.get_typed_children (Tuplet)
723
724 class Time_modification(Music_xml_node):
725     def get_fraction (self):
726         b = self.get_maybe_exist_named_child ('actual-notes')
727         a = self.get_maybe_exist_named_child ('normal-notes')
728         return (int(a.get_text ()), int (b.get_text ()))
729
730 class Accidental (Music_xml_node):
731     def __init__ (self):
732         Music_xml_node.__init__ (self)
733         self.editorial = False
734         self.cautionary = False
735
736 class Music_xml_spanner (Music_xml_node):
737     def get_type (self):
738         if hasattr (self, 'type'):
739             return self.type
740         else:
741             return 0
742     def get_size (self):
743         if hasattr (self, 'size'):
744             return string.atoi (self.size)
745         else:
746             return 0
747
748 class Wedge (Music_xml_spanner):
749     pass
750
751 class Tuplet (Music_xml_spanner):
752     pass
753
754 class Bracket (Music_xml_spanner):
755     pass
756
757 class Dashes (Music_xml_spanner):
758     pass
759
760 class Slur (Music_xml_spanner):
761     def get_type (self):
762         return self.type
763
764 class Beam (Music_xml_spanner):
765     def get_type (self):
766         return self.get_text ()
767     def is_primary (self):
768         return self.number == "1"
769
770 class Wavy_line (Music_xml_spanner):
771     pass
772     
773 class Pedal (Music_xml_spanner):
774     pass
775
776 class Glissando (Music_xml_spanner):
777     pass
778
779 class Octave_shift (Music_xml_spanner):
780     # default is 8 for the octave-shift!
781     def get_size (self):
782         if hasattr (self, 'size'):
783             return string.atoi (self.size)
784         else:
785             return 8
786
787 class Chord (Music_xml_node):
788     pass
789
790 class Dot (Music_xml_node):
791     pass
792
793 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
794 # for the inner <rest> element, not the whole rest block.
795 class Rest (Music_xml_node):
796     def __init__ (self):
797         Music_xml_node.__init__ (self)
798         self._is_whole_measure = False
799     def is_whole_measure (self):
800         return self._is_whole_measure
801     def get_step (self):
802         ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
803         if ch:
804             step = ch.get_text ().strip ()
805             return step
806         else:
807             return None
808     def get_octave (self):
809         ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
810         if ch:
811             step = ch.get_text ().strip ()
812             return int (step)
813         else:
814             return None
815
816 class Type (Music_xml_node):
817     pass
818 class Grace (Music_xml_node):
819     pass
820 class Staff (Music_xml_node):
821     pass
822
823 class Direction (Music_xml_node):
824     pass
825 class DirType (Music_xml_node):
826     pass
827
828 class Bend (Music_xml_node):
829     def bend_alter (self):
830         alter = self.get_maybe_exist_named_child ('bend-alter')
831         if alter:
832             return alter.get_text()
833         else:
834             return 0
835
836 class Words (Music_xml_node):
837     pass
838
839 class Harmony (Music_xml_node):
840     pass
841
842 class Frame (Music_xml_node):
843     def get_frets (self):
844         return self.get_named_child_value_number ('frame-frets', 4)
845     def get_strings (self):
846         return self.get_named_child_value_number ('frame-strings', 6)
847     def get_first_fret (self):
848         return self.get_named_child_value_number ('first-fret', 1)
849 class Frame_Note (Music_xml_node):
850     def get_string (self):
851         return self.get_named_child_value_number ('string', 1)
852     def get_fret (self):
853         return self.get_named_child_value_number ('fret', 0)
854     def get_fingering (self):
855         return self.get_named_child_value_number ('fingering', -1)
856     def get_barre (self):
857         n = self.get_maybe_exist_named_child ('barre')
858         if n:
859             return getattr (n, 'type', '')
860         else:
861             return ''
862
863
864 ## need this, not all classes are instantiated
865 ## for every input file. Only add those classes, that are either directly
866 ## used by class name or extend Music_xml_node in some way!
867 class_dict = {
868         '#comment': Hash_comment,
869         '#text': Hash_text,
870         'accidental': Accidental,
871         'attributes': Attributes,
872         'barline': Barline,
873         'bar-style': BarStyle,
874         'beam' : Beam,
875         'bend' : Bend,
876         'bracket' : Bracket,
877         'chord': Chord,
878         'dashes' : Dashes,
879         'dot': Dot,
880         'direction': Direction,
881         'direction-type': DirType,
882         'duration': Duration,
883         'frame': Frame,
884         'frame-note': Frame_Note,
885         'glissando': Glissando,
886         'grace': Grace,
887         'harmony': Harmony,
888         'identification': Identification,
889         'lyric': Lyric,
890         'measure': Measure,
891         'notations': Notations,
892         'note': Note,
893         'octave-shift': Octave_shift,
894         'part': Part,
895     'part-group': Part_group,
896         'part-list': Part_list,
897         'pedal': Pedal,
898         'pitch': Pitch,
899         'rest': Rest,
900     'score-part': Score_part,
901         'slur': Slur,
902         'staff': Staff,
903         'syllabic': Syllabic,
904         'text': Text,
905         'time-modification': Time_modification,
906         'tuplet': Tuplet,
907         'type': Type,
908         'unpitched': Unpitched,
909         'wavy-line': Wavy_line,
910         'wedge': Wedge,
911         'words': Words,
912         'work': Work,
913 }
914
915 def name2class_name (name):
916     name = name.replace ('-', '_')
917     name = name.replace ('#', 'hash_')
918     name = name[0].upper() + name[1:].lower()
919
920     return str (name)
921
922 def get_class (name):
923     classname = class_dict.get (name)
924     if classname:
925         return classname
926     else:
927         class_name = name2class_name (name)
928         klass = new.classobj (class_name, (Music_xml_node,) , {})
929         class_dict[name] = klass
930         return klass
931         
932 def lxml_demarshal_node (node):
933     name = node.tag
934
935     if name is None:
936         return None
937     klass = get_class (name)
938     py_node = klass()
939     
940     py_node._original = node
941     py_node._name = name
942     py_node._data = node.text
943     py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
944     py_node._children = filter (lambda x: x, py_node._children)
945     
946     for c in py_node._children:
947         c._parent = py_node
948
949     for (k,v) in node.items ():
950         py_node.__dict__[k] = v
951         py_node._attribute_dict[k] = v
952
953     return py_node
954
955 def minidom_demarshal_node (node):
956     name = node.nodeName
957
958     klass = get_class (name)
959     py_node = klass()
960     py_node._name = name
961     py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
962     for c in py_node._children:
963         c._parent = py_node
964
965     if node.attributes:
966         for (nm, value) in node.attributes.items():
967             py_node.__dict__[nm] = value
968             py_node._attribute_dict[nm] = value
969             
970     py_node._data = None
971     if node.nodeType == node.TEXT_NODE and node.data:
972         py_node._data = node.data 
973
974     py_node._original = node
975     return py_node
976
977
978 if __name__  == '__main__':
979         import lxml.etree
980         
981         tree = lxml.etree.parse ('beethoven.xml')
982         mxl_tree = lxml_demarshal_node (tree.getroot ())
983         ks = class_dict.keys()
984         ks.sort()
985         print '\n'.join (ks)