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