3 # once upon a rainy monday afternoon.
8 # ABC standard v1.6: http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt
12 program_name = 'abc2ly'
13 version = '@TOPLEVEL_VERSION@'
14 if version == '@' + 'TOPLEVEL_VERSION' + '@':
25 sys.stderr.write ("This script needs Python 1.5.1\n")
35 current_voice_idx = -1
36 current_lyric_idx = -1
38 def select_voice (name):
39 if not voice_idx_dict.has_key (name):
41 voice_idx_dict[name] = len (voices) -1
42 __main__.current_voice_idx = voice_idx_dict[name]
45 # current_voice_idx >= 0
48 global_key = [0] * 7 # UGH
49 names = ["One", "Two", "Three"]
59 def __init__ (self, n, d = 1):
64 g = gcd (self.num, self.den)
65 self.num = self.num / g
66 self.den = self.den /g
71 def __sub__ (self, other):
76 def dump_header (outf,hdr):
77 outf.write ('\\header {')
81 outf.write ('\n%s = "%s";\n'% (k,hdr[k]))
84 def dump_lyrics (outf):
85 for i in range (len (lyrics)):
86 outf.write ("\nverse%s = \\lyrics {" % names [i])
87 outf.write ("\n" + lyrics [i])
90 def dump_voices (outf):
91 ks = voice_idx_dict.keys()
94 outf.write ("\nvoice%s = \\notes {" % k)
95 outf.write ("\n" + voices [voice_idx_dict[k]])
98 def dump_score (outf):
99 outf.write (r"""\score{
103 ks = voice_idx_dict.keys ();
106 outf.write ("\n \\context Staff=\"%s\" \\$voice%s " % (k,k))# ugh
107 for i in range (len (lyrics)):
109 if j >= len (voices):
111 outf.write ("\n \\context Lyrics=\"%s\" \\addlyrics \\$voice%s \\$verse%s " %
112 (names [i], names [j], names [i]))
114 dump_header (outf ,header)
120 def set_default_length (s):
121 m = re.search ('1/([0-9]+)', s)
123 __main__.default_len = string.atoi ( m.group (1))
125 def set_default_len_from_time_sig (s):
126 m = re.search ('([0-9]+)/([0-9]+)', s)
128 n = string.atoi (m.group (1))
129 d = string.atoi (m.group (2))
130 if (n * 1.0 )/(d * 1.0) < 0.75:
142 sys.stderr.write ("can't open file: %s\n" % f)
146 sys.stderr.write ("gulped emty file: %s\n" % f)
151 # pitch manipulation. Tuples are (name, alteration).
152 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
153 # pitch in semitones.
154 def semitone_pitch (tup):
164 p = p + t* 2 + tup[1]
167 def fifth_above_pitch (tup):
168 (n, a) = (tup[0] + 4, tup[1])
170 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
181 (t,a) = fifth_above_pitch (p)
182 if semitone_pitch((t,a)) % 12 == 0:
194 (t,a) = quart_above_pitch (p)
195 if semitone_pitch((t,a)) % 12 == 0:
201 def quart_above_pitch (tup):
202 (n, a) = (tup[0] + 3, tup[1])
204 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
212 intkey = (ord (k[0]) - ord('a') + 5) % 7
216 if k and k[0] == 'b':
219 elif k and k[0] == '#':
223 keytup = (intkey, intkeyacc)
225 sharp_key_seq = sharp_keys ()
226 flat_key_seq = flat_keys ()
230 if keytup in sharp_key_seq:
232 key_count = sharp_key_seq.index (keytup)
233 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
235 elif keytup in flat_key_seq:
237 key_count = flat_key_seq.index (keytup)
238 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
244 key_table[a] = key_table[a] + accsign
260 def try_parse_tuplet_begin (str, state):
261 if re.match ('\([0-9]', str):
264 state.parsing_tuplet = 1
266 voices_append ("\\times %s {" % tup_lookup[dig])
269 def try_parse_group_end (str, state):
270 if str and str[0] in HSPACE:
272 if state.parsing_tuplet:
273 state.parsing_tuplet = 0
277 def header_append (key, a):
279 if header.has_key (key):
280 s = header[key] + "\n"
283 def stuff_append (stuff, idx, a):
290 linelen = len (v) - string.rfind(v, '\n')
291 if linelen + len (a) > 80:
298 def voices_append(a):
299 if current_voice_idx < 0:
300 select_voice ('default')
302 stuff_append (voices, current_voice_idx, a)
304 def lyrics_append(a):
305 stuff_append (lyrics, current_lyric_idx, a)
308 def try_parse_header_line (ln):
309 m = re.match ('^(.): *(.*)$', ln)
314 a = re.sub ('"', '\\"', a)
320 # global_voice_stuff.append ('\\time %s;' % a)
321 set_default_len_from_time_sig (a)
322 voices_append ('\\time %s;' % a)
324 __main__.global_key =compute_key (a)# ugh.
325 voices_append ('\\key %s;' % a)
328 header ['origin'] = a
330 header ['crossRefNumber'] = a
334 header_append ('history', a)
338 header ['composer'] = a
340 header ['subtitle'] = a
342 set_default_length (ln)
344 a = re.sub (' .*$', '', a)
355 def pitch_to_mudela_name (name, acc):
365 return chr (name + ord('c')) + s * acc
367 def octave_to_mudela_quotes (o):
380 while str and str[0] in DIGITS:
381 durstr = durstr + str[0]
386 n =string.atoi (durstr)
390 def duration_to_mudela_duration (multiply_tup, defaultlen, dots):
393 # (num / den) / defaultlen < 1/base
394 while base * multiply_tup[0] < multiply_tup[1]:
398 return '%d%s' % ( base, '.'* dots)
402 self.next_articulation = ''
405 self.parsing_tuplet = 0
409 # return (str, num,den,dots)
410 def parse_duration (str, parser_state):
412 den = parser_state.next_den
413 parser_state.next_den = 1
415 (str, num) = parse_num (str)
420 while str[:1] == '/':
424 (str, d) =parse_num (str)
428 den = den * default_len
430 current_dots = parser_state.next_dots
431 parser_state.next_dots = 0
434 current_dots = current_dots + 1;
435 parser_state.next_den = parser_state.next_den * 2
440 parser_state.next_dots = parser_state.next_dots + 1
448 if num % multiplier == 0 and den % f == 0:
449 num = num / multiplier
451 current_dots = current_dots + d
453 return (str, num,den,current_dots)
456 def try_parse_rest (str, parser_state):
457 if not str or str[0] <> 'z':
462 (str, num,den,d) = parse_duration (str, parser_state)
463 voices_append ('r%s' % duration_to_mudela_duration ((num,den), default_len, d))
467 def try_parse_articulation (str, state):
470 state.next_articulation = state.next_articulation + '-.'
474 state.next_articulation = state.next_articulation + '-\\trill'
477 # s7m2 input doesnt care about spaces
478 if re.match('[ \t]*\(', str):
479 str = string.lstrip (str)
482 while str[:1] =='(' and str[1] not in DIGITS:
483 slur_begin = slur_begin + 1
484 state.next_articulation = state.next_articulation + '('
489 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
490 def try_parse_note (str, parser_state):
510 if str[0] in "ABCDEFG":
511 str = string.lower (str[0]) + str[1:]
516 if str[0] in "abcdefg":
517 notename = (ord(str[0]) - ord('a') + 5)%7
520 return str # failed; not a note!
525 while str[0] == '\'':
529 (str, num,den,current_dots) = parse_duration (str, parser_state)
532 if re.match('[ \t]*\)', str):
533 str = string.lstrip (str)
537 slur_end = slur_end + 1
542 voices_append ('%s' % ')' *slur_end )
543 voices_append ("%s%s%s" %
544 (pitch_to_mudela_name (notename, acc + global_key[notename]),
545 octave_to_mudela_quotes (octave),
546 duration_to_mudela_duration ((num,den), default_len, current_dots)))
547 if parser_state.next_articulation:
548 articulation = articulation + parser_state.next_articulation
549 parser_state.next_articulation = ''
551 voices_append (articulation)
553 voices_append ('%s' % '(' * slur_begin )
558 def junk_space (str):
559 while str and str[0] in '\t\n ':
565 def try_parse_guitar_chord (str, state):
569 while str and str[0] != '"':
576 state.next_articulation = "-\"%s\"" % gc
579 def try_parse_escape (str):
580 if not str or str [0] != '\\':
585 key_table = compute_key ()
590 # |] thin-thick double bar line
591 # || thin-thin double bar line
592 # [| thick-thin double bar line
595 # :: left-right repeat
611 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
613 def try_parse_bar (str,state):
616 # first try the longer one
618 if str[:trylen] and bar_dict.has_key (str[:trylen]):
620 bs = "\\bar \"%s\";" % bar_dict[s]
622 sys.stderr.write('Warning kludging for barline `%s\'\n' % s)
631 if state.parsing_tuplet:
632 state.parsing_tuplet =0
639 def try_parse_tie (str):
642 voices_append (' ~ ')
645 def try_parse_chord_delims (str):
661 voices_append ("\\spanrequest \\stop \"slur\"" * end);
665 def try_parse_grace_delims (str):
668 voices_append ('\\grace { ')
682 state = Parser_state ()
684 sys.stderr.write ("Line ... ")
690 if not (lineno % happy_count):
691 sys.stderr.write ('[%d]'% lineno)
693 if re.match ('^[\t ]*(%.*)?$', ln):
695 m = re.match ('^(.*?)%(.*)$',ln)
697 voices_append ('%% %s\n' % m.group(2))
702 ln = try_parse_header_line (ln)
704 # Try nibbling characters off until the line doesn't change.
708 ln = try_parse_chord_delims (ln)
709 ln = try_parse_rest (ln, state)
710 ln = try_parse_articulation (ln,state)
711 ln = try_parse_note (ln, state)
712 ln = try_parse_bar (ln, state)
713 ln = try_parse_tie (ln)
714 ln = try_parse_escape (ln)
715 ln = try_parse_guitar_chord (ln, state)
716 ln = try_parse_tuplet_begin (ln, state)
717 ln = try_parse_group_end (ln, state)
718 ln = try_parse_grace_delims (ln)
722 msg = "%s: %d: Huh? Don't understand\n" % (fn, lineno)
723 sys.stderr.write (msg)
724 left = orig_ln[0:-len (ln)]
725 sys.stderr.write (left + '\n')
726 sys.stderr.write (' ' * len (left) + ln + '\n')
730 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
734 Convert ABC to Mudela.
736 Usage: abc2ly [OPTION]... ABC-FILE
740 -o, --output=FILE set output filename to FILE
745 (options, files) = getopt.getopt (sys.argv[1:], 'o:h', ['help', 'output='])
751 if o== '--help' or o == '-h':
753 if o == '--output' or o == '-o':
760 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
765 sys.stderr.write ('Parsing... [%s]\n' % f)
769 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
770 sys.stderr.write ('Ly output to: %s...' % out_filename)
771 outf = open (out_filename, 'w')
777 sys.stderr.write ('\n')