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