]> git.donarmstrong.com Git - lilypond.git/blob - python/musicxml.py
MusicXML: Fix small issues detected with Recordare sample MusicXML files
[lilypond.git] / python / musicxml.py
1 import new
2 import string
3 from rational import *
4 import re
5 import sys
6
7 def escape_ly_output_string (input_string):
8     return_string = input_string
9     needs_quotes = not re.match (u"^[a-zA-ZäöüÜÄÖßñ]*$", return_string);
10     if needs_quotes:
11         return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
12     return return_string
13
14
15 class Xml_node:
16     def __init__ (self):
17         self._children = []
18         self._data = None
19         self._original = None
20         self._name = 'xml_node'
21         self._parent = None
22         self._attribute_dict = {}
23         
24     def get_parent (self):
25         return self._parent
26     
27     def is_first (self):
28         return self._parent.get_typed_children (self.__class__)[0] == self
29
30     def original (self):
31         return self._original 
32     def get_name (self):
33         return self._name
34
35     def get_text (self):
36         if self._data:
37             return self._data
38
39         if not self._children:
40             return ''
41
42         return ''.join ([c.get_text () for c in self._children])
43
44     def message (self, msg):
45         sys.stderr.write (msg+'\n')
46
47         p = self
48         while p:
49             sys.stderr.write ('  In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()])))
50             p = p.get_parent ()
51         
52     def get_typed_children (self, klass):
53         if not klass:
54             return []
55         else:
56             return [c for c in self._children if isinstance(c, klass)]
57
58     def get_named_children (self, nm):
59         return self.get_typed_children (get_class (nm))
60
61     def get_named_child (self, nm):
62         return self.get_maybe_exist_named_child (nm)
63
64     def get_children (self, predicate):
65         return [c for c in self._children if predicate(c)]
66
67     def get_all_children (self):
68         return self._children
69
70     def get_maybe_exist_named_child (self, name):
71         return self.get_maybe_exist_typed_child (get_class (name))
72
73     def get_maybe_exist_typed_child (self, klass):
74         cn = self.get_typed_children (klass)
75         if len (cn)==0:
76             return None
77         elif len (cn) == 1:
78             return cn[0]
79         else:
80             raise "More than 1 child", klass
81
82     def get_unique_typed_child (self, klass):
83         cn = self.get_typed_children(klass)
84         if len (cn) <> 1:
85             sys.stderr.write (self.__dict__ + '\n')
86             raise 'Child is not unique for', (klass, 'found', cn)
87
88         return cn[0]
89
90 class Music_xml_node (Xml_node):
91     def __init__ (self):
92         Xml_node.__init__ (self)
93         self.duration = Rational (0)
94         self.start = Rational (0)
95
96 class Work (Xml_node):
97     def get_work_information (self, tag):
98         wt = self.get_maybe_exist_named_child (tag)
99         if wt:
100             return wt.get_text ()
101         else:
102             return ''
103       
104     def get_work_title (self):
105         return self.get_work_information ('work-title')
106     def get_work_number (self):
107         return self.get_work_information ('work-number')
108     def get_opus (self):
109         return self.get_work_information ('opus')
110
111 class Identification (Xml_node):
112     def get_rights (self):
113         rights = self.get_maybe_exist_named_child ('rights')
114         if rights:
115             return rights.get_text ()
116         else:
117             return ''
118
119     def get_creator (self, type):
120         creators = self.get_named_children ('creator')
121         # return the first creator tag that has the particular type
122         for i in creators:
123             if hasattr (i, 'type') and i.type == type:
124                 return i.get_text ()
125         return None
126
127     def get_composer (self):
128         c = self.get_creator ('composer')
129         if c:
130             return c
131         creators = self.get_named_children ('creator')
132         # return the first creator tag that has no type at all
133         for i in creators:
134             if not hasattr (i, 'type'):
135                 return i.get_text ()
136         return None
137     def get_arranger (self):
138         return self.get_creator ('arranger')
139     def get_editor (self):
140         return self.get_creator ('editor')
141     def get_poet (self):
142         v = self.get_creator ('lyricist')
143         if v:
144             return v
145         v = self.get_creator ('poet')
146         return v
147     
148     def get_encoding_information (self, type):
149         enc = self.get_named_children ('encoding')
150         if enc:
151             children = enc[0].get_named_children (type)
152             if children:
153                 return children[0].get_text ()
154         else:
155             return None
156       
157     def get_encoding_software (self):
158         return self.get_encoding_information ('software')
159     def get_encoding_date (self):
160         return self.get_encoding_information ('encoding-date')
161     def get_encoding_person (self):
162         return self.get_encoding_information ('encoder')
163     def get_encoding_description (self):
164         return self.get_encoding_information ('encoding-description')
165
166
167 class Duration (Music_xml_node):
168     def get_length (self):
169         dur = int (self.get_text ()) * Rational (1,4)
170         return dur
171
172 class Hash_comment (Music_xml_node):
173     pass
174 class Hash_text (Music_xml_node):
175     pass
176
177 class Pitch (Music_xml_node):
178     def get_step (self):
179         ch = self.get_unique_typed_child (get_class (u'step'))
180         step = ch.get_text ().strip ()
181         return step
182     def get_octave (self):
183         ch = self.get_unique_typed_child (get_class (u'octave'))
184
185         step = ch.get_text ().strip ()
186         return int (step)
187
188     def get_alteration (self):
189         ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
190         alter = 0
191         if ch:
192             alter = int (ch.get_text ().strip ())
193         return alter
194
195 class Measure_element (Music_xml_node):
196     def get_voice_id (self):
197         voice_id = self.get_maybe_exist_named_child ('voice')
198         if voice_id:
199             return voice_id.get_text ()
200         else:
201             return None
202
203     def is_first (self):
204         cn = self._parent.get_typed_children (self.__class__)
205         cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
206         return cn[0] == self
207
208 class Attributes (Measure_element):
209     def __init__ (self):
210         Measure_element.__init__ (self)
211         self._dict = {}
212
213     def set_attributes_from_previous (self, dict):
214         self._dict.update (dict)
215         
216     def read_self (self):
217         for c in self.get_all_children ():
218             self._dict[c.get_name()] = c
219
220     def get_named_attribute (self, name):
221         return self._dict.get (name)
222
223     def get_measure_length (self):
224         (n,d) = self.get_time_signature ()
225         return Rational (n,d)
226         
227     def get_time_signature (self):
228         "return time sig as a (beat, beat-type) tuple"
229
230         try:
231             mxl = self.get_named_attribute ('time')
232             if mxl:
233                 beats = mxl.get_maybe_exist_named_child ('beats')
234                 type = mxl.get_maybe_exist_named_child ('beat-type')
235                 return (int (beats.get_text ()),
236                         int (type.get_text ()))
237             else:
238                 return (4, 4)
239         except KeyError:
240             sys.stderr.write ('error: requested time signature, but time sig unknown\n')
241             return (4, 4)
242
243     # returns clef information in the form ("cleftype", position, octave-shift)
244     def get_clef_information (self):
245         clefinfo = ['G', 2, 0]
246         mxl = self.get_named_attribute ('clef')
247         if not mxl:
248             return clefinfo
249         sign = mxl.get_maybe_exist_named_child ('sign')
250         if sign:
251             clefinfo[0] = sign.get_text()
252         line = mxl.get_maybe_exist_named_child ('line')
253         if line:
254             clefinfo[1] = string.atoi (line.get_text ())
255         octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
256         if octave:
257             clefinfo[2] = string.atoi (octave.get_text ())
258         return clefinfo
259
260     def get_key_signature (self):
261         "return (fifths, mode) tuple"
262
263         key = self.get_named_attribute ('key')
264         mode_node = key.get_maybe_exist_named_child ('mode')
265         mode = 'major'
266         if mode_node:
267             mode = mode_node.get_text ()
268
269         fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
270         return (fifths, mode)
271                 
272
273 class Note (Measure_element):
274     def __init__ (self):
275         Measure_element.__init__ (self)
276         self.instrument_name = ''
277         
278     def get_duration_log (self):
279         ch = self.get_maybe_exist_typed_child (get_class (u'type'))
280
281         if ch:
282             log = ch.get_text ().strip()
283             return {'256th': 8,
284                     '128th': 7,
285                     '64th': 6,
286                     '32nd': 5,
287                     '16th': 4,
288                     'eighth': 3,
289                     'quarter': 2,
290                     'half': 1,
291                     'whole': 0,
292                     'breve': -1,
293                     'long': -2}.get (log, 0)
294         else:
295             sys.stderr.write ("Encountered note without duration (no <type> element): %s\n" % self)
296             return 0
297
298     def get_factor (self):
299         return 1
300
301     def get_pitches (self):
302         return self.get_typed_children (get_class (u'pitch'))
303
304 class Part_list (Music_xml_node):
305     def __init__ (self):
306         Music_xml_node.__init__ (self)
307         self._id_instrument_name_dict = {}
308         
309     def generate_id_instrument_dict (self):
310
311         ## not empty to make sure this happens only once.
312         mapping = {1: 1}
313         for score_part in self.get_named_children ('score-part'):
314             for instr in score_part.get_named_children ('score-instrument'):
315                 id = instr.id
316                 name = instr.get_named_child ("instrument-name")
317                 mapping[id] = name.get_text ()
318
319         self._id_instrument_name_dict = mapping
320
321     def get_instrument (self, id):
322         if not self._id_instrument_name_dict:
323             self.generate_id_instrument_dict()
324
325         instrument_name = self._id_instrument_name_dict.get (id)
326         if instrument_name:
327             return instrument_name
328         else:
329             sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
330             return "Grand Piano"
331         
332 class Measure (Music_xml_node):
333     def get_notes (self):
334         return self.get_typed_children (get_class (u'note'))
335
336 class Syllabic (Music_xml_node):
337     def continued (self):
338         text = self.get_text()
339         return (text == "begin") or (text == "middle")
340 class Text (Music_xml_node):
341     pass
342
343 class Lyric (Music_xml_node):
344     def get_number (self):
345         if hasattr (self, 'number'):
346             return self.number
347         else:
348             return -1
349
350     def lyric_to_text (self):
351         continued = False
352         syllabic = self.get_maybe_exist_typed_child (Syllabic)
353         if syllabic:
354             continued = syllabic.continued ()
355         text = self.get_maybe_exist_typed_child (Text)
356         
357         if text:
358             text = text.get_text()
359             # We need to convert soft hyphens to -, otherwise the ascii codec as well
360             # as lilypond will barf on that character
361             text = string.replace( text, u'\xad', '-' )
362         
363         if text == "-" and continued:
364             return "--"
365         elif text == "_" and continued:
366             return "__"
367         elif continued and text:
368             return escape_ly_output_string (text) + " --"
369         elif continued:
370             return "--"
371         elif text:
372             return escape_ly_output_string (text)
373         else:
374             return ""
375
376 class Musicxml_voice:
377     def __init__ (self):
378         self._elements = []
379         self._staves = {}
380         self._start_staff = None
381         self._lyrics = []
382         self._has_lyrics = False
383
384     def add_element (self, e):
385         self._elements.append (e)
386         if (isinstance (e, Note)
387             and e.get_maybe_exist_typed_child (Staff)):
388             name = e.get_maybe_exist_typed_child (Staff).get_text ()
389
390             if not self._start_staff:
391                 self._start_staff = name
392             self._staves[name] = True
393
394         lyrics = e.get_typed_children (Lyric)
395         if not self._has_lyrics:
396           self.has_lyrics = len (lyrics) > 0
397
398         for l in lyrics:
399             nr = l.get_number()
400             if (nr > 0) and not (nr in self._lyrics):
401                 self._lyrics.append (nr)
402
403     def insert (self, idx, e):
404         self._elements.insert (idx, e)
405
406     def get_lyrics_numbers (self):
407         if (len (self._lyrics) == 0) and self._has_lyrics:
408             #only happens if none of the <lyric> tags has a number attribute
409             return [1]
410         else:
411             return self._lyrics
412
413
414
415 class Part (Music_xml_node):
416     def __init__ (self):
417         Music_xml_node.__init__ (self)
418         self._voices = []
419
420     def get_part_list (self):
421         n = self
422         while n and n.get_name() != 'score-partwise':
423             n = n._parent
424
425         return n.get_named_child ('part-list')
426         
427     def interpret (self):
428         """Set durations and starting points."""
429         
430         part_list = self.get_part_list ()
431         
432         now = Rational (0)
433         factor = Rational (1)
434         attributes_dict = {}
435         attributes_object = None
436         measures = self.get_typed_children (Measure)
437         last_moment = Rational (-1)
438         last_measure_position = Rational (-1)
439         for m in measures:
440             measure_start_moment = now
441             measure_position = Rational (0)
442             for n in m.get_all_children ():
443                 if isinstance (n, Hash_text):
444                     continue
445                 dur = Rational (0)
446
447                 if n.__class__ == Attributes:
448                     n.set_attributes_from_previous (attributes_dict)
449                     n.read_self ()
450                     attributes_dict = n._dict.copy ()
451                     attributes_object = n
452                     
453                     factor = Rational (1,
454                                        int (attributes_dict.get ('divisions').get_text ()))
455
456                 
457                 if (n.get_maybe_exist_typed_child (Duration)):
458                     mxl_dur = n.get_maybe_exist_typed_child (Duration)
459                     dur = mxl_dur.get_length () * factor
460                     
461                     if n.get_name() == 'backup':
462                         dur = - dur
463                     if n.get_maybe_exist_typed_child (Grace):
464                         dur = Rational (0)
465
466                     rest = n.get_maybe_exist_typed_child (Rest)
467                     if (rest
468                         and attributes_object
469                         and attributes_object.get_measure_length () == dur):
470
471                         rest._is_whole_measure = True
472
473                 if (dur > Rational (0) 
474                     and n.get_maybe_exist_typed_child (Chord)):
475                     now = last_moment
476                     measure_position = last_measure_position
477
478                 n._when = now
479                 n._measure_position = measure_position
480                 n._duration = dur
481                 if dur > Rational (0):
482                     last_moment = now
483                     last_measure_position = measure_position
484                     now += dur
485                     measure_position += dur
486                 elif dur < Rational (0):
487                     # backup element, reset measure position
488                     now += dur
489                     measure_position += dur
490                     if measure_position < 0:
491                         # backup went beyond the measure start => reset to 0
492                         now -= measure_position
493                         measure_position = 0
494                     last_moment = now
495                     last_measure_position = measure_position
496                 if n._name == 'note':
497                     instrument = n.get_maybe_exist_named_child ('instrument')
498                     if instrument:
499                         n.instrument_name = part_list.get_instrument (instrument.id)
500
501             if attributes_object:
502                 length = attributes_object.get_measure_length ()
503                 new_now = measure_start_moment + length
504                 
505                 if now <> new_now:
506                     problem = 'incomplete'
507                     if now > new_now:
508                         problem = 'overfull'
509
510                     ## only for verbose operation.
511                     if problem <> 'incomplete':
512                         m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
513
514                 now = new_now
515
516     def extract_voices (part):
517         voices = {}
518         measures = part.get_typed_children (Measure)
519         elements = []
520         for m in measures:
521             elements.extend (m.get_all_children ())
522
523         start_attr = None
524         for n in elements:
525             voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
526
527             # TODO: If the first element of a voice is a dynamics entry,
528             #       then voice_id is not yet set! Thus it will currently be ignored
529             if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
530                 continue
531
532             if isinstance (n, Attributes) and not start_attr:
533                 start_attr = n
534                 continue
535
536             if isinstance (n, Attributes) or isinstance (n, Direction):
537                 for v in voices.values ():
538                     v.add_element (n)
539                 continue
540
541             id = voice_id.get_text ()
542             if not voices.has_key (id):
543                 voices[id] = Musicxml_voice()
544
545             voices[id].add_element (n)
546
547         if start_attr:
548             for (k,v) in voices.items ():
549                 v.insert (0, start_attr)
550
551         part._voices = voices
552
553     def get_voices (self):
554         return self._voices
555
556 class Notations (Music_xml_node):
557     def get_tie (self):
558         ts = self.get_named_children ('tied')
559         starts = [t for t in ts if t.type == 'start']
560         if starts:
561             return starts[0]
562         else:
563             return None
564
565     def get_tuplet (self):
566         return self.get_maybe_exist_typed_child (Tuplet)
567
568 class Time_modification(Music_xml_node):
569     def get_fraction (self):
570         b = self.get_maybe_exist_named_child ('actual-notes')
571         a = self.get_maybe_exist_named_child ('normal-notes')
572         return (int(a.get_text ()), int (b.get_text ()))
573
574 class Accidental (Music_xml_node):
575     def __init__ (self):
576         Music_xml_node.__init__ (self)
577         self.editorial = False
578         self.cautionary = False
579
580 class Music_xml_spanner (Music_xml_node):
581     def get_type (self):
582         if hasattr (self, 'type'):
583             return self.type
584         else:
585             return 0
586     def get_size (self):
587         if hasattr (self, 'size'):
588             return string.atoi (self.size)
589         else:
590             return 0
591
592 class Wedge (Music_xml_spanner):
593     pass
594
595 class Tuplet (Music_xml_spanner):
596     pass
597
598 class Slur (Music_xml_spanner):
599     def get_type (self):
600         return self.type
601
602 class Beam (Music_xml_spanner):
603     def get_type (self):
604         return self.get_text ()
605     def is_primary (self):
606         return self.number == "1"
607
608 class Wavy_line (Music_xml_spanner):
609     pass
610     
611 class Pedal (Music_xml_spanner):
612     pass
613
614 class Glissando (Music_xml_spanner):
615     pass
616
617 class Octave_shift (Music_xml_spanner):
618     # default is 8 for the octave-shift!
619     def get_size (self):
620         if hasattr (self, 'size'):
621             return string.atoi (self.size)
622         else:
623             return 8
624
625 class Chord (Music_xml_node):
626     pass
627
628 class Dot (Music_xml_node):
629     pass
630
631 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
632 # for the inner <rest> element, not the whole rest block.
633 class Rest (Music_xml_node):
634     def __init__ (self):
635         Music_xml_node.__init__ (self)
636         self._is_whole_measure = False
637     def is_whole_measure (self):
638         return self._is_whole_measure
639     def get_step (self):
640         ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
641         if ch:
642             step = ch.get_text ().strip ()
643             return step
644         else:
645             return None
646     def get_octave (self):
647         ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
648         if ch:
649             step = ch.get_text ().strip ()
650             return int (step)
651         else:
652             return None
653
654 class Type (Music_xml_node):
655     pass
656 class Grace (Music_xml_node):
657     pass
658 class Staff (Music_xml_node):
659     pass
660
661 class Direction (Music_xml_node):
662     pass
663 class DirType (Music_xml_node):
664     pass
665
666 class Bend (Music_xml_node):
667     def bend_alter (self):
668         alter = self.get_maybe_exist_named_child ('bend-alter')
669         if alter:
670             return alter.get_text()
671         else:
672             return 0
673
674
675
676 ## need this, not all classes are instantiated
677 ## for every input file. Only add those classes, that are either directly
678 ## used by class name or extend Music_xml_node in some way!
679 class_dict = {
680         '#comment': Hash_comment,
681         '#text': Hash_text,
682         'accidental': Accidental,
683         'attributes': Attributes,
684         'beam' : Beam,
685         'bend' : Bend,
686         'chord': Chord,
687         'dot': Dot,
688         'direction': Direction,
689         'direction-type': DirType,
690         'duration': Duration,
691         'glissando': Glissando,
692         'grace': Grace,
693         'identification': Identification,
694         'lyric': Lyric,
695         'measure': Measure,
696         'notations': Notations,
697         'note': Note,
698         'octave-shift': Octave_shift,
699         'part': Part,
700         'part-list': Part_list,
701         'pedal': Pedal,
702         'pitch': Pitch,
703         'rest': Rest,
704         'slur': Slur,
705         'staff': Staff,
706         'syllabic': Syllabic,
707         'text': Text,
708         'time-modification': Time_modification,
709         'tuplet': Tuplet,
710         'type': Type,
711         'wavy-line': Wavy_line,
712         'wedge': Wedge,
713         'work': Work,
714 }
715
716 def name2class_name (name):
717     name = name.replace ('-', '_')
718     name = name.replace ('#', 'hash_')
719     name = name[0].upper() + name[1:].lower()
720
721     return str (name)
722
723 def get_class (name):
724     classname = class_dict.get (name)
725     if classname:
726         return classname
727     else:
728         class_name = name2class_name (name)
729         klass = new.classobj (class_name, (Music_xml_node,) , {})
730         class_dict[name] = klass
731         return klass
732         
733 def lxml_demarshal_node (node):
734     name = node.tag
735
736     if name is None:
737         return None
738     klass = get_class (name)
739     py_node = klass()
740     
741     py_node._original = node
742     py_node._name = name
743     py_node._data = node.text
744     py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
745     py_node._children = filter (lambda x: x, py_node._children)
746     
747     for c in py_node._children:
748         c._parent = py_node
749
750     for (k,v) in node.items ():
751         py_node.__dict__[k] = v
752         py_node._attribute_dict[k] = v
753
754     return py_node
755
756 def minidom_demarshal_node (node):
757     name = node.nodeName
758
759     klass = get_class (name)
760     py_node = klass()
761     py_node._name = name
762     py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
763     for c in py_node._children:
764         c._parent = py_node
765
766     if node.attributes:
767         for (nm, value) in node.attributes.items():
768             py_node.__dict__[nm] = value
769             py_node._attribute_dict[nm] = value
770             
771     py_node._data = None
772     if node.nodeType == node.TEXT_NODE and node.data:
773         py_node._data = node.data 
774
775     py_node._original = node
776     return py_node
777
778
779 if __name__  == '__main__':
780         import lxml.etree
781         
782         tree = lxml.etree.parse ('beethoven.xml')
783         mxl_tree = lxml_demarshal_node (tree.getroot ())
784         ks = class_dict.keys()
785         ks.sort()
786         print '\n'.join (ks)