]> git.donarmstrong.com Git - lilypond.git/blobdiff - scripts/musicxml2ly.py
(grob-cause): replace backslashes by /
[lilypond.git] / scripts / musicxml2ly.py
index 4e5a39b2d838158aff34ddd4bae5e867fa673241..4b5abf9a7061f450fc1fe46b95645adf96cd7294 100644 (file)
@@ -7,6 +7,7 @@ import os
 import string
 from gettext import gettext as _
 
+
 datadir = '@local_lilypond_datadir@'
 if not os.path.isdir (datadir):
        datadir = '@lilypond_datadir@'
@@ -25,6 +26,8 @@ sys.path.insert (0, os.path.join (datadir, 'python'))
 
 import musicxml
 import musicexp
+import lilylib as ly
+
 from rational import Rational
 
 
@@ -212,7 +215,6 @@ def musicxml_note_to_lily_main_event (n):
                if acc:
                        # let's not force accs everywhere. 
                        event.cautionary = acc.editorial
-                       print event, event.cautionary, event.ly_expression()
                
        elif n.get_maybe_exist_typed_child (musicxml.Rest):
                event = musicexp.RestEvent()
@@ -221,17 +223,20 @@ def musicxml_note_to_lily_main_event (n):
        return event
 
 def musicxml_voice_to_lily_voice (voice):
-       
        ly_voice = []
        ly_now = Rational (0)
+       pending_skip = Rational (0) 
 
        tuplet_events = []
 
-       for n in voice:
+       for n in voice._elements:
                if n.get_name () == 'forward':
                        continue
                
                if isinstance (n, musicxml.Attributes):
+                       ly_now += pending_skip
+                       pending_skip = Rational (0)
+                       
                        ly_voice.extend (musicxml_attributes_to_lily (n))
                        continue
                
@@ -242,13 +247,17 @@ def musicxml_voice_to_lily_voice (voice):
                if n.is_first () and ly_voice:
                        ly_voice[-1].comment += '\n'
                
+
+               main_event = musicxml_note_to_lily_main_event (n)
+
                ev_chord = None
                if None ==  n.get_maybe_exist_typed_child (musicxml.Chord):
-                       if ly_voice:
-                               ly_now += ly_voice[-1].get_length ()
+                       ly_now += pending_skip
+                       pending_skip = main_event.get_length ()
 
                        if ly_now <> n._when:
                                diff = n._when - ly_now
+
                                if diff < Rational (0):
                                        print 'huh: negative skip', n._when, ly_now, n._duration
                                        diff = Rational (1,314159265)
@@ -261,15 +270,14 @@ def musicxml_voice_to_lily_voice (voice):
                        pass
                
                ev_chord = ly_voice[-1]
-
-               main_event = musicxml_note_to_lily_main_event (n)
                ev_chord.append (main_event)
-                       
+               
                notations = n.get_maybe_exist_typed_child (musicxml.Notations)
                tuplet_event = None
                span_events = []
                if notations:
                        if notations.get_tuplet():
+                               tuplet_event = notations.get_tuplet()
                                mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
                                frac = (1,1)
                                if mod:
@@ -333,56 +341,39 @@ def musicxml_pitch_to_lily (mxl_pitch):
        p.octave = mxl_pitch.get_octave () - 4
        return p
 
-def get_all_voices (parts):
-       progress ("Synchronizing MusicXML...")
-       
-       all_voices = {} 
-       for p in parts:
-               p.interpret ()
-               p.extract_voices ()             
-               voice_dict = p.get_voices ()
-               
-               for (id, voice) in voice_dict.items ():
-                       m_name = 'Part' + p.id + 'Voice' + id
-                       m_name = musicxml_id_to_lily (m_name)
-                       all_voices[m_name] = voice
 
 
-       progress ("Converting to LilyPond expressions...")
+def voices_in_part (part):
+       """Return a Name -> Voice dictionary for PART"""
+       part.interpret ()
+       part.extract_voices ()          
+       voice_dict = part.get_voices ()
+
+       return voice_dict
+
+def voices_in_part_in_parts (parts):
+       """return a Part -> Name -> Voice dictionary"""
+       return dict([(p, voices_in_part (p)) for p in parts])
+
+
+def get_all_voices (parts):
+       all_voices = voices_in_part_in_parts (parts)
+
        all_ly_voices = {}
-       for (k, v) in all_voices.items():
-               all_ly_voices[k] = musicxml_voice_to_lily_voice (v)
+       for p, name_voice in all_voices.items ():
 
+               part_ly_voices = {}
+               for n, v in name_voice.items ():
+                       progress ("Converting to LilyPond expressions...")
+                       part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
+
+               all_ly_voices[p] = part_ly_voices
+               
        return all_ly_voices
 
-class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
-    def format_heading(self, heading):
-           if heading:
-                   return heading[0].upper() + heading[1:] + ':\n'
-           return ''
-    def format_option_strings(self, option):
-           sep = ' '
-           if option._short_opts and option._long_opts:
-                   sep = ','
-
-           metavar = ''
-           if option.takes_value():
-                   metavar = '=' + option.metavar or option.dest.upper()
-
-           return "%3s%s %s%s" % (" ".join (option._short_opts),
-                                  sep,
-                                  " ".join (option._long_opts),
-                                  metavar)
-
-    def format_usage(self, usage):
-        return _("Usage: %s\n") % usage
-    
-    def format_description(self, description):
-           return description
-  
 
 def option_parser ():
