]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
Don't crash when a score does not have an explicit key or clef set (e.g. Rosegarden...
[lilypond.git] / scripts / musicxml2ly.py
1 #!@TARGET_PYTHON@
2
3 import optparse
4 import sys
5 import re
6 import os
7 import string
8 from gettext import gettext as _
9
10 """
11 @relocate-preamble@
12 """
13
14 import lilylib as ly
15
16 import musicxml
17 import musicexp
18
19 from rational import Rational
20
21
22 def progress (str):
23     sys.stderr.write (str + '\n')
24     sys.stderr.flush ()
25     
26
27 def musicxml_duration_to_lily (mxl_note):
28     d = musicexp.Duration ()
29     if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
30         d.duration_log = mxl_note.get_duration_log ()
31     else:
32         d.duration_log = 0
33
34     d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
35     d.factor = mxl_note._duration / d.get_length ()
36
37     return d         
38
39 def group_tuplets (music_list, events):
40
41
42     """Collect Musics from
43     MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
44     """
45
46     
47     indices = []
48
49     j = 0
50     for (ev_chord, tuplet_elt, fraction) in events:
51         while (j < len (music_list)):
52             if music_list[j]== ev_chord:
53                 break
54             j += 1
55         if tuplet_elt.type == 'start':
56             indices.append ((j, None, fraction))
57         elif tuplet_elt.type == 'stop':
58             indices[-1] = (indices[-1][0], j, indices[-1][2])
59
60     new_list = []
61     last = 0
62     for (i1, i2, frac) in indices:
63         if i1 >= i2:
64             continue
65
66         new_list.extend (music_list[last:i1])
67         seq = musicexp.SequentialMusic ()
68         last = i2 + 1
69         seq.elements = music_list[i1:last]
70
71         tsm = musicexp.TimeScaledMusic ()
72         tsm.element = seq
73
74         tsm.numerator = frac[0]
75         tsm.denominator  = frac[1]
76
77         new_list.append (tsm)
78
79     new_list.extend (music_list[last:])
80     return new_list
81
82
83 def musicxml_clef_to_lily (attributes):
84     change = musicexp.ClefChange ()
85     change.type = attributes.get_clef_sign ()
86     return change
87     
88 def musicxml_time_to_lily (attributes):
89     (beats, type) = attributes.get_time_signature ()
90
91     change = musicexp.TimeSignatureChange()
92     change.fraction = (beats, type)
93     
94     return change
95
96 def musicxml_key_to_lily (attributes):
97     start_pitch  = musicexp.Pitch ()
98     (fifths, mode) = attributes.get_key_signature () 
99     try:
100         (n,a) = {
101             'major' : (0,0),
102             'minor' : (5,0),
103             }[mode]
104         start_pitch.step = n
105         start_pitch.alteration = a
106     except  KeyError:
107         print 'unknown mode', mode
108
109     fifth = musicexp.Pitch()
110     fifth.step = 4
111     if fifths < 0:
112         fifths *= -1
113         fifth.step *= -1
114         fifth.normalize ()
115     
116     for x in range (fifths):
117         start_pitch = start_pitch.transposed (fifth)
118
119     start_pitch.octave = 0
120
121     change = musicexp.KeySignatureChange()
122     change.mode = mode
123     change.tonic = start_pitch
124     return change
125     
126 def musicxml_attributes_to_lily (attrs):
127     elts = []
128     attr_dispatch =  {
129         'clef': musicxml_clef_to_lily,
130         'time': musicxml_time_to_lily,
131         'key': musicxml_key_to_lily
132     }
133     for (k, func) in attr_dispatch.items ():
134         children = attrs.get_named_children (k)
135
136         ## ugh: you get clefs spread over staves for piano
137         if children:
138             elts.append (func (attrs))
139     
140     return elts
141
142 spanner_event_dict = {
143     'slur' : musicexp.SlurEvent,
144     'beam' : musicexp.BeamEvent,
145 }        
146 spanner_type_dict = {
147     'start': -1,
148     'begin': -1,
149     'stop': 1,
150     'end' : 1
151 }
152
153 def musicxml_spanner_to_lily_event (mxl_event):
154     ev = None
155     
156     name = mxl_event.get_name()
157     try:
158         func = spanner_event_dict[name]
159         ev = func()
160     except KeyError:
161         print 'unknown span event ', mxl_event
162
163     try:
164         key = mxl_event.get_type ()
165         ev.span_direction = spanner_type_dict[key]
166     except KeyError:
167         print 'unknown span type', key, 'for', name
168
169     return ev
170
171 def musicxml_direction_to_indicator (direction):
172     val = { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction)
173     if val:
174         return val
175     else:
176         return ''
177
178 def musicxml_fermata_to_lily_event (mxl_event):
179     ev = musicexp.ArticulationEvent ()
180     ev.type = "fermata"
181     if hasattr (mxl_event, 'type'):
182       dir = musicxml_direction_to_indicator (mxl_event.type)
183       if dir:
184         ev.force_direction = dir
185     return ev
186
187 def musicxml_tremolo_to_lily_event(mxl_event):
188     if mxl_event.get_name () != "tremolo": 
189         return
190     ev = musicexp.TremoloEvent ()
191     ev.bars = mxl_event.get_text ()
192     return ev
193
194 # TODO: Some translations are missing!
195 articulations_dict = { 
196     ##### ORNAMENTS
197     "trill-mark": "trill", 
198     "turn": "turn", 
199     #"delayed-turn": "?", 
200     "inverted-turn": "reverseturn", 
201     #"shake": "?", 
202     #"wavy-line": "?", 
203     "mordent": "mordent",
204     #"inverted-mordent": "?", 
205     #"schleifer": "?" 
206     ##### TECHNICALS
207     "up-bow": "upbow", 
208     "down-bow": "downbow", 
209     #"harmonic": "", 
210     #"open-string": "", 
211     #"thumb-position": "", 
212     #"fingering": "", 
213     #"pluck": "", 
214     #"double-tongue": "", 
215     #"triple-tongue": "", 
216     #"stopped": "", 
217     #"snap-pizzicato": "", 
218     #"fret": "", 
219     #"string": "", 
220     #"hammer-on": "", 
221     #"pull-off": "", 
222     #"bend": "", 
223     #"tap": "", 
224     #"heel": "", 
225     #"toe": "", 
226     #"fingernails": ""
227     ##### ARTICULATIONS
228     "accent": "accent", 
229     "strong-accent": "marcato", 
230     "staccato": "staccato", 
231     "tenuto": "tenuto", 
232     #"detached-legato": "", 
233     "staccatissimo": "staccatissimo", 
234     #"spiccato": "", 
235     #"scoop": "", 
236     #"plop": "", 
237     #"doit": "", 
238     #"falloff": "",
239     "breath-mark": "breathe", 
240     #"caesura": "caesura", 
241     #"stress": "", 
242     #"unstress": ""
243 }
244
245 def musicxml_articulation_to_lily_event(mxl_event):
246     ev = musicexp.ArticulationEvent ()
247     tp = articulations_dict.get (mxl_event.get_name ())
248     if not tp:
249         return
250     
251     ev.type = tp
252
253     # Some articulations use the type attribute, other the placement...
254     dir = None
255     if hasattr (mxl_event, 'type'):
256         dir = musicxml_direction_to_indicator (mxl_event.type)
257     if hasattr (mxl_event, 'placement'):
258         dir = musicxml_direction_to_indicator (mxl_event.placement)
259     if dir:
260         ev.force_direction = dir
261     return ev
262
263
264 instrument_drumtype_dict = {
265     'Acoustic Snare Drum': 'acousticsnare',
266     'Side Stick': 'sidestick',
267     'Open Triangle': 'opentriangle',
268     'Mute Triangle': 'mutetriangle',
269     'Tambourine': 'tambourine',
270     
271 }
272
273 def musicxml_note_to_lily_main_event (n):
274     pitch  = None
275     duration = None
276         
277     mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
278     event = None
279     if mxl_pitch:
280         pitch = musicxml_pitch_to_lily (mxl_pitch)
281         event = musicexp.NoteEvent()
282         event.pitch = pitch
283
284         acc = n.get_maybe_exist_named_child ('accidental')
285         if acc:
286             # let's not force accs everywhere. 
287             event.cautionary = acc.editorial
288         
289     elif n.get_maybe_exist_typed_child (musicxml.Rest):
290         event = musicexp.RestEvent()
291     elif n.instrument_name:
292         event = musicexp.NoteEvent ()
293         try:
294             event.drum_type = instrument_drumtype_dict[n.instrument_name]
295         except KeyError:
296             n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
297             event.drum_type = 'acousticsnare'
298     
299     if not event:
300         n.message ("cannot find suitable event")
301
302     event.duration = musicxml_duration_to_lily (n)
303     return event
304
305
306 ## todo
307 class NegativeSkip:
308     def __init__ (self, here, dest):
309         self.here = here
310         self.dest = dest
311
312 class LilyPondVoiceBuilder:
313     def __init__ (self):
314         self.elements = []
315         self.end_moment = Rational (0)
316         self.begin_moment = Rational (0)
317         self.pending_multibar = Rational (0)
318
319     def _insert_multibar (self):
320         r = musicexp.MultiMeasureRest ()
321         r.duration = musicexp.Duration()
322         r.duration.duration_log = 0
323         r.duration.factor = self.pending_multibar
324         self.elements.append (r)
325         self.begin_moment = self.end_moment
326         self.end_moment = self.begin_moment + self.pending_multibar
327         self.pending_multibar = Rational (0)
328         
329     def add_multibar_rest (self, duration):
330         self.pending_multibar += duration
331         
332         
333     def add_music (self, music, duration):
334         assert isinstance (music, musicexp.Music)
335         if self.pending_multibar > Rational (0):
336             self._insert_multibar ()
337
338         self.elements.append (music)
339         self.begin_moment = self.end_moment
340         self.end_moment = self.begin_moment + duration 
341
342     def add_bar_check (self, number):
343         b = musicexp.BarCheck ()
344         b.bar_number = number
345         self.add_music (b, Rational (0))
346
347     def jumpto (self, moment):
348         current_end = self.end_moment + self.pending_multibar
349         diff = moment - current_end
350         
351         if diff < Rational (0):
352             print 'Negative skip', diff
353             diff = Rational (0)
354
355         if diff > Rational (0):
356             skip = musicexp.SkipEvent()
357             skip.duration.duration_log = 0
358             skip.duration.factor = diff
359
360             evc = musicexp.EventChord ()
361             evc.elements.append (skip)
362             self.add_music (evc, diff)
363                 
364     def last_event_chord (self, starting_at):
365
366         value = None
367         if (self.elements
368             and isinstance (self.elements[-1], musicexp.EventChord)
369             and self.begin_moment == starting_at):
370             value = self.elements[-1]
371         else:
372             self.jumpto (starting_at)
373             value = None
374
375         return value
376         
377     def correct_negative_skip (self, goto):
378         self.end_moment = goto
379         self.begin_moment = goto
380         evc = musicexp.EventChord ()
381         self.elements.append (evc)
382         
383 def musicxml_voice_to_lily_voice (voice):
384     tuplet_events = []
385     modes_found = {}
386
387     voice_builder = LilyPondVoiceBuilder()
388
389     for n in voice._elements:
390         if n.get_name () == 'forward':
391             continue
392
393         if not n.get_maybe_exist_named_child ('chord'):
394             try:
395                 voice_builder.jumpto (n._when)
396             except NegativeSkip, neg:
397                 voice_builder.correct_negative_skip (n._when)
398                 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
399             
400         if isinstance (n, musicxml.Attributes):
401             if n.is_first () and n._measure_position == Rational (0):
402                 try:
403                     number = int (n.get_parent ().number)
404                 except ValueError:
405                     number = 0
406                 
407                 voice_builder.add_bar_check (number)
408             for a in musicxml_attributes_to_lily (n):
409                 voice_builder.add_music (a, Rational (0))
410             continue
411
412         if not n.__class__.__name__ == 'Note':
413             print 'not a Note or Attributes?', n
414             continue
415
416         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
417         if (rest
418             and rest.is_whole_measure ()):
419
420             voice_builder.add_multibar_rest (n._duration)
421             continue
422
423         if n.is_first () and n._measure_position == Rational (0):
424             try: 
425                 num = int (n.get_parent ().number)
426             except ValueError:
427                 num = 0
428             voice_builder.add_bar_check (num)
429         
430         main_event = musicxml_note_to_lily_main_event (n)
431
432         try:
433             if main_event.drum_type:
434                 modes_found['drummode'] = True
435         except AttributeError:
436             pass
437
438
439         ev_chord = voice_builder.last_event_chord (n._when)
440         if not ev_chord: 
441             ev_chord = musicexp.EventChord()
442             voice_builder.add_music (ev_chord, n._duration)
443
444         ev_chord.append (main_event)
445         
446         notations = n.get_maybe_exist_typed_child (musicxml.Notations)
447         tuplet_event = None
448         span_events = []
449         
450         # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
451         # +tied | +slur | +tuplet | glissando | slide | 
452               # ornaments | technical | articulations | dynamics |
453               # +fermata | arpeggiate | non-arpeggiate | 
454               # accidental-mark | other-notation
455         if notations:
456             if notations.get_tuplet():
457                 tuplet_event = notations.get_tuplet()
458                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
459                 frac = (1,1)
460                 if mod:
461                     frac = mod.get_fraction ()
462                 
463                 tuplet_events.append ((ev_chord, tuplet_event, frac))
464
465             slurs = [s for s in notations.get_named_children ('slur')
466                 if s.get_type () in ('start','stop')]
467             if slurs:
468                 if len (slurs) > 1:
469                     print 'more than 1 slur?'
470
471                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
472                 ev_chord.append (lily_ev)
473
474             mxl_tie = notations.get_tie ()
475             if mxl_tie and mxl_tie.type == 'start':
476                 ev_chord.append (musicexp.TieEvent ())
477                 
478             fermatas = notations.get_named_children ('fermata')
479             for a in fermatas:
480                 ev = musicxml_fermata_to_lily_event (a);
481                 if ev: 
482                     ev_chord.append (ev)
483                 
484             # Articulations can contain the following child elements:
485             #         accent | strong-accent | staccato | tenuto |
486             #         detached-legato | staccatissimo | spiccato |
487             #         scoop | plop | doit | falloff | breath-mark | 
488             #         caesura | stress | unstress
489             # Technical can contain the following child elements:
490             #         up-bow | down-bow | harmonic | open-string |
491             #         thumb-position | fingering | pluck | double-tongue |
492             #         triple-tongue | stopped | snap-pizzicato | fret |
493             #         string | hammer-on | pull-off | bend | tap | heel |
494             #         toe | fingernails | other-technical
495             # Ornaments can contain the following child elements:
496             #         trill-mark | turn | delayed-turn | inverted-turn |
497             #         shake | wavy-line | mordent | inverted-mordent | 
498             #         schleifer | tremolo | other-ornament, accidental-mark
499             ornaments = notations.get_named_children ('ornaments')
500             for a in ornaments:
501                 for ch in a.get_named_children ('tremolo'):
502                     ev = musicxml_tremolo_to_lily_event (ch)
503                     if ev: 
504                         ev_chord.append (ev)
505
506             ornaments += notations.get_named_children ('articulations')
507             ornaments += notations.get_named_children ('technical')
508
509             for a in ornaments:
510                 for ch in a.get_all_children ():
511                     ev = musicxml_articulation_to_lily_event (ch)
512                     if ev: 
513                         ev_chord.append (ev)
514
515         mxl_beams = [b for b in n.get_named_children ('beam')
516                      if (b.get_type () in ('begin', 'end')
517                          and b.is_primary ())] 
518         if mxl_beams:
519             beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
520             if beam_ev:
521                 ev_chord.append (beam_ev)
522             
523         if tuplet_event:
524             mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
525             frac = (1,1)
526             if mod:
527                 frac = mod.get_fraction ()
528                 
529             tuplet_events.append ((ev_chord, tuplet_event, frac))
530
531     ## force trailing mm rests to be written out.   
532     voice_builder.add_music (musicexp.EventChord (), Rational (0))
533     
534     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
535
536     seq_music = musicexp.SequentialMusic()
537
538     if 'drummode' in modes_found.keys ():
539         ## \key <pitch> barfs in drummode.
540         ly_voice = [e for e in ly_voice
541                     if not isinstance(e, musicexp.KeySignatureChange)]
542     
543     seq_music.elements = ly_voice
544
545     
546     
547     if len (modes_found) > 1:
548        print 'Too many modes found', modes_found.keys ()
549
550     return_value = seq_music
551     for mode in modes_found.keys ():
552         v = musicexp.ModeChangingMusicWrapper()
553         v.element = return_value
554         v.mode = mode
555         return_value = v
556     
557     return return_value
558
559
560 def musicxml_id_to_lily (id):
561     digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
562               'Nine', 'Ten']
563     
564     for dig in digits:
565         d = digits.index (dig)
566         id = re.sub ('%d' % d, dig, id)
567
568     id = re.sub  ('[^a-zA-Z]', 'X', id)
569     return id
570
571
572 def musicxml_pitch_to_lily (mxl_pitch):
573     p = musicexp.Pitch()
574     p.alteration = mxl_pitch.get_alteration ()
575     p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
576     p.octave = mxl_pitch.get_octave () - 4
577     return p
578
579 def voices_in_part (part):
580     """Return a Name -> Voice dictionary for PART"""
581     part.interpret ()
582     part.extract_voices ()
583     voice_dict = part.get_voices ()
584
585     return voice_dict
586
587 def voices_in_part_in_parts (parts):
588     """return a Part -> Name -> Voice dictionary"""
589     return dict([(p, voices_in_part (p)) for p in parts])
590
591
592 def get_all_voices (parts):
593     all_voices = voices_in_part_in_parts (parts)
594
595     all_ly_voices = {}
596     for p, name_voice in all_voices.items ():
597
598         part_ly_voices = {}
599         for n, v in name_voice.items ():
600             progress ("Converting to LilyPond expressions...")
601             part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
602
603         all_ly_voices[p] = part_ly_voices
604         
605     return all_ly_voices
606
607
608 def option_parser ():
609     p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
610                              version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
611                                       +
612 _ ("""This program is free software.  It is covered by the GNU General Public
613 License and you are welcome to change it and/or distribute copies of it
614 under certain conditions.  Invoke as `%s --warranty' for more
615 information.""") % 'lilypond'
616 + """
617 Copyright (c) 2005--2007 by
618     Han-Wen Nienhuys <hanwen@xs4all.nl> and
619     Jan Nieuwenhuizen <janneke@gnu.org>
620 """),
621                              description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
622     p.add_option ('-v', '--verbose',
623                   action="store_true",
624                   dest='verbose',
625                   help=_ ("be verbose"))
626
627     p.add_option ('', '--lxml',
628                   action="store_true",
629                   default=False,
630                   dest="use_lxml",
631                   help=_ ("Use lxml.etree; uses less memory and cpu time."))
632     
633     p.add_option ('-o', '--output',
634                   metavar=_ ("FILE"),
635                   action="store",
636                   default=None,
637                   type='string',
638                   dest='output_name',
639                   help=_ ("set output filename to FILE"))
640     p.add_option_group ('bugs',
641                         description=(_ ("Report bugs via")
642                                      + ''' http://post.gmane.org/post.php'''
643                                      '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
644     return p
645
646 def music_xml_voice_name_to_lily_name (part, name):
647     str = "Part%sVoice%s" % (part.id, name)
648     return musicxml_id_to_lily (str) 
649
650 def print_voice_definitions (printer, part_list, voices):
651     part_dict={}
652     for (part, nv_dict) in voices.items():
653         part_dict[part.id] = (part, nv_dict)
654
655     for part in part_list:
656         (part, nv_dict) = part_dict[part.id]
657         for (name, (voice, mxlvoice)) in nv_dict.items ():
658             k = music_xml_voice_name_to_lily_name (part, name)
659             printer.dump ('%s = ' % k)
660             voice.print_ly (printer)
661             printer.newline()
662
663             
664 def uniq_list (l):
665     return dict ([(elt,1) for elt in l]).keys ()
666     
667 def print_score_setup (printer, part_list, voices):
668     part_dict = dict ([(p.id, p) for p in voices.keys ()]) 
669
670     printer ('<<')
671     printer.newline ()
672     for part_definition in part_list:
673         part_name = part_definition.id
674         try:
675             part = part_dict[part_name]
676         except KeyError:
677             print 'unknown part in part-list:', part_name
678             continue
679
680         nv_dict = voices[part]
681         staves = reduce (lambda x,y: x+ y,
682                 [mxlvoice._staves.keys ()
683                  for (v, mxlvoice) in nv_dict.values ()],
684                 [])
685
686         if len (staves) > 1:
687             staves = uniq_list (staves)
688             staves.sort ()
689             printer ('\\context PianoStaff << ')
690             printer.newline ()
691             
692             for s in staves:
693                 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
694                         for (voice_name, (v, mxlvoice)) in nv_dict.items ()
695                         if mxlvoice._start_staff == s]
696                 
697                 printer ('\\context Staff = "%s" << ' % s)
698                 printer.newline ()
699                 for v in staff_voices:
700                     printer ('\\context Voice = "%s"  \\%s' % (v,v))
701                     printer.newline ()
702                 printer ('>>')
703                 printer.newline ()
704                 
705             printer ('>>')
706             printer.newline ()
707             
708         else:
709             printer ('\\new Staff <<')
710             printer.newline ()
711             for (n,v) in nv_dict.items ():
712
713                 n = music_xml_voice_name_to_lily_name (part, n) 
714                 printer ('\\context Voice = "%s"  \\%s' % (n,n))
715             printer ('>>')
716             printer.newline ()
717             
718     printer ('>>')
719     printer.newline ()
720
721 def print_ly_preamble (printer, filename):
722     printer.dump_version ()
723     printer.print_verbatim ('%% automatically converted from %s\n' % filename)
724
725 def read_musicxml (filename, use_lxml):
726     if use_lxml:
727         import lxml.etree
728         
729         tree = lxml.etree.parse (filename)
730         mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
731         return mxl_tree
732     else:
733         from xml.dom import minidom, Node
734         
735         doc = minidom.parse(filename)
736         node = doc.documentElement
737         return musicxml.minidom_demarshal_node (node)
738
739     return None
740
741
742 def convert (filename, options):
743     progress ("Reading MusicXML from %s ..." % filename)
744     
745     tree = read_musicxml (filename, options.use_lxml)
746
747     part_list = []
748     id_instrument_map = {}
749     if tree.get_maybe_exist_typed_child (musicxml.Part_list):
750         mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
751         part_list = mxl_pl.get_named_children ("score-part")
752         
753     parts = tree.get_typed_children (musicxml.Part)
754     voices = get_all_voices (parts)
755
756     if not options.output_name:
757         options.output_name = os.path.basename (filename) 
758         options.output_name = os.path.splitext (options.output_name)[0]
759
760
761     defs_ly_name = options.output_name + '-defs.ly'
762     driver_ly_name = options.output_name + '.ly'
763
764     printer = musicexp.Output_printer()
765     progress ("Output to `%s'" % defs_ly_name)
766     printer.set_file (open (defs_ly_name, 'w'))
767
768     print_ly_preamble (printer, filename)
769     print_voice_definitions (printer, part_list, voices)
770     
771     printer.close ()
772     
773     
774     progress ("Output to `%s'" % driver_ly_name)
775     printer = musicexp.Output_printer()
776     printer.set_file (open (driver_ly_name, 'w'))
777     print_ly_preamble (printer, filename)
778     printer.dump (r'\include "%s"' % defs_ly_name)
779     print_score_setup (printer, part_list, voices)
780     printer.newline ()
781
782     return voices
783
784
785 def main ():
786     opt_parser = option_parser()
787
788     (options, args) = opt_parser.parse_args ()
789     if not args:
790         opt_parser.print_usage()
791         sys.exit (2)
792
793     voices = convert (args[0], options)
794
795 if __name__ == '__main__':
796     main()