]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
9e48b1f53ebfc2b936862c5c95042e40df3457a0
[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     func = spanner_event_dict.get (name)
158     if func:
159         ev = func()
160     else:
161         print 'unknown span event ', mxl_event
162
163     key = mxl_event.get_type ()
164     span_direction = spanner_type_dict.get (key)
165     if span_direction:
166         ev.span_direction = span_direction
167     else:
168         print 'unknown span type', key, 'for', name
169
170     return ev
171
172 def musicxml_direction_to_indicator (direction):
173     return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
174
175 def musicxml_fermata_to_lily_event (mxl_event):
176     ev = musicexp.ArticulationEvent ()
177     ev.type = "fermata"
178     if hasattr (mxl_event, 'type'):
179       dir = musicxml_direction_to_indicator (mxl_event.type)
180       if dir:
181         ev.force_direction = dir
182     return ev
183
184 def musicxml_tremolo_to_lily_event(mxl_event):
185     if mxl_event.get_name () != "tremolo": 
186         return
187     ev = musicexp.TremoloEvent ()
188     ev.bars = mxl_event.get_text ()
189     return ev
190
191 # TODO: Some translations are missing!
192 articulations_dict = { 
193     ##### ORNAMENTS
194     "trill-mark": "trill", 
195     "turn": "turn", 
196     #"delayed-turn": "?", 
197     "inverted-turn": "reverseturn", 
198     #"shake": "?", 
199     #"wavy-line": "?", 
200     "mordent": "mordent",
201     #"inverted-mordent": "?", 
202     #"schleifer": "?" 
203     ##### TECHNICALS
204     "up-bow": "upbow", 
205     "down-bow": "downbow", 
206     #"harmonic": "", 
207     #"open-string": "", 
208     #"thumb-position": "", 
209     #"fingering": "", 
210     #"pluck": "", 
211     #"double-tongue": "", 
212     #"triple-tongue": "", 
213     #"stopped": "", 
214     #"snap-pizzicato": "", 
215     #"fret": "", 
216     #"string": "", 
217     #"hammer-on": "", 
218     #"pull-off": "", 
219     #"bend": "", 
220     #"tap": "", 
221     #"heel": "", 
222     #"toe": "", 
223     #"fingernails": ""
224     ##### ARTICULATIONS
225     "accent": "accent", 
226     "strong-accent": "marcato", 
227     "staccato": "staccato", 
228     "tenuto": "tenuto", 
229     #"detached-legato": "", 
230     "staccatissimo": "staccatissimo", 
231     #"spiccato": "", 
232     #"scoop": "", 
233     #"plop": "", 
234     #"doit": "", 
235     #"falloff": "",
236     "breath-mark": "breathe", 
237     #"caesura": "caesura", 
238     #"stress": "", 
239     #"unstress": ""
240 }
241
242 def musicxml_articulation_to_lily_event(mxl_event):
243     ev = musicexp.ArticulationEvent ()
244     tp = articulations_dict.get (mxl_event.get_name ())
245     if not tp:
246         return
247     
248     ev.type = tp
249
250     # Some articulations use the type attribute, other the placement...
251     dir = None
252     if hasattr (mxl_event, 'type'):
253         dir = musicxml_direction_to_indicator (mxl_event.type)
254     if hasattr (mxl_event, 'placement'):
255         dir = musicxml_direction_to_indicator (mxl_event.placement)
256     if dir:
257         ev.force_direction = dir
258     return ev
259
260
261 def musicxml_direction_to_lily( n ):
262     # TODO: Handle the <staff> element!
263     res = []
264     dirtype = n.get_maybe_exist_typed_child (musicxml.DirType)
265     if not dirtype: 
266       return res
267
268     for entry in dirtype.get_all_children ():
269         if entry.get_name () == "dynamics":
270             for dynentry in entry.get_all_children ():
271                 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp", 
272                     "f", "ff", "fff", "ffff", "fffff", "ffffff", 
273                     "mp", "mf", "sf", "sfp", "sfpp", "fp", 
274                     "rf", "rfz", "sfz", "sffz", "fz" )
275                 if not dynentry.get_name() in dynamics_available: 
276                     continue
277                 event = musicexp.DynamicsEvent ()
278                 event.type = dynentry.get_name ()
279                 res.append (event)
280       
281         if entry.get_name() == "wedge":
282             if hasattr (entry, 'type'):
283                 wedgetype = entry.type;
284                 wedgetypeval = {"crescendo" : 1, "decrescendo" : -1, 
285                                 "diminuendo" : -1, "stop" : 0 }.get (wedgetype)
286                 # Really check for != None, becaus otherwise 0 will also cause 
287                 # the code to be executed!
288                 if wedgetypeval != None:
289                     event = musicexp.HairpinEvent (wedgetypeval)
290                     res.append (event)
291
292     return res
293
294 instrument_drumtype_dict = {
295     'Acoustic Snare Drum': 'acousticsnare',
296     'Side Stick': 'sidestick',
297     'Open Triangle': 'opentriangle',
298     'Mute Triangle': 'mutetriangle',
299     'Tambourine': 'tambourine'
300 }
301
302 def musicxml_note_to_lily_main_event (n):
303     pitch  = None
304     duration = None
305         
306     mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
307     event = None
308     if mxl_pitch:
309         pitch = musicxml_pitch_to_lily (mxl_pitch)
310         event = musicexp.NoteEvent()
311         event.pitch = pitch
312
313         acc = n.get_maybe_exist_named_child ('accidental')
314         if acc:
315             # let's not force accs everywhere. 
316             event.cautionary = acc.editorial
317         
318     elif n.get_maybe_exist_typed_child (musicxml.Rest):
319         event = musicexp.RestEvent()
320     elif n.instrument_name:
321         event = musicexp.NoteEvent ()
322         drum_type = instrument_drumtype_dict.get (n.instrument_name)
323         if drum_type:
324             event.drum_type = drum_type
325         else:
326             n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
327             event.drum_type = 'acousticsnare'
328     
329     if not event:
330         n.message ("cannot find suitable event")
331
332     event.duration = musicxml_duration_to_lily (n)
333     return event
334
335
336 ## todo
337 class NegativeSkip:
338     def __init__ (self, here, dest):
339         self.here = here
340         self.dest = dest
341
342 class LilyPondVoiceBuilder:
343     def __init__ (self):
344         self.elements = []
345         self.pending_dynamics = []
346         self.end_moment = Rational (0)
347         self.begin_moment = Rational (0)
348         self.pending_multibar = Rational (0)
349
350     def _insert_multibar (self):
351         r = musicexp.MultiMeasureRest ()
352         r.duration = musicexp.Duration()
353         r.duration.duration_log = 0
354         r.duration.factor = self.pending_multibar
355         self.elements.append (r)
356         self.begin_moment = self.end_moment
357         self.end_moment = self.begin_moment + self.pending_multibar
358         self.pending_multibar = Rational (0)
359         
360     def add_multibar_rest (self, duration):
361         self.pending_multibar += duration
362         
363         
364     def add_music (self, music, duration):
365         assert isinstance (music, musicexp.Music)
366         if self.pending_multibar > Rational (0):
367             self._insert_multibar ()
368
369         self.elements.append (music)
370         self.begin_moment = self.end_moment
371         self.end_moment = self.begin_moment + duration 
372
373         # Insert all pending dynamics right after the note/rest:
374         if duration > Rational (0):
375             for d in self.pending_dynamics:
376                 self.elements.append (d)
377             self.pending_dynamics = []
378
379     def add_dynamics (self, dynamic):
380         # store the dynamic item(s) until we encounter the next note/rest:
381         self.pending_dynamics.append (dynamic)
382
383     def add_bar_check (self, number):
384         b = musicexp.BarCheck ()
385         b.bar_number = number
386         self.add_music (b, Rational (0))
387
388     def jumpto (self, moment):
389         current_end = self.end_moment + self.pending_multibar
390         diff = moment - current_end
391         
392         if diff < Rational (0):
393             print 'Negative skip', diff
394             diff = Rational (0)
395
396         if diff > Rational (0):
397             skip = musicexp.SkipEvent()
398             skip.duration.duration_log = 0
399             skip.duration.factor = diff
400
401             evc = musicexp.EventChord ()
402             evc.elements.append (skip)
403             self.add_music (evc, diff)
404                 
405     def last_event_chord (self, starting_at):
406
407         value = None
408         if (self.elements
409             and isinstance (self.elements[-1], musicexp.EventChord)
410             and self.begin_moment == starting_at):
411             value = self.elements[-1]
412         else:
413             self.jumpto (starting_at)
414             value = None
415
416         return value
417         
418     def correct_negative_skip (self, goto):
419         self.end_moment = goto
420         self.begin_moment = goto
421         evc = musicexp.EventChord ()
422         self.elements.append (evc)
423         
424 def musicxml_voice_to_lily_voice (voice):
425     tuplet_events = []
426     modes_found = {}
427
428     voice_builder = LilyPondVoiceBuilder()
429
430     for n in voice._elements:
431         if n.get_name () == 'forward':
432             continue
433
434         if isinstance (n, musicxml.Direction):
435             for a in musicxml_direction_to_lily (n):
436                 voice_builder.add_dynamics (a)
437             continue
438         
439         if not n.get_maybe_exist_named_child ('chord'):
440             try:
441                 voice_builder.jumpto (n._when)
442             except NegativeSkip, neg:
443                 voice_builder.correct_negative_skip (n._when)
444                 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
445             
446         if isinstance (n, musicxml.Attributes):
447             if n.is_first () and n._measure_position == Rational (0):
448                 try:
449                     number = int (n.get_parent ().number)
450                 except ValueError:
451                     number = 0
452                 
453                 voice_builder.add_bar_check (number)
454             for a in musicxml_attributes_to_lily (n):
455                 voice_builder.add_music (a, Rational (0))
456             continue
457
458         if not n.__class__.__name__ == 'Note':
459             print 'not a Note or Attributes?', n
460             continue
461
462         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
463         if (rest
464             and rest.is_whole_measure ()):
465
466             voice_builder.add_multibar_rest (n._duration)
467             continue
468
469         if n.is_first () and n._measure_position == Rational (0):
470             try: 
471                 num = int (n.get_parent ().number)
472             except ValueError:
473                 num = 0
474             voice_builder.add_bar_check (num)
475         
476         main_event = musicxml_note_to_lily_main_event (n)
477
478         if hasattr (main_event, 'drum_type') and main_event.drum_type:
479             modes_found['drummode'] = True
480
481
482         ev_chord = voice_builder.last_event_chord (n._when)
483         if not ev_chord: 
484             ev_chord = musicexp.EventChord()
485             voice_builder.add_music (ev_chord, n._duration)
486
487         ev_chord.append (main_event)
488         
489         notations = n.get_maybe_exist_typed_child (musicxml.Notations)
490         tuplet_event = None
491         span_events = []
492         
493         # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
494         # +tied | +slur | +tuplet | glissando | slide | 
495         #    ornaments | technical | articulations | dynamics |
496         #    +fermata | arpeggiate | non-arpeggiate | 
497         #    accidental-mark | other-notation
498         if notations:
499             if notations.get_tuplet():
500                 tuplet_event = notations.get_tuplet()
501                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
502                 frac = (1,1)
503                 if mod:
504                     frac = mod.get_fraction ()
505                 
506                 tuplet_events.append ((ev_chord, tuplet_event, frac))
507
508             slurs = [s for s in notations.get_named_children ('slur')
509                 if s.get_type () in ('start','stop')]
510             if slurs:
511                 if len (slurs) > 1:
512                     print 'more than 1 slur?'
513
514                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
515                 ev_chord.append (lily_ev)
516
517             mxl_tie = notations.get_tie ()
518             if mxl_tie and mxl_tie.type == 'start':
519                 ev_chord.append (musicexp.TieEvent ())
520                 
521             fermatas = notations.get_named_children ('fermata')
522             for a in fermatas:
523                 ev = musicxml_fermata_to_lily_event (a);
524                 if ev: 
525                     ev_chord.append (ev)
526                 
527             # Articulations can contain the following child elements:
528             #         accent | strong-accent | staccato | tenuto |
529             #         detached-legato | staccatissimo | spiccato |
530             #         scoop | plop | doit | falloff | breath-mark | 
531             #         caesura | stress | unstress
532             # Technical can contain the following child elements:
533             #         up-bow | down-bow | harmonic | open-string |
534             #         thumb-position | fingering | pluck | double-tongue |
535             #         triple-tongue | stopped | snap-pizzicato | fret |
536             #         string | hammer-on | pull-off | bend | tap | heel |
537             #         toe | fingernails | other-technical
538             # Ornaments can contain the following child elements:
539             #         trill-mark | turn | delayed-turn | inverted-turn |
540             #         shake | wavy-line | mordent | inverted-mordent | 
541             #         schleifer | tremolo | other-ornament, accidental-mark
542             ornaments = notations.get_named_children ('ornaments')
543             for a in ornaments:
544                 for ch in a.get_named_children ('tremolo'):
545                     ev = musicxml_tremolo_to_lily_event (ch)
546                     if ev: 
547                         ev_chord.append (ev)
548
549             ornaments += notations.get_named_children ('articulations')
550             ornaments += notations.get_named_children ('technical')
551
552             for a in ornaments:
553                 for ch in a.get_all_children ():
554                     ev = musicxml_articulation_to_lily_event (ch)
555                     if ev: 
556                         ev_chord.append (ev)
557
558             dynamics = notations.get_named_children ('dynamics')
559             for a in dynamics:
560                 for ch in a.get_all_children ():
561                     ev = musicxml_dynamics_to_lily_event (ch)
562                     if ev:
563                         ev_chord.append (ev)
564
565         mxl_beams = [b for b in n.get_named_children ('beam')
566                      if (b.get_type () in ('begin', 'end')
567                          and b.is_primary ())] 
568         if mxl_beams:
569             beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
570             if beam_ev:
571                 ev_chord.append (beam_ev)
572             
573         if tuplet_event:
574             mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
575             frac = (1,1)
576             if mod:
577                 frac = mod.get_fraction ()
578                 
579             tuplet_events.append ((ev_chord, tuplet_event, frac))
580
581     ## force trailing mm rests to be written out.   
582     voice_builder.add_music (musicexp.EventChord (), Rational (0))
583     
584     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
585
586     seq_music = musicexp.SequentialMusic()
587
588     if 'drummode' in modes_found.keys ():
589         ## \key <pitch> barfs in drummode.
590         ly_voice = [e for e in ly_voice
591                     if not isinstance(e, musicexp.KeySignatureChange)]
592     
593     seq_music.elements = ly_voice
594
595     
596     
597     if len (modes_found) > 1:
598        print 'Too many modes found', modes_found.keys ()
599
600     return_value = seq_music
601     for mode in modes_found.keys ():
602         v = musicexp.ModeChangingMusicWrapper()
603         v.element = return_value
604         v.mode = mode
605         return_value = v
606     
607     return return_value
608
609
610 def musicxml_id_to_lily (id):
611     digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
612               'Six', 'Seven', 'Eight', 'Nine', 'Ten']
613     
614     for digit in digits:
615         d = digits.index (digit)
616         id = re.sub ('%d' % d, digit, id)
617
618     id = re.sub  ('[^a-zA-Z]', 'X', id)
619     return id
620
621
622 def musicxml_pitch_to_lily (mxl_pitch):
623     p = musicexp.Pitch()
624     p.alteration = mxl_pitch.get_alteration ()
625     p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
626     p.octave = mxl_pitch.get_octave () - 4
627     return p
628
629 def voices_in_part (part):
630     """Return a Name -> Voice dictionary for PART"""
631     part.interpret ()
632     part.extract_voices ()
633     voice_dict = part.get_voices ()
634
635     return voice_dict
636
637 def voices_in_part_in_parts (parts):
638     """return a Part -> Name -> Voice dictionary"""
639     return dict([(p, voices_in_part (p)) for p in parts])
640
641
642 def get_all_voices (parts):
643     all_voices = voices_in_part_in_parts (parts)
644
645     all_ly_voices = {}
646     for p, name_voice in all_voices.items ():
647
648         part_ly_voices = {}
649         for n, v in name_voice.items ():
650             progress ("Converting to LilyPond expressions...")
651             part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
652
653         all_ly_voices[p] = part_ly_voices
654         
655     return all_ly_voices
656
657
658 def option_parser ():
659     p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
660                              version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
661                                       +
662 _ ("""This program is free software.  It is covered by the GNU General Public
663 License and you are welcome to change it and/or distribute copies of it
664 under certain conditions.  Invoke as `%s --warranty' for more
665 information.""") % 'lilypond'
666 + """
667 Copyright (c) 2005--2007 by
668     Han-Wen Nienhuys <hanwen@xs4all.nl> and
669     Jan Nieuwenhuizen <janneke@gnu.org>
670 """),
671                              description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
672     p.add_option ('-v', '--verbose',
673                   action="store_true",
674                   dest='verbose',
675                   help=_ ("be verbose"))
676
677     p.add_option ('', '--lxml',
678                   action="store_true",
679                   default=False,
680                   dest="use_lxml",
681                   help=_ ("Use lxml.etree; uses less memory and cpu time."))
682     
683     p.add_option ('-o', '--output',
684                   metavar=_ ("FILE"),
685                   action="store",
686                   default=None,
687                   type='string',
688                   dest='output_name',
689                   help=_ ("set output filename to FILE"))
690     p.add_option_group ('bugs',
691                         description=(_ ("Report bugs via")
692                                      + ''' http://post.gmane.org/post.php'''
693                                      '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
694     return p
695
696 def music_xml_voice_name_to_lily_name (part, name):
697     str = "Part%sVoice%s" % (part.id, name)
698     return musicxml_id_to_lily (str) 
699
700 def print_voice_definitions (printer, part_list, voices):
701     part_dict={}
702     for (part, nv_dict) in voices.items():
703         part_dict[part.id] = (part, nv_dict)
704
705     for part in part_list:
706         (part, nv_dict) = part_dict.get (part.id, (None, {}))
707         for (name, (voice, mxlvoice)) in nv_dict.items ():
708             k = music_xml_voice_name_to_lily_name (part, name)
709             printer.dump ('%s = ' % k)
710             voice.print_ly (printer)
711             printer.newline()
712
713             
714 def uniq_list (l):
715     return dict ([(elt,1) for elt in l]).keys ()
716     
717 def print_score_setup (printer, part_list, voices):
718     part_dict = dict ([(p.id, p) for p in voices.keys ()]) 
719
720     printer ('<<')
721     printer.newline ()
722     for part_definition in part_list:
723         part_name = part_definition.id
724         part = part_dict.get (part_name)
725         if not part:
726             print 'unknown part in part-list:', part_name
727             continue
728
729         nv_dict = voices.get (part)
730         staves = reduce (lambda x,y: x+ y,
731                 [mxlvoice._staves.keys ()
732                  for (v, mxlvoice) in nv_dict.values ()],
733                 [])
734
735         if len (staves) > 1:
736             staves = uniq_list (staves)
737             staves.sort ()
738             printer ('\\context PianoStaff << ')
739             printer.newline ()
740             
741             for s in staves:
742                 staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
743                         for (voice_name, (v, mxlvoice)) in nv_dict.items ()
744                         if mxlvoice._start_staff == s]
745                 
746                 printer ('\\context Staff = "%s" << ' % s)
747                 printer.newline ()
748                 for v in staff_voices:
749                     printer ('\\context Voice = "%s"  \\%s' % (v,v))
750                     printer.newline ()
751                 printer ('>>')
752                 printer.newline ()
753                 
754             printer ('>>')
755             printer.newline ()
756             
757         else:
758             printer ('\\new Staff <<')
759             printer.newline ()
760             for (n,v) in nv_dict.items ():
761
762                 n = music_xml_voice_name_to_lily_name (part, n) 
763                 printer ('\\context Voice = "%s"  \\%s' % (n,n))
764             printer ('>>')
765             printer.newline ()
766             
767     printer ('>>')
768     printer.newline ()
769
770 def print_ly_preamble (printer, filename):
771     printer.dump_version ()
772     printer.print_verbatim ('%% automatically converted from %s\n' % filename)
773
774 def read_musicxml (filename, use_lxml):
775     if use_lxml:
776         import lxml.etree
777         
778         tree = lxml.etree.parse (filename)
779         mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
780         return mxl_tree
781     else:
782         from xml.dom import minidom, Node
783         
784         doc = minidom.parse(filename)
785         node = doc.documentElement
786         return musicxml.minidom_demarshal_node (node)
787
788     return None
789
790
791 def convert (filename, options):
792     progress ("Reading MusicXML from %s ..." % filename)
793     
794     tree = read_musicxml (filename, options.use_lxml)
795
796     part_list = []
797     id_instrument_map = {}
798     if tree.get_maybe_exist_typed_child (musicxml.Part_list):
799         mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
800         part_list = mxl_pl.get_named_children ("score-part")
801         
802     parts = tree.get_typed_children (musicxml.Part)
803     voices = get_all_voices (parts)
804
805     if not options.output_name:
806         options.output_name = os.path.basename (filename) 
807         options.output_name = os.path.splitext (options.output_name)[0]
808
809
810     defs_ly_name = options.output_name + '-defs.ly'
811     driver_ly_name = options.output_name + '.ly'
812
813     printer = musicexp.Output_printer()
814     progress ("Output to `%s'" % defs_ly_name)
815     printer.set_file (open (defs_ly_name, 'w'))
816
817     print_ly_preamble (printer, filename)
818     print_voice_definitions (printer, part_list, voices)
819     
820     printer.close ()
821     
822     
823     progress ("Output to `%s'" % driver_ly_name)
824     printer = musicexp.Output_printer()
825     printer.set_file (open (driver_ly_name, 'w'))
826     print_ly_preamble (printer, filename)
827     printer.dump (r'\include "%s"' % defs_ly_name)
828     print_score_setup (printer, part_list, voices)
829     printer.newline ()
830
831     return voices
832
833
834 def main ():
835     opt_parser = option_parser()
836
837     (options, args) = opt_parser.parse_args ()
838     if not args:
839         opt_parser.print_usage()
840         sys.exit (2)
841
842     voices = convert (args[0], options)
843
844 if __name__ == '__main__':
845     main()