3 # midi2ly.py -- LilyPond midi import script
5 # This file is part of LilyPond, the GNU music typesetter.
7 # Copyright (C) 1998--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
8 # Jan Nieuwenhuizen <janneke@gnu.org>
10 # LilyPond is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
15 # LilyPond is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
38 ################################################################
43 scale_steps = [0, 2, 4, 5, 7, 9, 11]
51 start_quant_clocks = 0
53 duration_quant_clocks = 0
54 allowed_tuplet_clocks = []
57 ################################################################
60 program_name = sys.argv[0]
61 program_version = '@TOPLEVEL_VERSION@'
63 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
64 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
66 errorport = sys.stderr
69 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
73 ly.encoded_write (sys.stdout, '''
80 ''' % ( _ ('Copyright (c) %s by') % '1998--2015',
82 _ ('Distributed under terms of the GNU General Public License.'),
83 _ ('It comes with NO WARRANTY.')))
86 ly.encoded_write (errorport, s + '\n')
89 progress (_ ("warning: ") + s)
92 progress (_ ("error: ") + s)
93 raise Exception (_ ("Exiting... "))
96 if global_options.debug:
97 progress ("debug: " + s)
99 def system (cmd, ignore_error = 0):
100 return ly.system (cmd, ignore_error=ignore_error)
102 def strip_extension (f, ext):
103 (p, e) = os.path.splitext (f)
110 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
111 def __init__ (self, clocks):
113 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
115 def dur_num_den (self, clocks):
116 for i in range (len (allowed_tuplet_clocks)):
117 if clocks == allowed_tuplet_clocks[i]:
118 return global_options.allowed_tuplets[i]
120 dur = 0; num = 1; den = 1;
121 g = gcd (clocks, clocks_per_1)
123 (dur, num) = (clocks_per_1 / g, clocks / g)
124 if not dur in self.allowed_durs:
125 dur = 4; num = clocks; den = clocks_per_4
126 return (dur, num, den)
132 elif self.num == 3 and self.dur != 1:
133 s = '%d.' % (self.dur / 2)
135 s = '%d*%d' % (self.dur, self.num)
137 s = '%d*%d/%d' % (self.dur, self.num, self.den)
139 global reference_note
140 reference_note.duration = self
144 def compare (self, other):
145 return self.clocks - other.clocks
154 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
155 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
156 alteration_names = ('eses', 'es', '', 'is' , 'isis')
157 def __init__ (self, clocks, pitch, velocity):
159 self.velocity = velocity
162 self.duration = Duration (clocks)
163 (self.octave, self.notename, self.alteration) = self.o_n_a ()
167 # minor scale: la-la (= + 5) '''
169 n = self.names[(self.pitch) % 12]
170 a = self.alterations[(self.pitch) % 12]
172 key = global_options.key
177 a = - self.alterations[(self.pitch) % 12]
180 # By tradition, all scales now consist of a sequence
181 # of 7 notes each with a distinct name, from amongst
182 # a b c d e f g. But, minor scales have a wide
183 # second interval at the top - the 'leading note' is
184 # sharped. (Why? it just works that way! Anything
185 # else doesn't sound as good and isn't as flexible at
186 # saying things. In medieval times, scales only had 6
187 # notes to avoid this problem - the hexachords.)
189 # So, the d minor scale is d e f g a b-flat c-sharp d
190 # - using d-flat for the leading note would skip the
191 # name c and duplicate the name d. Why isn't c-sharp
192 # put in the key signature? Tradition. (It's also
193 # supposedly based on the Pythagorean theory of the
194 # cycle of fifths, but that really only applies to
195 # major scales...) Anyway, g minor is g a b-flat c d
196 # e-flat f-sharp g, and all the other flat minor keys
197 # end up with a natural leading note. And there you
200 # John Sankey <bf250@freenet.carleton.ca>
202 # Let's also do a-minor: a b c d e f gis a
206 o = self.pitch / 12 - 4
210 if (key.sharps == 0 and key.flats == 0
211 and n == 5 and a == -1):
214 elif key.flats == 1 and n == 1 and a == -1:
217 elif key.flats == 2 and n == 4 and a == -1:
220 elif key.sharps == 5 and n == 4 and a == 0:
223 elif key.sharps == 6 and n == 1 and a == 0:
226 elif key.sharps == 7 and n == 5 and a == 0:
230 if key.flats >= 6 and n == 6 and a == 0:
231 n = 0; a = -1; o = o + 1
233 if key.flats >= 7 and n == 2 and a == 0:
237 if key.sharps >= 3 and n == 3 and a == 0:
240 if key.sharps >= 4 and n == 0 and a == 0:
241 n = 6; a = 1; o = o - 1
246 s = chr ((self.notename + 2) % 7 + ord ('a'))
247 return 'Note(%s %s)' % (s, self.duration.dump ())
249 def dump (self, dump_dur=True):
250 global reference_note
251 s = chr ((self.notename + 2) % 7 + ord ('a'))
252 s = s + self.alteration_names[self.alteration + 2]
253 if global_options.absolute_pitches:
256 delta = self.pitch - reference_note.pitch
257 commas = sign (delta) * (abs (delta) / 12)
259 * (self.notename - reference_note.notename) + 7)
261 or ((self.notename == reference_note.notename)
262 and (abs (delta) > 4) and (abs (delta) < 12))):
263 commas = commas + sign (delta)
268 s = s + "," * -commas
271 and (self.duration.compare (reference_note.duration)
272 or global_options.explicit_durations)):
273 s = s + self.duration.dump ()
275 # Chords need to handle their reference duration themselves
277 reference_note = self
284 def __init__ (self, num, den):
289 def bar_clocks (self):
290 return clocks_per_1 * self.num / self.den
293 return 'Time(%d/%d)' % (self.num, self.den)
298 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
301 def __init__ (self, seconds_per_1):
303 self.seconds_per_1 = seconds_per_1
306 return 'Tempo(%d)' % self.bpm ()
309 return 4 * 60 / self.seconds_per_1
312 return '\n ' + '\\tempo 4 = %d ' % (self.bpm ()) + '\n '
315 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
316 def __init__ (self, type):
320 return 'Clef(%s)' % self.clefs[self.type]
323 return '\n \\clef %s\n ' % self.clefs[self.type]
326 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
327 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
329 def __init__ (self, sharps, flats, minor):
336 global_options.key = self
339 if self.sharps and self.flats:
343 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
345 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
348 name = chr ((k + 2) % 7 + ord ('a'))
350 name = chr ((k + 2) % 7 + ord ('a'))
352 # fis cis gis dis ais eis bis
353 sharps = (2, 4, 6, 1, 3, 5, 7)
354 # bes es as des ges ces fes
355 flats = (6, 4, 2, 7, 5, 3, 1)
358 if flats[k] <= self.flats:
361 if sharps[k] <= self.sharps:
365 name = name + Note.alteration_names[a + 2]
373 return '\n\n ' + s + '\n '
381 'SEQUENCE_TRACK_NAME',
391 if ((' ' <= chr <= '~') or chr in ['\n','\r']):
396 def __init__ (self, type, text):
399 self.text =''.join(map(self._text_only, text))
402 # urg, we should be sure that we're in a lyrics staff
404 if self.type == midi.LYRIC:
405 s = '"%s"' % self.text
406 d = Duration (self.clocks)
407 if (global_options.explicit_durations
408 or d.compare (reference_note.duration)):
409 s = s + Duration (self.clocks).dump ()
411 elif (self.text.strip ()
412 and self.type == midi.SEQUENCE_TRACK_NAME
413 and not self.text == 'control track'
414 and not self.track.lyrics_p_):
415 text = self.text.replace ('(MIDI)', '').strip ()
417 s = '\n \\set Staff.instrumentName = "%(text)s"\n ' % locals ()
418 elif self.text.strip ():
419 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
423 return 'Text(%d=%s)' % (self.type, self.text)
425 def get_voice (channel, music):
426 debug ('channel: ' + str (channel) + '\n')
427 return unthread_notes (music)
430 def __init__ (self, number):
434 def add (self, event):
435 self.events.append (event)
436 def get_voice (self):
438 self.music = self.parse ()
439 return get_voice (self.number, self.music)
446 for e in self.events:
449 if start_quant_clocks:
450 t = quantise_clocks (t, start_quant_clocks)
452 if (e[1][0] == midi.NOTE_OFF
453 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0)):
454 debug ('%d: NOTE OFF: %s' % (t, e[1][1]))
456 debug (' ...treated as OFF')
457 end_note (pitches, notes, t, e[1][1])
459 elif e[1][0] == midi.NOTE_ON:
460 if not pitches.has_key (e[1][1]):
461 debug ('%d: NOTE ON: %s' % (t, e[1][1]))
462 pitches[e[1][1]] = (t, e[1][2])
466 # all include ALL_NOTES_OFF
467 elif (e[1][0] >= midi.ALL_SOUND_OFF
468 and e[1][0] <= midi.POLY_MODE_ON):
470 end_note (pitches, notes, t, i)
472 elif e[1][0] == midi.META_EVENT:
473 if e[1][1] == midi.END_OF_TRACK:
475 end_note (pitches, notes, t, i)
478 elif e[1][1] == midi.SET_TEMPO:
479 (u0, u1, u2) = map (ord, e[1][2])
480 us_per_4 = u2 + 256 * (u1 + 256 * u0)
481 seconds_per_1 = us_per_4 * 4 / 1e6
482 music.append ((t, Tempo (seconds_per_1)))
483 elif e[1][1] == midi.TIME_SIGNATURE:
484 (num, dur, clocks4, count32) = map (ord, e[1][2])
486 music.append ((t, Time (num, den)))
487 elif e[1][1] == midi.KEY_SIGNATURE:
488 (alterations, minor) = map (ord, e[1][2])
491 if alterations < 127:
494 flats = 256 - alterations
496 k = Key (sharps, flats, minor)
497 if not t and global_options.key:
498 # At t == 0, a set --key overrides us
499 k = global_options.key
500 music.append ((t, k))
502 # ugh, must set key while parsing
503 # because Note init uses key
504 # Better do Note.calc () at dump time?
505 global_options.key = k
507 elif (e[1][1] == midi.LYRIC
508 or (global_options.text_lyrics
509 and e[1][1] == midi.TEXT_EVENT)):
510 self.lyrics_p_ = True
512 last_lyric.clocks = t - last_time
513 music.append ((last_time, last_lyric))
515 last_lyric = Text (midi.LYRIC, e[1][2])
517 elif (e[1][1] >= midi.SEQUENCE_NUMBER
518 and e[1][1] <= midi.CUE_POINT):
519 text = Text (e[1][1], e[1][2])
521 music.append ((t, text))
522 if (text.type == midi.SEQUENCE_TRACK_NAME):
523 self.name = text.text
525 if global_options.verbose:
526 sys.stderr.write ("SKIP: %s\n" % `e`)
528 if global_options.verbose:
529 sys.stderr.write ("SKIP: %s\n" % `e`)
532 # last_lyric.clocks = t - last_time
534 last_lyric.clocks = clocks_per_4
535 music.append ((last_time, last_lyric))
540 if i < len (music) and notes[0][0] >= music[i][0]:
543 music.insert (i, notes[0])
547 class Track (Channel):
549 Channel.__init__ (self, None)
552 self.lyrics_p_ = False
553 def _add (self, event):
554 self.events.append (event)
555 def add (self, event, channel=None):
559 self.channels[channel] = self.channels.get (channel, Channel (channel))
560 self.channels[channel].add (event)
561 def get_voices (self):
562 return ([self.get_voice ()]
563 + [self.channels[k].get_voice ()
564 for k in sorted (self.channels.keys ())])
566 def create_track (events):
570 if data[0] > 0x7f and data[0] < 0xf0:
571 channel = data[0] & 0x0f
572 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
573 track.add (e, channel)
578 def quantise_clocks (clocks, quant):
579 q = int (clocks / quant) * quant
581 for tquant in allowed_tuplet_clocks:
582 if int (clocks / tquant) * tquant == clocks:
584 if 2 * (clocks - q) > quant:
588 def end_note (pitches, notes, t, e):
590 (lt, vel) = pitches[e]
600 if duration_quant_clocks:
601 d = quantise_clocks (d, duration_quant_clocks)
603 d = duration_quant_clocks
606 (lt, Note (d, e, vel)))
611 def unthread_notes (channel):
620 if (e[1].__class__ == Note
621 and ((t == start_busy_t
622 and e[1].clocks + t == end_busy_t)
623 or t >= end_busy_t)):
626 end_busy_t = t + e[1].clocks
627 elif (e[1].__class__ == Time
628 or e[1].__class__ == Key
629 or e[1].__class__ == Text
630 or e[1].__class__ == Tempo):
634 threads.append (thread)
649 def dump_skip (skip, clocks):
650 return skip + Duration (clocks).dump () + ' '
659 if i.__class__ == Note:
664 s = s + dump (notes[0])
665 elif len (notes) > 1:
666 global reference_note
667 reference_dur = reference_note.duration
669 s = s + notes[0].dump (dump_dur=False)
672 s = s + i.dump (dump_dur=False)
674 if (r.duration.compare (reference_dur)
675 or global_options.explicit_durations):
676 s = s + r.duration.dump ()
681 def dump_bar_line (last_bar_t, t, bar_count):
683 bar_t = time.bar_clocks ()
684 if t - last_bar_t >= bar_t:
685 bar_count = bar_count + (t - last_bar_t) / bar_t
687 if t - last_bar_t == bar_t:
688 s = '\n | %% %(bar_count)d\n ' % locals ()
691 # urg, this will barf at meter changes
692 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
694 return (s, last_bar_t, bar_count)
697 def dump_voice (thread, skip):
698 global reference_note, time
699 ref = Note (0, 4*12, 0)
700 if not reference_note:
703 ref.duration = reference_note.duration
710 if last_e and last_e[0] == e[0]:
714 chs.append ((last_e[0], ch))
721 chs.append ((last_e[0], ch))
731 i = lines[-1].rfind ('\n') + 1
732 if len (lines[-1][i:]) > LINE_BELL:
737 if bar_max and t > time.bar_clocks () * bar_max:
738 d = time.bar_clocks () * bar_max - last_t
739 lines[-1] = lines[-1] + dump_skip (skip, d)
741 errorport.write ('BUG: time skew')
743 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
746 if bar_max and bar_count > bar_max:
749 lines[-1] = lines[-1] + s
750 lines[-1] = lines[-1] + dump_chord (ch[1])
754 if i.clocks > clocks:
759 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
761 lines[-1] = lines[-1] + s
763 return '\n '.join (lines) + '\n'
765 def number2ascii (i):
770 s = '%c' % (m + ord ('A')) + s
774 def get_track_name (i):
775 return 'track' + number2ascii (i)
777 def get_channel_name (i):
778 return 'channel' + number2ascii (i)
780 def get_voice_name (i, zero_too_p=False):
782 return 'voice' + number2ascii (i)
785 def lst_append (lst, x):
789 def get_voice_layout (average_pitch):
791 for i in range (len (average_pitch)):
792 d[average_pitch[i]] = lst_append (d.get (average_pitch[i], []), i)
793 s = list (reversed (sorted (average_pitch)))
794 non_empty = len (filter (lambda x: x, s))
795 names = ['One', 'Two']
797 names = ['One', 'Three', 'Four', 'Two']
798 layout = map (lambda x: '', range (len (average_pitch)))
799 for i, n in zip (s, names):
808 def dump_track (track, n):
810 track_name = get_track_name (n)
812 average_pitch = track_average_pitch (track)
813 voices = len (filter (lambda x: x, average_pitch[1:]))
814 clef = get_best_clef (average_pitch[0])
818 for channel in track:
820 channel_name = get_channel_name (c)
822 for voice in channel:
823 voice_name = get_voice_name (v)
824 voice_id = track_name + channel_name + voice_name
825 item = voice_first_item (voice)
827 if item and item.__class__ == Note:
829 if global_options.skip:
831 s += '%(voice_id)s = ' % locals ()
832 if not global_options.absolute_pitches:
834 elif item and item.__class__ == Text:
836 s += '%(voice_id)s = \\lyricmode ' % locals ()
839 s += '%(voice_id)s = ' % locals ()
841 if not n and not vv and global_options.key:
842 s += global_options.key.dump ()
843 if average_pitch[vv+1] and voices > 1:
844 vl = get_voice_layout (average_pitch[1:])[vv]
846 s += ' \\voice' + vl + '\n'
848 if not global_options.quiet:
849 warning (_ ('found more than 5 voices on a staff, expect bad output'))
850 s += ' ' + dump_voice (voice, skip)
855 s += '%(track_name)s = <<\n' % locals ()
858 s += clef.dump () + '\n'
862 for channel in track:
864 channel_name = get_channel_name (c)
866 for voice in channel:
867 voice_context_name = get_voice_name (vv, zero_too_p=True)
868 voice_name = get_voice_name (v)
871 voice_id = track_name + channel_name + voice_name
872 item = voice_first_item (voice)
874 if item and item.__class__ == Text:
876 s += ' \\context %(context)s = %(voice_context_name)s \\%(voice_id)s\n' % locals ()
880 def voice_first_item (voice):
882 if (event[1].__class__ == Note
883 or (event[1].__class__ == Text
884 and event[1].type == midi.LYRIC)):
888 def channel_first_item (channel):
889 for voice in channel:
890 first = voice_first_item (voice)
895 def track_first_item (track):
896 for channel in track:
897 first = channel_first_item (channel)
902 def track_average_pitch (track):
906 for channel in track:
907 for voice in channel:
911 if event[1].__class__ == Note:
914 p[v] += event[1].pitch
923 def get_best_clef (average_pitch):
925 if average_pitch <= 3*12:
927 elif average_pitch <= 5*12:
929 elif average_pitch >= 7*12:
934 def __init__ (self, track):
935 self.voices = track.get_voices ()
937 return dump_track (self.voices, i)
939 def convert_midi (in_file, out_file):
943 global clocks_per_1, clocks_per_4, key
944 global start_quant_clocks
945 global duration_quant_clocks
946 global allowed_tuplet_clocks
949 str = open (in_file, 'rb').read ()
950 clocks_max = bar_max * clocks_per_1 * 2
951 midi_dump = midi.parse (str, clocks_max)
953 clocks_per_1 = midi_dump[0][1]
954 clocks_per_4 = clocks_per_1 / 4
957 if global_options.start_quant:
958 start_quant_clocks = clocks_per_1 / global_options.start_quant
960 if global_options.duration_quant:
961 duration_quant_clocks = clocks_per_1 / global_options.duration_quant
963 allowed_tuplet_clocks = []
964 for (dur, num, den) in global_options.allowed_tuplets:
965 allowed_tuplet_clocks.append (clocks_per_1 / dur * num / den)
967 if global_options.verbose:
968 print 'allowed tuplet clocks:', allowed_tuplet_clocks
970 tracks = [create_track (t) for t in midi_dump[1]]
971 # urg, parse all global track events, such as Key first
972 # this fixes key in different voice/staff problem
978 voices = t.get_voices ()
979 if ((t.name and prev and prev.name)
980 and t.name.split (':')[0] == prev.name.split (':')[0]):
981 # staves[-1].voices += voices
982 # all global track events first
983 staves[-1].voices = ([staves[-1].voices[0]]
985 + staves[-1].voices[1:]
988 staves.append (Staff (t))
991 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
1003 \remove "Note_heads_engraver"
1004 \consists "Completion_heads_engraver"
1005 \remove "Rest_engraver"
1006 \consists "Completion_rest_engraver"
1011 for i in global_options.include_header:
1012 s += '\n%% included from %(i)s\n' % locals ()
1013 s += open (i).read ()
1018 for i, t in enumerate (staves):
1021 s += '\n\\score {\n <<\n'
1023 control_track = False
1025 for i, staff in enumerate (staves):
1026 track_name = get_track_name (i)
1027 item = track_first_item (staff.voices)
1028 staff_name = track_name
1030 if not i and not item and len (staves) > 1:
1031 control_track = track_name
1033 elif (item and item.__class__ == Note):
1036 s += ' \\context %(context)s=%(staff_name)s \\%(control_track)s\n' % locals ()
1037 elif item and item.__class__ == Text:
1040 s += ' \\context %(context)s=%(staff_name)s \\%(track_name)s\n' % locals ()
1048 if not global_options.quiet:
1049 progress (_ ("%s output to `%s'...") % ('LY', out_file))
1054 handle = open (out_file, 'w')
1060 def get_option_parser ():
1061 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
1062 description=_ ("Convert %s to LilyPond input.\n") % 'MIDI',
1063 add_help_option=False)
1065 p.add_option ('-a', '--absolute-pitches',
1066 action='store_true',
1067 help=_ ('print absolute pitches'))
1068 p.add_option ('-d', '--duration-quant',
1070 help=_ ('quantise note durations on DUR'))
1071 p.add_option ('-D', '--debug',
1072 action='store_true',
1073 help=_ ('debug printing'))
1074 p.add_option ('-e', '--explicit-durations',
1075 action='store_true',
1076 help=_ ('print explicit durations'))
1077 p.add_option('-h', '--help',
1079 help=_ ('show this help and exit'))
1080 p.add_option('-i', '--include-header',
1081 help=_ ('prepend FILE to output'),
1085 p.add_option('-k', '--key', help=_ ('set key: ALT=+sharps|-flats; MINOR=1'),
1086 metavar=_ ('ALT[:MINOR]'),
1088 p.add_option ('-o', '--output', help=_ ('write output to FILE'),
1091 p.add_option ('-p', '--preview', help=_ ('preview of first 4 bars'),
1092 action='store_true')
1093 p.add_option ('-q', '--quiet',
1094 action="store_true",
1095 help=_ ("suppress progress messages and warnings about excess voices"))
1096 p.add_option ('-s', '--start-quant',help= _ ('quantise note starts on DUR'),
1098 p.add_option ('-S', '--skip',
1099 action = "store_true",
1100 help =_ ("use s instead of r for rests"))
1101 p.add_option ('-t', '--allow-tuplet',
1102 metavar=_ ('DUR*NUM/DEN'),
1104 dest='allowed_tuplets',
1105 help=_ ('allow tuplet durations DUR*NUM/DEN'),
1107 p.add_option ('-V', '--verbose', help=_ ('be verbose'),
1108 action='store_true')
1109 p.version = 'midi2ly (LilyPond) @TOPLEVEL_VERSION@'
1110 p.add_option ('--version',
1112 help=_ ('show version number and exit'))
1113 p.add_option ('-w', '--warranty', help=_ ('show warranty and copyright'),
1114 action='store_true',)
1115 p.add_option ('-x', '--text-lyrics', help=_ ('treat every text as a lyric'),
1116 action='store_true')
1118 p.add_option_group (ly.display_encode (_ ('Examples')),
1120 $ midi2ly --key=-2:1 --duration-quant=32 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1122 p.add_option_group ('',
1124 _ ('Report bugs via %s')
1125 % 'http://post.gmane.org/post.php'
1126 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1132 opt_parser = get_option_parser ()
1133 (options, args) = opt_parser.parse_args ()
1135 if options.warranty:
1139 if not args or args[0] == '-':
1140 opt_parser.print_help ()
1141 ly.stderr_write ('\n%s: %s %s\n' % (program_name, _ ('error: '),
1142 _ ('no files specified on command line.')))
1145 if options.duration_quant:
1146 options.duration_quant = int (options.duration_quant)
1149 (alterations, minor) = map (int, (options.key + ':0').split (':'))[0:2]
1152 if alterations >= 0:
1153 sharps = alterations
1155 flats = - alterations
1156 options.key = Key (sharps, flats, minor)
1158 if options.start_quant:
1159 options.start_quant = int (options.start_quant)
1165 options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
1166 for a in options.allowed_tuplets]
1169 sys.stderr.write ('Allowed tuplets: %s\n' % `options.allowed_tuplets`)
1171 global global_options
1172 global_options = options
1177 files = do_options ()
1179 exts = ['.midi', '.mid', '.MID']
1183 g = strip_extension (g, e)
1184 if not os.path.exists (f):
1187 if os.path.exists (n):
1191 if not global_options.output:
1193 outbase = os.path.basename (g)
1194 o = outbase + '-midi.ly'
1195 elif (global_options.output[-1] == os.sep
1196 or os.path.isdir (global_options.output)):
1197 outdir = global_options.output
1198 outbase = os.path.basename (g)
1199 o = os.path.join (outdir, outbase + '-midi.ly')
1201 o = global_options.output
1202 (outdir, outbase) = os.path.split (o)
1204 if outdir and outdir != '.' and not os.path.exists (outdir):
1205 os.mkdir (outdir, 0777)
1209 if __name__ == '__main__':