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@'
22 sys.stderr.write ("This script needs Python 1.5.1\n")
32 current_voice_idx = -1
33 current_lyric_idx = -1
35 def select_voice (name):
36 if not voice_idx_dict.has_key (name):
38 voice_idx_dict[name] = len (voices) -1
39 __main__.current_voice_idx = voice_idx_dict[name]
42 # current_voice_idx >= 0
45 global_key = [0] * 7 # UGH
46 names = ["One", "Two", "Three"]
56 def __init__ (self, n, d = 1):
61 g = gcd (self.num, self.den)
62 self.num = self.num / g
63 self.den = self.den /g
68 def __sub__ (self, other):
73 def dump_header (outf,hdr):
74 outf.write ('\\header {')
78 outf.write ('\n%s = "%s";\n'% (k,hdr[k]))
81 def dump_lyrics (outf):
82 for i in range (len (lyrics)):
83 outf.write ("\nverse%s = \\lyrics {" % names [i])
84 outf.write ("\n" + lyrics [i])
87 def dump_voices (outf):
88 ks = voice_idx_dict.keys()
91 outf.write ("\nvoice%s = \\notes {" % k)
92 outf.write ("\n" + voices [voice_idx_dict[k]])
95 def dump_score (outf):
96 outf.write (r"""\score{
100 ks = voice_idx_dict.keys ();
103 outf.write ("\n \\context Staff=\"%s\" \\$voice%s " % (k,k))# ugh
104 for i in range (len (lyrics)):
106 if j >= len (voices):
108 outf.write ("\n \\context Lyrics=\"%s\" \\addlyrics \\$voice%s \\$verse%s " %
109 (names [i], names [j], names [i]))
111 dump_header (outf ,header)
117 def set_default_length (s):
118 m = re.search ('1/([0-9]+)', s)
120 __main__.default_len = string.atoi ( m.group (1))
122 def set_default_len_from_time_sig (s):
123 m = re.search ('([0-9]+)/([0-9]+)', s)
125 n = string.atoi (m.group (1))
126 d = string.atoi (m.group (2))
127 if (n * 1.0 )/(d * 1.0) < 0.75:
139 sys.stderr.write ("can't open file: %s\n" % f)
143 sys.stderr.write ("gulped emty file: %s\n" % f)
148 # pitch manipulation. Tuples are (name, alteration).
149 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
150 # pitch in semitones.
151 def semitone_pitch (tup):
161 p = p + t* 2 + tup[1]
164 def fifth_above_pitch (tup):
165 (n, a) = (tup[0] + 4, tup[1])
167 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
178 (t,a) = fifth_above_pitch (p)
179 if semitone_pitch((t,a)) % 12 == 0:
191 (t,a) = quart_above_pitch (p)
192 if semitone_pitch((t,a)) % 12 == 0:
198 def quart_above_pitch (tup):
199 (n, a) = (tup[0] + 3, tup[1])
201 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
209 intkey = (ord (k[0]) - ord('a') + 5) % 7
213 if k and k[0] == 'b':
216 elif k and k[0] == '#':
220 keytup = (intkey, intkeyacc)
222 sharp_key_seq = sharp_keys ()
223 flat_key_seq = flat_keys ()
227 if keytup in sharp_key_seq:
229 key_count = sharp_key_seq.index (keytup)
230 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
232 elif keytup in flat_key_seq:
234 key_count = flat_key_seq.index (keytup)
235 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
241 key_table[a] = key_table[a] + accsign
257 def try_parse_tuplet_begin (str, state):
258 if re.match ('\([0-9]', str):
261 state.parsing_tuplet = 1
263 voices_append ("\\times %s {" % tup_lookup[dig])
266 def try_parse_group_end (str, state):
267 if str and str[0] in HSPACE:
269 if state.parsing_tuplet:
270 state.parsing_tuplet = 0
274 def header_append (key, a):
276 if header.has_key (key):
277 s = header[key] + "\n"
280 def stuff_append (stuff, idx, a):
287 linelen = len (v) - string.rfind(v, '\n')
288 if linelen + len (a) > 80:
295 def voices_append(a):
296 if current_voice_idx < 0:
297 select_voice ('default')
299 stuff_append (voices, current_voice_idx, a)
301 def lyrics_append(a):
302 stuff_append (lyrics, current_lyric_idx, a)
305 def try_parse_header_line (ln):
306 m = re.match ('^(.): *(.*)$', ln)
311 a = re.sub ('"', '\\"', a)
317 # global_voice_stuff.append ('\\time %s;' % a)
318 set_default_len_from_time_sig (a)
319 voices_append ('\\time %s;' % a)
321 __main__.global_key =compute_key (a)# ugh.
322 voices_append ('\\key %s;' % a)
325 header ['origin'] = a
327 header ['crossRefNumber'] = a
331 header_append ('history', a)
335 header ['composer'] = a
337 header ['subtitle'] = a
339 set_default_length (ln)
341 a = re.sub (' .*$', '', a)
352 def pitch_to_mudela_name (name, acc):
362 return chr (name + ord('c')) + s * acc
364 def octave_to_mudela_quotes (o):
377 while str and str[0] in DIGITS:
378 durstr = durstr + str[0]
383 n =string.atoi (durstr)
387 def duration_to_mudela_duration (multiply_tup, defaultlen, dots):
390 # (num / den) / defaultlen < 1/base
391 while base * multiply_tup[0] < multiply_tup[1]:
395 return '%d%s' % ( base, '.'* dots)
399 self.next_articulation = ''
402 self.parsing_tuplet = 0
406 # return (str, num,den,dots)
407 def parse_duration (str, parser_state):
409 den = parser_state.next_den
410 parser_state.next_den = 1
412 (str, num) = parse_num (str)
417 while str[:1] == '/':
421 (str, d) =parse_num (str)
425 den = den * default_len
427 current_dots = parser_state.next_dots
428 parser_state.next_dots = 0
431 current_dots = current_dots + 1;
432 parser_state.next_den = parser_state.next_den * 2
437 parser_state.next_dots = parser_state.next_dots + 1
445 if num % multiplier == 0 and den % f == 0:
446 num = num / multiplier
448 current_dots = current_dots + d
450 return (str, num,den,current_dots)
453 def try_parse_rest (str, parser_state):
454 if not str or str[0] <> 'z':
459 (str, num,den,d) = parse_duration (str, parser_state)
460 voices_append ('r%s' % duration_to_mudela_duration ((num,den), default_len, d))
464 def try_parse_articulation (str, state):
467 state.next_articulation = state.next_articulation + '-.'
471 state.next_articulation = state.next_articulation + '-\\trill'
474 # s7m2 input doesnt care about spaces
475 if re.match('[ \t]*\(', str):
476 str = string.lstrip (str)
479 while str[:1] =='(' and str[1] not in DIGITS:
480 slur_begin = slur_begin + 1
481 state.next_articulation = state.next_articulation + '('
486 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
487 def try_parse_note (str, parser_state):
507 if str[0] in "ABCDEFG":
508 str = string.lower (str[0]) + str[1:]
513 if str[0] in "abcdefg":
514 notename = (ord(str[0]) - ord('a') + 5)%7
517 return str # failed; not a note!
522 while str[0] == '\'':
526 (str, num,den,current_dots) = parse_duration (str, parser_state)
529 if re.match('[ \t]*\)', str):
530 str = string.lstrip (str)
534 slur_end = slur_end + 1
539 voices_append ('%s' % ')' *slur_end )
540 voices_append ("%s%s%s" %
541 (pitch_to_mudela_name (notename, acc + global_key[notename]),
542 octave_to_mudela_quotes (octave),
543 duration_to_mudela_duration ((num,den), default_len, current_dots)))
544 if parser_state.next_articulation:
545 articulation = articulation + parser_state.next_articulation
546 parser_state.next_articulation = ''
548 voices_append (articulation)
550 voices_append ('%s' % '(' * slur_begin )
555 def junk_space (str):
556 while str and str[0] in '\t\n ':
562 def try_parse_guitar_chord (str, state):
566 while str and str[0] != '"':
573 state.next_articulation = "-\"%s\"" % gc
576 def try_parse_escape (str):
577 if not str or str [0] != '\\':
582 key_table = compute_key ()
587 # |] thin-thick double bar line
588 # || thin-thin double bar line
589 # [| thick-thin double bar line
592 # :: left-right repeat
608 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
610 def try_parse_bar (str,state):
613 # first try the longer one
615 if str[:trylen] and bar_dict.has_key (str[:trylen]):
617 bs = "\\bar \"%s\";" % bar_dict[s]
619 sys.stderr.write('Warning kludging for barline `%s\'\n' % s)
628 if state.parsing_tuplet:
629 state.parsing_tuplet =0
636 def try_parse_tie (str):
639 voices_append (' ~ ')
642 def try_parse_chord_delims (str):
658 voices_append ("\\spanrequest \\stop \"slur\"" * end);
662 def try_parse_grace_delims (str):
665 voices_append ('\\grace { ')
679 state = Parser_state ()
681 sys.stderr.write ("Parsing line ... ")
687 if not (lineno % happy_count):
688 sys.stderr.write ('[%d]'% lineno)
690 if re.match ('^[\t ]*(%.*)?$', ln):
692 m = re.match ('^(.*?)%(.*)$',ln)
694 voices_append ('%% %s\n' % m.group(2))
699 ln = try_parse_header_line (ln)
701 # Try nibbling characters off until the line doesn't change.
705 ln = try_parse_chord_delims (ln)
706 ln = try_parse_rest (ln, state)
707 ln = try_parse_articulation (ln,state)
708 ln = try_parse_note (ln, state)
709 ln = try_parse_bar (ln, state)
710 ln = try_parse_tie (ln)
711 ln = try_parse_escape (ln)
712 ln = try_parse_guitar_chord (ln, state)
713 ln = try_parse_tuplet_begin (ln, state)
714 ln = try_parse_group_end (ln, state)
715 ln = try_parse_grace_delims (ln)
719 msg = "%s: %d: Huh? Don't understand\n" % (fn, lineno)
720 sys.stderr.write (msg)
721 left = orig_ln[0:-len (ln)]
722 sys.stderr.write (left + '\n')
723 sys.stderr.write (' ' * len (left) + ln + '\n')
727 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
731 This is an ABC to mudela convertor.
733 Usage: abc2ly INPUTFILE
735 -h, --help this help.
736 -o, --output set output filename
742 (options, files) = getopt.getopt (sys.argv[1:], 'o:h', ['help', 'output='])
748 if o== '--help' or o == '-h':
750 if o == '--output' or o == '-o':
757 header['tagline'] = 'Lily was here %s -- Directly converted from ABC' % version
766 outf = open (out_filename, 'w')