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