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