]> git.donarmstrong.com Git - lilypond.git/blob - python/musicxml.py
* python/musicxml.py (Xml_node.__init__): _attribute_dict stores
[lilypond.git] / python / musicxml.py
1 import new
2 from rational import *
3
4 class Xml_node:
5     def __init__ (self):
6         self._children = []
7         self._data = None
8         self._original = None
9         self._name = 'xml_node'
10         self._parent = None
11         self._attribute_dict = {}
12         
13     def get_parent (self):
14         return self._parent
15     
16     def is_first (self):
17         return self._parent.get_typed_children (self.__class__)[0] == self
18
19     def original (self):
20         return self._original 
21     def get_name (self):
22         return self._name
23
24     def get_text (self):
25         if self._data:
26             return self._data
27
28         if not self._children:
29             return ''
30
31         return ''.join ([c.get_text () for c in self._children])
32
33     def message (self, msg):
34         print msg
35
36         p = self
37         while p:
38             print '  In: <%s %s>' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()]))
39             p = p.get_parent ()
40         
41     def get_typed_children (self, klass):
42         return [c for c in self._children if isinstance(c, klass)]
43
44     def get_named_children (self, nm):
45         return self.get_typed_children (class_dict[nm])
46
47     def get_named_child (self, nm):
48         return self.get_maybe_exist_named_child (nm)
49
50     def get_children (self, predicate):
51         return [c for c in self._children if predicate(c)]
52
53     def get_all_children (self):
54         return self._children
55
56     def get_maybe_exist_named_child (self, name):
57         return self.get_maybe_exist_typed_child (class_dict[name])
58
59     def get_maybe_exist_typed_child (self, klass):
60         cn = self.get_typed_children (klass)
61         if len (cn)==0:
62             return None
63         elif len (cn) == 1:
64             return cn[0]
65         else:
66             raise "More than 1 child", klass
67
68     def get_unique_typed_child (self, klass):
69         cn = self.get_typed_children(klass)
70         if len (cn) <> 1:
71             print self.__dict__ 
72             raise 'Child is not unique for', (klass, 'found', cn)
73
74         return cn[0]
75
76 class Music_xml_node (Xml_node):
77     def __init__ (self):
78         Xml_node.__init__ (self)
79         self.duration = Rational (0)
80         self.start = Rational (0)
81
82
83 class Duration (Music_xml_node):
84     def get_length (self):
85         dur = int (self.get_text ()) * Rational (1,4)
86         return dur
87
88 class Hash_comment (Music_xml_node):
89     pass
90
91 class Pitch (Music_xml_node):
92     def get_step (self):
93         ch = self.get_unique_typed_child (class_dict[u'step'])
94         step = ch.get_text ().strip ()
95         return step
96     def get_octave (self):
97         ch = self.get_unique_typed_child (class_dict[u'octave'])
98
99         step = ch.get_text ().strip ()
100         return int (step)
101
102     def get_alteration (self):
103         ch = self.get_maybe_exist_typed_child (class_dict[u'alter'])
104         alter = 0
105         if ch:
106             alter = int (ch.get_text ().strip ())
107         return alter
108
109 class Measure_element (Music_xml_node):
110     def get_voice_id (self):
111         voice_id = self.get_maybe_exist_named_child ('voice')
112         if voice_id:
113             return voice_id.get_text ()
114         else:
115             return None
116
117     def is_first (self):
118         cn = self._parent.get_typed_children (self.__class__)
119         cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
120         return cn[0] == self
121
122 class Attributes (Measure_element):
123     def __init__ (self):
124         Measure_element.__init__ (self)
125         self._dict = {}
126
127     def set_attributes_from_previous (self, dict):
128         self._dict.update (dict)
129         
130     def read_self (self):
131         for c in self.get_all_children ():
132             self._dict[c.get_name()] = c
133
134     def get_named_attribute (self, name):
135         return self._dict[name]
136
137     def get_measure_length (self):
138         (n,d) = self.get_time_signature ()
139         return Rational (n,d)
140         
141     def get_time_signature (self):
142         "return time sig as a (beat, beat-type) tuple"
143
144         try:
145             mxl = self.get_named_attribute ('time')
146             
147             beats = mxl.get_maybe_exist_named_child ('beats')
148             type = mxl.get_maybe_exist_named_child ('beat-type')
149             return (int (beats.get_text ()),
150                     int (type.get_text ()))
151         except KeyError:
152             print 'error: requested time signature, but time sig unknown'
153             return (4, 4)
154
155     def get_clef_sign (self):
156         mxl = self.get_named_attribute ('clef')
157         sign = mxl.get_maybe_exist_named_child ('sign')
158         if sign:
159             return sign.get_text ()
160         else:
161             print 'clef requested, but unknow'
162             return 'G'
163
164     def get_key_signature (self):
165         "return (fifths, mode) tuple"
166
167         key = self.get_named_attribute ('key')
168         mode_node = self.get_maybe_exist_named_child ('mode')
169         mode = 'major'
170         if mode_node:
171             mode = mode_node.get_text ()
172
173         fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
174         return (fifths, mode)
175                 
176
177 class Note (Measure_element):
178     def __init__ (self):
179         Measure_element.__init__ (self)
180         self.instrument_name = ''
181         
182     def get_duration_log (self):
183         ch = self.get_maybe_exist_typed_child (class_dict[u'type'])
184
185         if ch:
186             log = ch.get_text ().strip()
187             return {'eighth': 3,
188                     'quarter': 2,
189                     'half': 1,
190                     '16th': 4,
191                     '32nd': 5,
192                      'breve': -1,
193                     'long': -2,
194                     'whole': 0} [log]
195         else:
196             return 0
197
198     def get_factor (self):
199         return 1
200
201     def get_pitches (self):
202         return self.get_typed_children (class_dict[u'pitch'])
203
204 class Part_list (Music_xml_node):
205     def __init__ (self):
206         Music_xml_node.__init__ (self)
207         self._id_instrument_name_dict = {}
208         
209     def generate_id_instrument_dict (self):
210
211         ## not empty to make sure this happens only once.
212         mapping = {1: 1}
213         for score_part in self.get_named_children ('score-part'):
214             for instr in score_part.get_named_children ('score-instrument'):
215                 id = instr.id
216                 name = instr.get_named_child ("instrument-name")
217                 mapping[id] = name.get_text ()
218
219         self._id_instrument_name_dict = mapping
220
221     def get_instrument (self, id):
222         if not self._id_instrument_name_dict:
223             self.generate_id_instrument_dict()
224
225         try:
226             return self._id_instrument_name_dict[id]
227         except KeyError:
228             print "Opps, couldn't find instrument for ID=", id
229             return "Grand Piano"
230         
231 class Measure(Music_xml_node):
232     def get_notes (self):
233         return self.get_typed_children (class_dict[u'note'])
234
235     
236 class Musicxml_voice:
237     def __init__ (self):
238         self._elements = []
239         self._staves = {}
240         self._start_staff = None
241
242     def add_element (self, e):
243         self._elements.append (e)
244         if (isinstance (e, Note)
245             and e.get_maybe_exist_typed_child (Staff)):
246             name = e.get_maybe_exist_typed_child (Staff).get_text ()
247
248             if not self._start_staff:
249                 self._start_staff = name
250             self._staves[name] = True
251
252     def insert (self, idx, e):
253         self._elements.insert (idx, e)
254
255
256
257 class Part (Music_xml_node):
258     def __init__ (self):
259         Music_xml_node.__init__ (self)
260         self._voices = []
261
262     def get_part_list (self):
263         n = self
264         while n and n.get_name() != 'score-partwise':
265             n = n._parent
266
267         return n.get_named_child ('part-list')
268         
269     def interpret (self):
270         """Set durations and starting points."""
271         
272         part_list = self.get_part_list ()
273         
274         now = Rational (0)
275         factor = Rational (1)
276         attributes_dict = {}
277         attributes_object = None
278         measures = self.get_typed_children (Measure)
279         
280         for m in measures:
281             measure_start_moment = now
282             measure_position = Rational (0)
283             for n in m.get_all_children ():
284                 dur = Rational (0)
285
286                 if n.__class__ == Attributes:
287                     n.set_attributes_from_previous (attributes_dict)
288                     n.read_self ()
289                     attributes_dict = n._dict.copy ()
290                     attributes_object = n
291                     
292                     factor = Rational (1,
293                                        int (attributes_dict['divisions'].get_text ()))
294                 elif (n.get_maybe_exist_typed_child (Duration)
295                       and not n.get_maybe_exist_typed_child (Chord)):
296                     
297                     mxl_dur = n.get_maybe_exist_typed_child (Duration)
298                     dur = mxl_dur.get_length () * factor
299                     
300                     if n.get_name() == 'backup':
301                         dur = - dur
302                     if n.get_maybe_exist_typed_child (Grace):
303                         dur = Rational (0)
304
305                     rest = n.get_maybe_exist_typed_child (Rest)
306                     if (rest
307                         and attributes_object
308                         and attributes_object.get_measure_length () == dur):
309
310                         rest._is_whole_measure = True
311                         
312
313                 n._when = now
314                 n._measure_position = measure_position
315                 n._duration = dur
316                 now += dur
317                 measure_position += dur
318                 if n._name == 'note':
319                     instrument = n.get_maybe_exist_named_child ('instrument')
320                     if instrument:
321                         n.instrument_name = part_list.get_instrument (instrument.id)
322
323             if attributes_object:
324                 length = attributes_object.get_measure_length ()
325                 new_now = measure_start_moment + length
326                 
327                 if now <> new_now:
328                     problem = 'incomplete'
329                     if now > new_now:
330                         problem = 'overfull'
331                         
332                     m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
333
334                 now = new_now
335
336     def extract_voices (part):
337         voices = {}
338         measures = part.get_typed_children (Measure)
339         elements = []
340         for m in measures:
341             elements.extend (m.get_all_children ())
342
343         start_attr = None
344         for n in elements:
345             voice_id = n.get_maybe_exist_typed_child (class_dict['voice'])
346
347             if not (voice_id or isinstance (n, Attributes)):
348                 continue
349
350             if isinstance (n, Attributes) and not start_attr:
351                 start_attr = n
352                 continue
353
354             if isinstance (n, Attributes):
355                 for v in voices.values ():
356                     v.add_element (n)
357                 continue
358
359             id = voice_id.get_text ()
360             if not voices.has_key (id):
361                 voices[id] = Musicxml_voice()
362
363             voices[id].add_element (n)
364
365         if start_attr:
366             for (k,v) in voices.items ():
367                 v.insert (0, start_attr)
368
369         part._voices = voices
370
371     def get_voices (self):
372         return self._voices
373
374 class Notations (Music_xml_node):
375     def get_tie (self):
376         ts = self.get_named_children ('tied')
377         starts = [t for t in ts if t.type == 'start']
378         if starts:
379             return starts[0]
380         else:
381             return None
382
383     def get_tuplet (self):
384         return self.get_maybe_exist_typed_child (Tuplet)
385
386 class Time_modification(Music_xml_node):
387     def get_fraction (self):
388         b = self.get_maybe_exist_typed_child (class_dict['actual-notes'])
389         a = self.get_maybe_exist_typed_child (class_dict['normal-notes'])
390         return (int(a.get_text ()), int (b.get_text ()))
391
392 class Accidental (Music_xml_node):
393     def __init__ (self):
394         Music_xml_node.__init__ (self)
395         self.editorial = False
396         self.cautionary = False
397
398
399 class Tuplet(Music_xml_node):
400     pass
401
402 class Slur (Music_xml_node):
403     def get_type (self):
404         return self.type
405
406 class Beam (Music_xml_node):
407     def get_type (self):
408         return self.get_text ()
409     def is_primary (self):
410         return self.number == "1"
411     
412 class Chord (Music_xml_node):
413     pass
414
415 class Dot (Music_xml_node):
416     pass
417
418 class Alter (Music_xml_node):
419     pass
420
421 class Rest (Music_xml_node):
422     def __init__ (self):
423         Music_xml_node.__init__ (self)
424         self._is_whole_measure = False
425     def is_whole_measure (self):
426         return self._is_whole_measure
427
428 class Mode (Music_xml_node):
429     pass
430 class Tied (Music_xml_node):
431     pass
432
433 class Type (Music_xml_node):
434     pass
435 class Grace (Music_xml_node):
436     pass
437 class Staff (Music_xml_node):
438     pass
439
440 class Instrument (Music_xml_node):
441     pass
442
443 ## need this, not all classes are instantiated
444 ## for every input file.
445 class_dict = {
446         '#comment': Hash_comment,
447         'accidental': Accidental,
448         'alter': Alter,
449         'attributes': Attributes,
450         'beam' : Beam,
451         'chord': Chord,
452         'dot': Dot,
453         'duration': Duration,
454         'grace': Grace,
455         'instrument': Instrument, 
456         'mode' : Mode,
457         'measure': Measure,
458         'notations': Notations,
459         'note': Note,
460         'part': Part,
461         'pitch': Pitch,
462         'rest':Rest,
463         'slur': Slur,
464         'tied': Tied,
465         'time-modification': Time_modification,
466         'tuplet': Tuplet,
467         'type': Type,
468         'part-list': Part_list,
469         'staff': Staff,
470 }
471
472 def name2class_name (name):
473     name = name.replace ('-', '_')
474     name = name.replace ('#', 'hash_')
475     name = name[0].upper() + name[1:].lower()
476
477     return str (name)
478
479 def get_class (name):
480     try:
481         return class_dict[name]
482     except KeyError:
483         class_name = name2class_name (name)
484         klass = new.classobj (class_name, (Music_xml_node,) , {})
485         class_dict[name] = klass
486         return klass
487         
488 def lxml_demarshal_node (node):
489     name = node.tag
490
491     if name is None:
492         return None
493     klass = get_class (name)
494     py_node = klass()
495     
496     py_node._original = node
497     py_node._name = name
498     py_node._data = node.text
499     py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
500     py_node._children = filter (lambda x: x, py_node._children)
501     
502     for c in py_node._children:
503         c._parent = py_node
504
505     for (k,v) in node.items ():
506         py_node.__dict__[k] = v
507         py_node._attribute_dict[k] = v
508
509     return py_node
510
511 def minidom_demarshal_node (node):
512     name = node.nodeName
513
514     klass = get_class (name)
515     py_node = klass()
516     py_node._name = name
517     py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
518     for c in py_node._children:
519         c._parent = py_node
520
521     if node.attributes:
522         for (nm, value) in node.attributes.items():
523             py_node.__dict__[nm] = value
524             py_node._attribute_dict[nm] = value
525             
526     py_node._data = None
527     if node.nodeType == node.TEXT_NODE and node.data:
528         py_node._data = node.data 
529
530     py_node._original = node
531     return py_node
532
533
534 if __name__  == '__main__':
535         import lxml.etree
536         
537         tree = lxml.etree.parse ('beethoven.xml')
538         mxl_tree = lxml_demarshal_node (tree.getroot ())
539         ks = class_dict.keys()
540         ks.sort()
541         print '\n'.join (ks)