-       p = optparse.OptionParser(usage='musicxml2ly FILE.xml',
+       p = ly.get_option_parser(usage='musicxml2ly FILE.xml',
                                  version = """%prog (LilyPond) @TOPLEVEL_VERSION@
 
 This program is free software.  It is covered by the GNU General Public
@@ -390,7 +381,7 @@ License and you are welcome to change it and/or distribute copies of it
 under certain conditions.  Invoke as `lilypond --warranty' for more
 information.
 
-Copyright (c) 2005 by
+Copyright (c) 2005--2006 by
   Han-Wen Nienhuys <hanwen@xs4all.nl> and
   Jan Nieuwenhuizen <janneke@gnu.org>
 """,
@@ -413,38 +404,123 @@ Copyright (c) 2005 by
 
        p.add_option_group  ('', description = '''Report bugs via http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
 ''')
-       p.formatter = NonDentedHeadingFormatter () 
        return p
 
+def music_xml_voice_name_to_lily_name (part, name):
+       str = "Part%sVoice%s" % (part.id, name)
+       return musicxml_id_to_lily (str) 
+
+def print_voice_definitions (printer, voices):
+       for (part, nv_dict) in voices.items():
+               for (name, (voice, mxlvoice)) in nv_dict.items ():
+                       k = music_xml_voice_name_to_lily_name (part, name)
+                       printer.dump ('%s = ' % k)
+                       voice.print_ly (printer)
+                       printer.newline()
+def uniq_list (l):
+       return dict ([(elt,1) for elt in l]).keys ()
+       
+def print_score_setup (printer, part_list, voices):
+       part_dict = dict ([(p.id, p) for p in voices.keys ()]) 
+
+       printer ('<<')
+       printer.newline ()
+       for part_definition in part_list:
+               part_name = part_definition.id
+               try:
+                       part = part_dict[part_name]
+               except KeyError:
+                       print 'unknown part in part-list:', part_name
+                       continue
+
+               nv_dict = voices[part]
+               staves = reduce (lambda x,y: x+ y,
+                                [mxlvoice._staves.keys ()
+                                 for (v, mxlvoice) in nv_dict.values ()],
+                                [])
+
+               if len (staves) > 1:
+                       staves = uniq_list (staves)
+                       staves.sort ()
+                       printer ('\\context PianoStaff << ')
+                       printer.newline ()
+                       
+                       for s in staves:
+                               staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
+                                               for (voice_name, (v, mxlvoice)) in nv_dict.items ()
+                                               if mxlvoice._start_staff == s]
+                               
+                               printer ('\\context Staff = "%s" << ' % s)
+                               printer.newline ()
+                               for v in staff_voices:
+                                       printer ('\\context Voice = "%s"  \\%s' % (v,v))
+                                       printer.newline ()
+                               printer ('>>')
+                               printer.newline ()
+                               
+                       printer ('>>')
+                       printer.newline ()
+                       
+               else:
+                       printer ('\\new Staff <<')
+                       printer.newline ()
+                       for (n,v) in nv_dict.items ():
+
+                               n = music_xml_voice_name_to_lily_name (part, n) 
+                               printer ('\\context Voice = "%s"  \\%s' % (n,n))
+                       printer ('>>')
+                       printer.newline ()
+                       
+
+       printer ('>>')
+       printer.newline ()
+
+                               
+
+def print_ly_preamble (printer, filename):
+       printer.dump_version ()
+       printer.print_verbatim ('%% converted from %s\n' % filename)
 
 def convert (filename, output_name):
-       
        printer = musicexp.Output_printer()
-
        progress ("Reading MusicXML...")
        
        tree = musicxml.read_musicxml (filename)
        parts = tree.get_typed_children (musicxml.Part)
-
        voices = get_all_voices (parts)
 
-       if output_name:
-               printer.file = open (output_name,'w')
+       part_list = []
+       if tree.get_maybe_exist_typed_child (musicxml.Part_list):
+               pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
+               part_list = pl.get_named_children ("score-part")
                
+       if not output_name:
+               output_name = os.path.basename (filename)
+               output_name = os.path.splitext (output_name)[0] + '.ly'
+
+               
+       if output_name:
+               progress ("Output to `%s'" % output_name)
+               printer.set_file (open (output_name, 'w'))
+       
        progress ("Printing as .ly...")
-       for  (k,v) in voices.items():
-               printer.dump ('%s = ' % k)
-               v.print_ly (printer)
-               printer.newline()
 
+       print_ly_preamble (printer, filename)
+       print_voice_definitions (printer,  voices)
+       print_score_setup (printer, part_list, voices)
+       printer.newline ()
        return voices
 
 
-opt_parser = option_parser()
+def main ():
+       opt_parser = option_parser()
+
+       (options, args) = opt_parser.parse_args ()
+       if not args:
+               opt_parser.print_usage()
+               sys.exit (2)
 
-(options, args) = opt_parser.parse_args ()
-if not args:
-       opt_parser.print_usage()
-       sys.exit (2)
+       voices = convert (args[0], options.output)
 
-voices = convert (args[0], options.output)
+if __name__ == '__main__':
+       main()