3 # once upon a rainy monday afternoon.
8 # ABC standard v1.6: http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt
10 # Enhancements (Roy R. Rankin)
12 # Header section moved to top of lilypond file
13 # handle treble, treble-8, alto, and bass clef
14 # Handle voices (V: headers) with clef and part names, multiple voices
15 # Handle w: lyrics with multiple verses
16 # Handle key mode names for minor, major, phrygian, ionian, locrian, aeolian,
17 # mixolydian, lydian, dorian
18 # Handle part names from V: header
19 # Tuplets handling fixed up
20 # Lines starting with |: not discarded as header lines
21 # Multiple T: and C: header entries handled
22 # Accidental maintained until next bar check
23 # Silent rests supported
24 # articulations fermata, upbow, downbow, ltoe, accent, tenuto supported
25 # Chord strings([-^]"string") can contain a '#'
26 # Header fields enclosed by [] in notes string processed
27 # W: words output after tune as abc2ps does it (they failed before)
31 # Multiple tunes in single file not supported
32 # Blank T: header lines should write score and open a new score
33 # Not all header fields supported
34 # Beaming not preserved between ABC and lilypond
35 # ABC line breaks are ignored
36 # Block comments generate error and are ignored
37 # Postscript commands are ignored
38 # lyrics not resynchronized by line breaks (lyrics must fully match notes)
44 program_name = 'abc2ly'
45 version = '@TOPLEVEL_VERSION@'
46 if version == '@' + 'TOPLEVEL_VERSION' + '@':
47 version = '1.2.9' # uGUHGUHGHGUGH
65 current_voice_idx = -1
66 current_lyric_idx = -1
70 global_key = [0] * 7 # UGH
71 names = ["One", "Two", "Three"]
79 if re.match('^treble', s):
81 if re.match ('^-8', s):
83 state.base_octave = -2
84 voices_append("\\clef \"G_8\";\n")
87 voices_append("\\clef treble;\n")
88 elif re.match('^alto', s):
90 state.base_octave = -1
91 voices_append ("\\clef alto;\n" )
92 elif re.match('^bass',s ):
94 state.base_octave = -2
95 voices_append ("\\clef bass;\n" )
98 def select_voice (name, rol):
99 if not voice_idx_dict.has_key (name):
100 state_list.append(Parser_state())
103 voice_idx_dict[name] = len (voices) -1
104 __main__.current_voice_idx = voice_idx_dict[name]
105 __main__.state = state_list[current_voice_idx]
107 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
111 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
115 if keyword == 'clef':
117 elif keyword == "name":
118 value = re.sub ('\\\\','\\\\\\\\', value)
119 voices_append ("\\property Staff.instrument = %s\n" % value )
120 __main__.part_names = 1
121 elif keyword == "sname" or keyword == "snm":
122 voices_append ("\\property Staff.instr = %s\n" % value )
130 def dump_header (outf,hdr):
131 outf.write ('\\header {\n')
135 outf.write ('\t%s = "%s";\n'% (k,hdr[k]))
138 def dump_lyrics (outf):
140 outf.write("\n\\score\n{\n \\context Lyrics\n <\n")
141 for i in range (len (lyrics)):
142 outf.write ( lyrics [i])
144 outf.write(" >\n \\paper{}\n}\n")
146 def dump_slyrics (outf):
147 ks = voice_idx_dict.keys()
150 for i in range (len(slyrics[voice_idx_dict[k]])):
151 outf.write ("\nwords%sV%d = \\lyrics {" % (k, i))
152 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
155 def dump_voices (outf):
156 ks = voice_idx_dict.keys()
159 outf.write ("\nvoice%s = \\notes {" % k)
160 outf.write ("\n" + voices [voice_idx_dict[k]])
163 def dump_score (outf):
164 outf.write (r"""\score{
168 ks = voice_idx_dict.keys ();
171 if k == 'default' and len (voice_idx_dict) > 1:
173 if len ( slyrics [voice_idx_dict[k]] ):
174 outf.write ("\n \\addlyrics")
175 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
177 outf.write ("\t \\$voicedefault\n")
178 outf.write ("\t \\$voice%s " % k)
179 outf.write ("\n\t}\n")
180 if len ( slyrics [voice_idx_dict[k]] ):
181 outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<\t" % k)
182 for i in range (len(slyrics[voice_idx_dict[k]])):
183 outf.write("\n\t { \\$words%sV%d }" % ( k, i) )
184 outf.write ( "\n\t>\n" )
186 outf.write ("\n\t\\paper {\n")
188 outf.write ("\t \\translator \n\t {\n")
189 outf.write ("\t\t\\StaffContext\n")
190 outf.write ("\t\t\\consists Staff_margin_engraver;\n")
191 outf.write ("\t }\n")
192 outf.write ("\t}\n\t\\midi {}\n}\n")
196 def set_default_length (s):
197 m = re.search ('1/([0-9]+)', s)
199 __main__.default_len = string.atoi ( m.group (1))
201 def set_default_len_from_time_sig (s):
202 m = re.search ('([0-9]+)/([0-9]+)', s)
204 n = string.atoi (m.group (1))
205 d = string.atoi (m.group (2))
206 if (n * 1.0 )/(d * 1.0) < 0.75:
207 __main__.default_len = 16
209 __main__.default_len = 8
218 sys.stderr.write ("can't open file: %s\n" % f)
222 sys.stderr.write ("gulped emty file: %s\n" % f)
227 # pitch manipulation. Tuples are (name, alteration).
228 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
229 # pitch in semitones.
230 def semitone_pitch (tup):
240 p = p + t* 2 + tup[1]
243 def fifth_above_pitch (tup):
244 (n, a) = (tup[0] + 4, tup[1])
246 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
257 (t,a) = fifth_above_pitch (p)
258 if semitone_pitch((t,a)) % 12 == 0:
270 (t,a) = quart_above_pitch (p)
271 if semitone_pitch((t,a)) % 12 == 0:
277 def quart_above_pitch (tup):
278 (n, a) = (tup[0] + 3, tup[1])
280 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
285 key_lookup = { # abc to lilypond key mode names
293 'mix' : 'mixolydian',
302 if k and k[0] == '#':
305 elif k and k[0] == 'b':
312 if key_lookup.has_key(type):
313 return("%s \\%s" % ( key, key_lookup[type]))
314 sys.stderr.write("Unknown key type %s ignored\n" % type)
317 def shift_key (note, acc , shift):
318 s = semitone_pitch((note, acc))
319 s = (s + shift + 12) % 12
331 key_shift = { # semitone shifts for key mode names
345 intkey = (ord (k[0]) - ord('a') + 5) % 7
349 if k and k[0] == 'b':
352 elif k and k[0] == '#':
356 if k and key_shift.has_key(k):
357 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
358 keytup = (intkey, intkeyacc)
360 sharp_key_seq = sharp_keys ()
361 flat_key_seq = flat_keys ()
365 if keytup in sharp_key_seq:
367 key_count = sharp_key_seq.index (keytup)
368 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
370 elif keytup in flat_key_seq:
372 key_count = flat_key_seq.index (keytup)
373 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
379 key_table[a] = key_table[a] + accsign
394 def try_parse_tuplet_begin (str, state):
395 if re.match ('\([2-9]', str):
398 state.parsing_tuplet = string.atoi (dig[0])
400 voices_append ("\\times %s {" % tup_lookup[dig])
403 def try_parse_group_end (str, state):
404 if str and str[0] in HSPACE:
408 def header_append (key, a):
410 if header.has_key (key):
411 s = header[key] + "\n"
415 linelen = len (v) - string.rfind(v, '\n')
416 if linelen + len (a) > 80:
420 def stuff_append (stuff, idx, a):
424 stuff [idx] = wordwrap(a, stuff[idx])
428 def voices_append(a):
429 if current_voice_idx < 0:
430 select_voice ('default', '')
432 stuff_append (voices, current_voice_idx, a)
434 def lyrics_append(a):
435 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
436 a = re.sub ( '"', '\\"', a) # latex does not like naked "'s
437 a = '\t{ \\lyrics "' + a + '" }\n'
438 stuff_append (lyrics, current_lyric_idx, a)
440 # break lyrics to words and put "'s around words containing numbers and '"'s
445 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
449 word = re.sub('"', '\\"', word) # escape "
450 if re.match('.*[0-9"]', word):
451 word = re.sub('_', ' ', word) # _ causes probs inside ""
452 ret = ret + '\"' + word + '\" '
454 ret = ret + word + ' '
459 def slyrics_append(a):
460 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
461 a = re.sub ( '-', '- ', a) # split words with -
462 a = re.sub ( '\\\\- ', '-', a) # unless \-
463 a = re.sub ( '~', '_', a) # ~ to space('_')
464 a = re.sub ( '\*', '_ ', a) # * to to space
465 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
466 if re.match('.*[0-9"]', a): # put numbers and " into quoted string
468 a = re.sub ( '$', ' ', a) # insure space between lines
469 __main__.lyric_idx = lyric_idx + 1
470 if len(slyrics[current_voice_idx]) <= lyric_idx:
471 slyrics[current_voice_idx].append(a)
473 v = slyrics[current_voice_idx][lyric_idx]
474 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
477 def try_parse_header_line (ln, state):
478 m = re.match ('^([A-Za-z]): *(.*)$', ln)
484 a = re.sub('[ \t]*$','', a) #strip trailing blanks
485 if header.has_key('title'):
487 header['title'] = header['title'] + '\\\\\\\\' + a
492 if not state.common_time:
493 state.common_time = 1
494 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
497 if not state.common_time:
498 state.common_time = 1
499 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
501 # global_voice_stuff.append ('\\time %s;' % a)
502 set_default_len_from_time_sig (a)
503 voices_append ('\\time %s;' % a)
508 __main__.global_key =compute_key (a)# ugh.
509 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
511 voices_append ('\\key %s;' % lily_key(m.group(1)))
512 check_clef(m.group(2))
514 voices_append ('\\key %s;' % lily_key(a))
515 if g == 'O': # Origin
516 header ['origin'] = a
517 if g == 'X': # Reference Number
518 header ['crossRefNumber'] = a
521 if g == 'H': # History
522 header_append ('history', a)
525 if g == 'C': # Composer
526 if header.has_key('composer'):
528 header['composer'] = header['composer'] + '\\\\\\\\' + a
530 header['composer'] = a
532 header ['subtitle'] = a
533 if g == 'L': # Default note length
534 set_default_length (ln)
536 voice = re.sub (' .*$', '', a)
537 rest = re.sub ('^[^ \t]* *', '', a)
539 voices_append(state.next_bar)
541 select_voice (voice, rest)
544 if g == 'w': # vocals
550 # we use in this order specified accidental, active accidental for bar,
551 # active accidental for key
552 def pitch_to_mudela_name (name, acc, bar_acc, key):
565 return(chr (name + ord('c')) + s)
568 def octave_to_mudela_quotes (o):
581 while str and str[0] in DIGITS:
582 durstr = durstr + str[0]
587 n =string.atoi (durstr)
591 def duration_to_mudela_duration (multiply_tup, defaultlen, dots):
594 # (num / den) / defaultlen < 1/base
595 while base * multiply_tup[0] < multiply_tup[1]:
599 return '%d%s' % ( base, '.'* dots)
604 self.next_articulation = ''
608 self.parsing_tuplet = 0
615 # return (str, num,den,dots)
616 def parse_duration (str, parser_state):
618 den = parser_state.next_den
619 parser_state.next_den = 1
621 (str, num) = parse_num (str)
626 while str[:1] == '/':
630 (str, d) =parse_num (str)
634 den = den * default_len
636 current_dots = parser_state.next_dots
637 parser_state.next_dots = 0
638 if re.match ('[ \t]*[<>]', str):
639 while str[0] in HSPACE:
643 current_dots = current_dots + 1;
644 parser_state.next_den = parser_state.next_den * 2
649 parser_state.next_dots = parser_state.next_dots + 1
657 if num % multiplier == 0 and den % f == 0:
658 num = num / multiplier
660 current_dots = current_dots + d
662 return (str, num,den,current_dots)
665 def try_parse_rest (str, parser_state):
666 if not str or str[0] <> 'z' and str[0] <> 'x':
669 __main__.lyric_idx = -1
671 if parser_state.next_bar:
672 voices_append(parser_state.next_bar)
673 parser_state.next_bar = ''
681 (str, num,den,d) = parse_duration (str, parser_state)
682 voices_append ('%s%s' % (rest, duration_to_mudela_duration ((num,den), default_len, d)))
683 if parser_state.next_articulation:
684 voices_append (parser_state.next_articulation)
685 parser_state.next_articulation = ''
698 'J' : '', # ignore slide
699 'R' : '', # ignore roll
703 def try_parse_articulation (str, state):
705 while str and artic_tbl.has_key(str[:1]):
706 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
707 if not artic_tbl[str[:1]]:
708 sys.stderr.write("Warning: ignoring %s\n" % str[:1] )
714 # s7m2 input doesnt care about spaces
715 if re.match('[ \t]*\(', str):
716 str = string.lstrip (str)
719 while str[:1] =='(' and str[1] not in DIGITS:
720 slur_begin = slur_begin + 1
721 state.next_articulation = state.next_articulation + '('
727 # remember accidental for rest of bar
729 def set_bar_acc(note, octave, acc, state):
732 n_oct = note + octave * 7
733 state.in_acc[n_oct] = acc
735 # get accidental set in this bar or UNDEF if not set
736 def get_bar_acc(note, octave, state):
737 n_oct = note + octave * 7
738 if state.in_acc.has_key(n_oct):
739 return(state.in_acc[n_oct])
743 def clear_bar_acc(state):
744 for k in state.in_acc.keys():
749 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
750 def try_parse_note (str, parser_state):
769 octave = parser_state.base_octave
770 if str[0] in "ABCDEFG":
771 str = string.lower (str[0]) + str[1:]
776 if str[0] in "abcdefg":
777 notename = (ord(str[0]) - ord('a') + 5)%7
780 return str # failed; not a note!
783 __main__.lyric_idx = -1
785 if parser_state.next_bar:
786 voices_append(parser_state.next_bar)
787 parser_state.next_bar = ''
792 while str[0] == '\'':
796 (str, num,den,current_dots) = parse_duration (str, parser_state)
799 if re.match('[ \t]*\)', str):
800 str = string.lstrip (str)
804 slur_end = slur_end + 1
809 voices_append ('%s' % ')' *slur_end )
811 bar_acc = get_bar_acc(notename, octave, parser_state)
812 pit = pitch_to_mudela_name(notename, acc, bar_acc, global_key[notename])
813 oct = octave_to_mudela_quotes (octave)
814 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
818 voices_append ("%s%s%s%s" %
820 duration_to_mudela_duration ((num,den), default_len, current_dots)))
822 set_bar_acc(notename, octave, acc, parser_state)
823 if parser_state.next_articulation:
824 articulation = articulation + parser_state.next_articulation
825 parser_state.next_articulation = ''
827 voices_append (articulation)
829 if parser_state.parsing_tuplet:
830 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
831 if not parser_state.parsing_tuplet:
834 voices_append ('%s' % '(' * slur_begin )
839 def junk_space (str):
840 while str and str[0] in '\t\n ':
846 def try_parse_guitar_chord (str, state):
850 while str and str[0] != '"':
856 gc = re.sub('#', '\\#', gc) # escape '#'s
857 state.next_articulation = ("-\"%s\"" % gc) + state.next_articulation
860 def try_parse_escape (str):
861 if not str or str [0] != '\\':
866 key_table = compute_key ()
870 # |] thin-thick double bar line
871 # || thin-thin double bar line
872 # [| thick-thin double bar line
875 # :: left-right repeat
891 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
893 def try_parse_bar (str,state):
896 # first try the longer one
898 if str[:trylen] and bar_dict.has_key (str[:trylen]):
900 bs = "\\bar \"%s\";" % bar_dict[s]
902 sys.stderr.write('Warning kludging for barline `%s\'\n' % s)
907 state.next_bar = '|\n'
911 if bs <> None or state.next_bar != '':
912 if state.parsing_tuplet:
913 state.parsing_tuplet =0
922 def try_parse_tie (str):
925 voices_append (' ~ ')
928 def bracket_escape (str, state):
929 m = re.match ( '^([^\]]*)] *(.*)$', str)
933 try_parse_header_line (cmd, state)
936 def try_parse_chord_delims (str, state):
939 if re.match('[A-Z]:', str): # bracket escape
940 return bracket_escape(str, state)
942 voices_append(state.next_bar)
953 voices_append(state.next_bar)
969 voices_append ("\\spanrequest \\stop \"slur\"" * end);
973 def try_parse_grace_delims (str, state):
976 voices_append(state.next_bar)
979 voices_append ('\\grace { ')
993 select_voice('default', '')
995 sys.stderr.write ("Line ... ")
997 __main__.state = state_list[current_voice_idx]
1002 if not (lineno % happy_count):
1003 sys.stderr.write ('[%d]'% lineno)
1005 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1008 voices_append ('%% %s\n' % m.group(2))
1013 ln = try_parse_header_line (ln, state)
1015 # Try nibbling characters off until the line doesn't change.
1017 while ln != prev_ln:
1019 ln = try_parse_chord_delims (ln, state)
1020 ln = try_parse_rest (ln, state)
1021 ln = try_parse_articulation (ln,state)
1022 ln = try_parse_note (ln, state)
1023 ln = try_parse_bar (ln, state)
1024 ln = try_parse_tie (ln)
1025 ln = try_parse_escape (ln)
1026 ln = try_parse_guitar_chord (ln, state)
1027 ln = try_parse_tuplet_begin (ln, state)
1028 ln = try_parse_group_end (ln, state)
1029 ln = try_parse_grace_delims (ln, state)
1030 ln = junk_space (ln)
1033 msg = "%s: %d: Huh? Don't understand\n" % (fn, lineno)
1034 sys.stderr.write (msg)
1035 left = orig_ln[0:-len (ln)]
1036 sys.stderr.write (left + '\n')
1037 sys.stderr.write (' ' * len (left) + ln + '\n')
1041 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1045 Convert ABC to Mudela.
1047 Usage: abc2ly [OPTION]... ABC-FILE
1050 -h, --help this help
1051 -o, --output=FILE set output filename to FILE
1052 -v, --version version information
1055 def print_version ():
1056 print r"""abc2ly (GNU lilypond) %s""" % version
1060 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1066 if o== '--help' or o == '-h':
1069 if o == '--version' or o == '-v':
1073 if o == '--output' or o == '-o':
1081 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1086 sys.stderr.write ('Parsing... [%s]\n' % f)
1089 if not out_filename:
1090 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1091 sys.stderr.write ('Ly output to: %s...' % out_filename)
1092 outf = open (out_filename, 'w')
1094 # dump_global (outf)
1095 dump_header (outf ,header)
1100 sys.stderr.write ('\n')