]> git.donarmstrong.com Git - lilypond.git/blob - python/musicxml.py
Merge branch 'master' of /home/lilycvs/git/lily/
[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 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                 # figured bass has a duration, but applies to the next note
533                 # and should not change the current measure position!
534                 if isinstance (n, FiguredBass):
535                     n._divisions = factor.denominator ()
536                     continue
537
538                 if isinstance (n, Hash_text):
539                     continue
540                 dur = Rational (0)
541
542                 if n.__class__ == Attributes:
543                     n.set_attributes_from_previous (attributes_dict)
544                     n.read_self ()
545                     attributes_dict = n._dict.copy ()
546                     attributes_object = n
547                     
548                     factor = Rational (1,
549                                        int (attributes_dict.get ('divisions').get_text ()))
550
551                 
552                 if (n.get_maybe_exist_typed_child (Duration)):
553                     mxl_dur = n.get_maybe_exist_typed_child (Duration)
554                     dur = mxl_dur.get_length () * factor
555                     
556                     if n.get_name() == 'backup':
557                         dur = - dur
558                     if n.get_maybe_exist_typed_child (Grace):
559                         dur = Rational (0)
560
561                     rest = n.get_maybe_exist_typed_child (Rest)
562                     if (rest
563                         and attributes_object
564                         and attributes_object.get_measure_length () == dur):
565
566                         rest._is_whole_measure = True
567
568                 if (dur > Rational (0) 
569                     and n.get_maybe_exist_typed_child (Chord)):
570                     now = last_moment
571                     measure_position = last_measure_position
572
573                 n._when = now
574                 n._measure_position = measure_position
575                 n._duration = dur
576                 if dur > Rational (0):
577                     last_moment = now
578                     last_measure_position = measure_position
579                     now += dur
580                     measure_position += dur
581                 elif dur < Rational (0):
582                     # backup element, reset measure position
583                     now += dur
584                     measure_position += dur
585                     if measure_position < 0:
586                         # backup went beyond the measure start => reset to 0
587                         now -= measure_position
588                         measure_position = 0
589                     last_moment = now
590                     last_measure_position = measure_position
591                 if n._name == 'note':
592                     instrument = n.get_maybe_exist_named_child ('instrument')
593                     if instrument:
594                         n.instrument_name = part_list.get_instrument (instrument.id)
595
596             # Incomplete first measures are not padded, but registered as partial
597             if is_first_measure:
598                 is_first_measure = False
599                 # upbeats are marked as implicit measures
600                 if attributes_object and m.is_implicit ():
601                     length = attributes_object.get_measure_length ()
602                     measure_end = measure_start_moment + length
603                     if measure_end <> now:
604                         m.partial = now
605             previous_measure = m
606
607     # modify attributes so that only those applying to the given staff remain
608     def extract_attributes_for_staff (part, attr, staff):
609         attributes = copy.copy (attr)
610         attributes._children = copy.copy (attr._children)
611         attributes._dict = attr._dict.copy ()
612         for c in attributes._children:
613             if hasattr (c, 'number') and c.number != staff:
614                 attributes._children.remove (c)
615         return attributes
616
617     def extract_voices (part):
618         voices = {}
619         measures = part.get_typed_children (Measure)
620         elements = []
621         for m in measures:
622             if m.partial > 0:
623                 elements.append (Partial (m.partial))
624             elements.extend (m.get_all_children ())
625         # make sure we know all voices already so that dynamics, clefs, etc.
626         # can be assigned to the correct voices
627         voice_to_staff_dict = {}
628         for n in elements:
629             voice_id = n.get_maybe_exist_named_child (u'voice')
630             vid = None
631             if voice_id:
632                 vid = voice_id.get_text ()
633
634             staff_id = n.get_maybe_exist_named_child (u'staff')
635             sid = None
636             if staff_id:
637                 sid = staff_id.get_text ()
638             else:
639                 sid = "None"
640             if vid and not voices.has_key (vid):
641                 voices[vid] = Musicxml_voice()
642             if vid and sid and not n.get_maybe_exist_typed_child (Grace):
643                 if not voice_to_staff_dict.has_key (vid):
644                     voice_to_staff_dict[vid] = sid
645         # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
646         # need to assign staff-assigned objects like clefs, times, etc. to
647         # all the correct voices. This will never work entirely correct due
648         # to staff-switches, but that's the best we can do!
649         staff_to_voice_dict = {}
650         for (v,s) in voice_to_staff_dict.items ():
651             if not staff_to_voice_dict.has_key (s):
652                 staff_to_voice_dict[s] = [v]
653             else:
654                 staff_to_voice_dict[s].append (v)
655
656
657         start_attr = None
658         assign_to_next_note = []
659         id = None
660         for n in elements:
661             voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
662
663             if not (voice_id or isinstance (n, Attributes) or
664                     isinstance (n, Direction) or isinstance (n, Partial) or
665                     isinstance (n, Barline) or isinstance (n, Harmony) or
666                     isinstance (n, FiguredBass) ):
667                 continue
668
669             if isinstance (n, Attributes) and not start_attr:
670                 start_attr = n
671                 continue
672
673             if isinstance (n, Attributes):
674                 # assign these only to the voices they really belongs to!
675                 for (s, vids) in staff_to_voice_dict.items ():
676                     staff_attributes = part.extract_attributes_for_staff (n, s)
677                     for v in vids:
678                         voices[v].add_element (staff_attributes)
679                 continue
680
681             if isinstance (n, Partial) or isinstance (n, Barline):
682                 for v in voices.keys ():
683                     voices[v].add_element (n)
684                 continue
685
686             if isinstance (n, Direction):
687                 staff_id = n.get_maybe_exist_named_child (u'staff')
688                 if staff_id:
689                     staff_id = staff_id.get_text ()
690                 if staff_id:
691                     dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
692                 else:
693                     dir_voices = voices.keys ()
694                 for v in dir_voices:
695                     voices[v].add_element (n)
696                 continue
697
698             if isinstance (n, Harmony) or isinstance (n, FiguredBass):
699                 # store the harmony or figured bass element until we encounter 
700                 # the next note and assign it only to that one voice.
701                 assign_to_next_note.append (n)
702                 continue
703
704             id = voice_id.get_text ()
705             if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
706                 #Skip this note. 
707                 pass
708             else:
709                 for i in assign_to_next_note:
710                     voices[id].add_element (i)
711                 assign_to_next_note = []
712                 voices[id].add_element (n)
713
714         # Assign all remaining elements from assign_to_next_note to the voice
715         # of the previous note:
716         for i in assign_to_next_note:
717             voices[id].add_element (i)
718         assign_to_next_note = []
719
720         if start_attr:
721             for (s, vids) in staff_to_voice_dict.items ():
722                 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
723                 staff_attributes.read_self ()
724                 part._staff_attributes_dict[s] = staff_attributes
725                 for v in vids:
726                     voices[v].insert (0, staff_attributes)
727                     voices[v]._elements[0].read_self()
728
729         part._voices = voices
730
731     def get_voices (self):
732         return self._voices
733     def get_staff_attributes (self):
734         return self._staff_attributes_dict
735
736 class Notations (Music_xml_node):
737     def get_tie (self):
738         ts = self.get_named_children ('tied')
739         starts = [t for t in ts if t.type == 'start']
740         if starts:
741             return starts[0]
742         else:
743             return None
744
745     def get_tuplets (self):
746         return self.get_typed_children (Tuplet)
747
748 class Time_modification(Music_xml_node):
749     def get_fraction (self):
750         b = self.get_maybe_exist_named_child ('actual-notes')
751         a = self.get_maybe_exist_named_child ('normal-notes')
752         return (int(a.get_text ()), int (b.get_text ()))
753
754 class Accidental (Music_xml_node):
755     def __init__ (self):
756         Music_xml_node.__init__ (self)
757         self.editorial = False
758         self.cautionary = False
759
760 class Music_xml_spanner (Music_xml_node):
761     def get_type (self):
762         if hasattr (self, 'type'):
763             return self.type
764         else:
765             return 0
766     def get_size (self):
767         if hasattr (self, 'size'):
768             return string.atoi (self.size)
769         else:
770             return 0
771
772 class Wedge (Music_xml_spanner):
773     pass
774
775 class Tuplet (Music_xml_spanner):
776     pass
777
778 class Bracket (Music_xml_spanner):
779     pass
780
781 class Dashes (Music_xml_spanner):
782     pass
783
784 class Slur (Music_xml_spanner):
785     def get_type (self):
786         return self.type
787
788 class Beam (Music_xml_spanner):
789     def get_type (self):
790         return self.get_text ()
791     def is_primary (self):
792         return self.number == "1"
793
794 class Wavy_line (Music_xml_spanner):
795     pass
796     
797 class Pedal (Music_xml_spanner):
798     pass
799
800 class Glissando (Music_xml_spanner):
801     pass
802
803 class Slide (Music_xml_spanner):
804     pass
805
806 class Octave_shift (Music_xml_spanner):
807     # default is 8 for the octave-shift!
808     def get_size (self):
809         if hasattr (self, 'size'):
810             return string.atoi (self.size)
811         else:
812             return 8
813
814 class Chord (Music_xml_node):
815     pass
816
817 class Dot (Music_xml_node):
818     pass
819
820 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
821 # for the inner <rest> element, not the whole rest block.
822 class Rest (Music_xml_node):
823     def __init__ (self):
824         Music_xml_node.__init__ (self)
825         self._is_whole_measure = False
826     def is_whole_measure (self):
827         return self._is_whole_measure
828     def get_step (self):
829         ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
830         if ch:
831             step = ch.get_text ().strip ()
832             return step
833         else:
834             return None
835     def get_octave (self):
836         ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
837         if ch:
838             step = ch.get_text ().strip ()
839             return int (step)
840         else:
841             return None
842
843 class Type (Music_xml_node):
844     pass
845 class Grace (Music_xml_node):
846     pass
847 class Staff (Music_xml_node):
848     pass
849
850 class Direction (Music_xml_node):
851     pass
852 class DirType (Music_xml_node):
853     pass
854
855 class Bend (Music_xml_node):
856     def bend_alter (self):
857         alter = self.get_maybe_exist_named_child ('bend-alter')
858         if alter:
859             return alter.get_text()
860         else:
861             return 0
862
863 class Words (Music_xml_node):
864     pass
865
866 class Harmony (Music_xml_node):
867     pass
868
869 class Frame (Music_xml_node):
870     def get_frets (self):
871         return self.get_named_child_value_number ('frame-frets', 4)
872     def get_strings (self):
873         return self.get_named_child_value_number ('frame-strings', 6)
874     def get_first_fret (self):
875         return self.get_named_child_value_number ('first-fret', 1)
876 class Frame_Note (Music_xml_node):
877     def get_string (self):
878         return self.get_named_child_value_number ('string', 1)
879     def get_fret (self):
880         return self.get_named_child_value_number ('fret', 0)
881     def get_fingering (self):
882         return self.get_named_child_value_number ('fingering', -1)
883     def get_barre (self):
884         n = self.get_maybe_exist_named_child ('barre')
885         if n:
886             return getattr (n, 'type', '')
887         else:
888             return ''
889
890 class FiguredBass (Music_xml_node):
891     pass
892
893
894
895 ## need this, not all classes are instantiated
896 ## for every input file. Only add those classes, that are either directly
897 ## used by class name or extend Music_xml_node in some way!
898 class_dict = {
899         '#comment': Hash_comment,
900         '#text': Hash_text,
901         'accidental': Accidental,
902         'attributes': Attributes,
903         'barline': Barline,
904         'bar-style': BarStyle,
905         'beam' : Beam,
906         'bend' : Bend,
907         'bracket' : Bracket,
908         'chord': Chord,
909         'dashes' : Dashes,
910         'dot': Dot,
911         'direction': Direction,
912         'direction-type': DirType,
913         'duration': Duration,
914         'frame': Frame,
915         'frame-note': Frame_Note,
916         'figured-bass': FiguredBass,
917         'glissando': Glissando,
918         'grace': Grace,
919         'harmony': Harmony,
920         'identification': Identification,
921         'lyric': Lyric,
922         'measure': Measure,
923         'notations': Notations,
924         'note': Note,
925         'octave-shift': Octave_shift,
926         'part': Part,
927     'part-group': Part_group,
928         'part-list': Part_list,
929         'pedal': Pedal,
930         'pitch': Pitch,
931         'rest': Rest,
932     'score-part': Score_part,
933         'slide': Slide,
934         'slur': Slur,
935         'staff': Staff,
936         'syllabic': Syllabic,
937         'text': Text,
938         'time-modification': Time_modification,
939         'tuplet': Tuplet,
940         'type': Type,
941         'unpitched': Unpitched,
942         'wavy-line': Wavy_line,
943         'wedge': Wedge,
944         'words': Words,
945         'work': Work,
946 }
947
948 def name2class_name (name):
949     name = name.replace ('-', '_')
950     name = name.replace ('#', 'hash_')
951     name = name[0].upper() + name[1:].lower()
952
953     return str (name)
954
955 def get_class (name):
956     classname = class_dict.get (name)
957     if classname:
958         return classname
959     else:
960         class_name = name2class_name (name)
961         klass = new.classobj (class_name, (Music_xml_node,) , {})
962         class_dict[name] = klass
963         return klass
964         
965 def lxml_demarshal_node (node):
966     name = node.tag
967
968     # Ignore comment nodes, which are also returned by the etree parser!
969     if name is None or node.__class__.__name__ == "_Comment":
970         return None
971     klass = get_class (name)
972     py_node = klass()
973     
974     py_node._original = node
975     py_node._name = name
976     py_node._data = node.text
977     py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
978     py_node._children = filter (lambda x: x, py_node._children)
979     
980     for c in py_node._children:
981         c._parent = py_node
982
983     for (k,v) in node.items ():
984         py_node.__dict__[k] = v
985         py_node._attribute_dict[k] = v
986
987     return py_node
988
989 def minidom_demarshal_node (node):
990     name = node.nodeName
991
992     klass = get_class (name)
993     py_node = klass()
994     py_node._name = name
995     py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
996     for c in py_node._children:
997         c._parent = py_node
998
999     if node.attributes:
1000         for (nm, value) in node.attributes.items():
1001             py_node.__dict__[nm] = value
1002             py_node._attribute_dict[nm] = value
1003             
1004     py_node._data = None
1005     if node.nodeType == node.TEXT_NODE and node.data:
1006         py_node._data = node.data 
1007
1008     py_node._original = node
1009     return py_node
1010
1011
1012 if __name__  == '__main__':
1013         import lxml.etree
1014         
1015         tree = lxml.etree.parse ('beethoven.xml')
1016         mxl_tree = lxml_demarshal_node (tree.getroot ())
1017         ks = class_dict.keys()
1018         ks.sort()
1019         print '\n'.join (ks)