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)
29 # Enhancements (Laura Conrad)
31 # Beaming now preserved between ABC and lilypond
35 # Multiple tunes in single file not supported
36 # Blank T: header lines should write score and open a new score
37 # Not all header fields supported
38 # ABC line breaks are ignored
39 # Block comments generate error and are ignored
40 # Postscript commands are ignored
41 # lyrics not resynchronized by line breaks (lyrics must fully match notes)
48 # - rewrite this to be like etf2ly.py
50 program_name = 'abc2ly'
51 version = '@TOPLEVEL_VERSION@'
52 if version == '@' + 'TOPLEVEL_VERSION' + '@':
53 version = '(unknown version)' # uGUHGUHGHGUGH
71 current_voice_idx = -1
72 current_lyric_idx = -1
77 global_key = [0] * 7 # UGH
78 names = ["One", "Two", "Three"]
86 if re.match('^treble', s):
88 if re.match ('^-8', s):
90 state.base_octave = -2
91 voices_append("\\clef \"G_8\";\n")
94 voices_append("\\clef treble;\n")
95 elif re.match('^alto', s):
97 state.base_octave = -1
98 voices_append ("\\clef alto;\n" )
99 elif re.match('^bass',s ):
101 state.base_octave = -2
102 voices_append ("\\clef bass;\n" )
105 def select_voice (name, rol):
106 if not voice_idx_dict.has_key (name):
107 state_list.append(Parser_state())
110 voice_idx_dict[name] = len (voices) -1
111 __main__.current_voice_idx = voice_idx_dict[name]
112 __main__.state = state_list[current_voice_idx]
114 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
118 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
122 if keyword == 'clef':
124 elif keyword == "name":
125 value = re.sub ('\\\\','\\\\\\\\', value)
126 voices_append ("\\property Staff.instrument = %s\n" % value )
127 __main__.part_names = 1
128 elif keyword == "sname" or keyword == "snm":
129 voices_append ("\\property Staff.instr = %s\n" % value )
137 def dump_header (outf,hdr):
138 outf.write ('\\header {\n')
142 outf.write ('\t%s = "%s";\n'% (k,hdr[k]))
145 def dump_lyrics (outf):
147 outf.write("\n\\score\n{\n \\context Lyrics\n <\n")
148 for i in range (len (lyrics)):
149 outf.write ( lyrics [i])
151 outf.write(" >\n \\paper{}\n}\n")
153 def dump_default_bar (outf):
154 outf.write ("\n\\property Score.defaultBarType=\"empty\"\n")
157 def dump_slyrics (outf):
158 ks = voice_idx_dict.keys()
161 for i in range (len(slyrics[voice_idx_dict[k]])):
162 outf.write ("\nwords%sV%d = \\lyrics {" % (k, i))
163 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
166 def dump_voices (outf):
167 ks = voice_idx_dict.keys()
170 outf.write ("\nvoice%s = \\notes {" % k)
171 dump_default_bar(outf)
172 outf.write ("\n" + voices [voice_idx_dict[k]])
175 def dump_score (outf):
176 outf.write (r"""\score{
180 ks = voice_idx_dict.keys ();
183 if k == 'default' and len (voice_idx_dict) > 1:
185 if len ( slyrics [voice_idx_dict[k]] ):
186 outf.write ("\n \\addlyrics")
187 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
189 outf.write ("\t \\$voicedefault\n")
190 outf.write ("\t \\$voice%s " % k)
191 outf.write ("\n\t}\n")
192 if len ( slyrics [voice_idx_dict[k]] ):
193 outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<\t" % k)
194 for i in range (len(slyrics[voice_idx_dict[k]])):
195 outf.write("\n\t { \\$words%sV%d }" % ( k, i) )
196 outf.write ( "\n\t>\n" )
198 outf.write ("\n\t\\paper {\n")
200 outf.write ("\t \\translator \n\t {\n")
201 outf.write ("\t\t\\StaffContext\n")
202 outf.write ("\t\t\\consists Staff_margin_engraver;\n")
203 outf.write ("\t }\n")
204 outf.write ("\t}\n\t\\midi {}\n}\n")
208 def set_default_length (s):
209 m = re.search ('1/([0-9]+)', s)
211 __main__.default_len = string.atoi ( m.group (1))
214 def set_default_len_from_time_sig (s):
215 m = re.search ('([0-9]+)/([0-9]+)', s)
217 n = string.atoi (m.group (1))
218 d = string.atoi (m.group (2))
219 if (n * 1.0 )/(d * 1.0) < 0.75:
220 __main__.default_len = 16
222 __main__.default_len = 8
231 sys.stderr.write ("can't open file: %s\n" % f)
235 sys.stderr.write ("gulped emty file: %s\n" % f)
240 # pitch manipulation. Tuples are (name, alteration).
241 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
242 # pitch in semitones.
243 def semitone_pitch (tup):
253 p = p + t* 2 + tup[1]
256 def fifth_above_pitch (tup):
257 (n, a) = (tup[0] + 4, tup[1])
259 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
270 (t,a) = fifth_above_pitch (p)
271 if semitone_pitch((t,a)) % 12 == 0:
283 (t,a) = quart_above_pitch (p)
284 if semitone_pitch((t,a)) % 12 == 0:
290 def quart_above_pitch (tup):
291 (n, a) = (tup[0] + 3, tup[1])
293 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
298 key_lookup = { # abc to lilypond key mode names
306 'mix' : 'mixolydian',
315 if k and k[0] == '#':
318 elif k and k[0] == 'b':
322 return '%s \\major' % key
325 if key_lookup.has_key(type):
326 return("%s \\%s" % ( key, key_lookup[type]))
327 sys.stderr.write("Unknown key type %s ignored\n" % type)
330 def shift_key (note, acc , shift):
331 s = semitone_pitch((note, acc))
332 s = (s + shift + 12) % 12
344 key_shift = { # semitone shifts for key mode names
358 intkey = (ord (k[0]) - ord('a') + 5) % 7
362 if k and k[0] == 'b':
365 elif k and k[0] == '#':
369 if k and key_shift.has_key(k):
370 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
371 keytup = (intkey, intkeyacc)
373 sharp_key_seq = sharp_keys ()
374 flat_key_seq = flat_keys ()
378 if keytup in sharp_key_seq:
380 key_count = sharp_key_seq.index (keytup)
381 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
383 elif keytup in flat_key_seq:
385 key_count = flat_key_seq.index (keytup)
386 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
392 key_table[a] = key_table[a] + accsign
407 def try_parse_tuplet_begin (str, state):
408 if re.match ('\([2-9]', str):
411 state.parsing_tuplet = string.atoi (dig[0])
413 voices_append ("\\times %s {" % tup_lookup[dig])
416 def try_parse_group_end (str, state):
417 if str and str[0] in HSPACE:
421 def header_append (key, a):
423 if header.has_key (key):
424 s = header[key] + "\n"
428 linelen = len (v) - string.rfind(v, '\n')
429 if linelen + len (a) > 80:
433 def stuff_append (stuff, idx, a):
437 stuff [idx] = wordwrap(a, stuff[idx])
441 def voices_append(a):
442 if current_voice_idx < 0:
443 select_voice ('default', '')
445 stuff_append (voices, current_voice_idx, a)
447 def lyrics_append(a):
448 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
449 a = re.sub ( '"', '\\"', a) # latex does not like naked "'s
450 a = '\t{ \\lyrics "' + a + '" }\n'
451 stuff_append (lyrics, current_lyric_idx, a)
453 # break lyrics to words and put "'s around words containing numbers and '"'s
458 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
462 word = re.sub('"', '\\"', word) # escape "
463 if re.match('.*[0-9"]', word):
464 word = re.sub('_', ' ', word) # _ causes probs inside ""
465 ret = ret + '\"' + word + '\" '
467 ret = ret + word + ' '
472 def slyrics_append(a):
473 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
474 a = re.sub ( '-', '- ', a) # split words with -
475 a = re.sub ( '\\\\- ', '-', a) # unless \-
476 a = re.sub ( '~', '_', a) # ~ to space('_')
477 a = re.sub ( '\*', '_ ', a) # * to to space
478 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
479 if re.match('.*[0-9"]', a): # put numbers and " into quoted string
481 a = re.sub ( '$', ' ', a) # insure space between lines
482 __main__.lyric_idx = lyric_idx + 1
483 if len(slyrics[current_voice_idx]) <= lyric_idx:
484 slyrics[current_voice_idx].append(a)
486 v = slyrics[current_voice_idx][lyric_idx]
487 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
490 def try_parse_header_line (ln, state):
491 m = re.match ('^([A-Za-z]): *(.*)$', ln)
497 a = re.sub('[ \t]*$','', a) #strip trailing blanks
498 if header.has_key('title'):
500 header['title'] = header['title'] + '\\\\\\\\' + a
505 if not state.common_time:
506 state.common_time = 1
507 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
510 if not state.common_time:
511 state.common_time = 1
512 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
514 if not length_specified:
515 set_default_len_from_time_sig (a)
516 voices_append ('\\time %s;' % a)
521 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
523 __main__.global_key =compute_key (m.group(1))# ugh.
524 voices_append ('\\key %s;' % lily_key(m.group(1)))
525 check_clef(m.group(2))
527 __main__.global_key =compute_key (a)# ugh.
528 voices_append ('\\key %s \\major;' % lily_key(a))
529 if g == 'O': # Origin
530 header ['origin'] = a
531 if g == 'X': # Reference Number
532 header ['crossRefNumber'] = a
535 if g == 'H': # History
536 header_append ('history', a)
539 if g == 'C': # Composer
540 if header.has_key('composer'):
542 header['composer'] = header['composer'] + '\\\\\\\\' + a
544 header['composer'] = a
546 header ['subtitle'] = a
547 if g == 'L': # Default note length
548 set_default_length (ln)
550 voice = re.sub (' .*$', '', a)
551 rest = re.sub ('^[^ \t]* *', '', a)
553 voices_append(state.next_bar)
555 select_voice (voice, rest)
558 if g == 'w': # vocals
564 # we use in this order specified accidental, active accidental for bar,
565 # active accidental for key
566 def pitch_to_mudela_name (name, acc, bar_acc, key):
579 return(chr (name + ord('c')) + s)
582 def octave_to_mudela_quotes (o):
595 while str and str[0] in DIGITS:
596 durstr = durstr + str[0]
601 n =string.atoi (durstr)
605 def duration_to_mudela_duration (multiply_tup, defaultlen, dots):
607 # (num / den) / defaultlen < 1/base
608 while base * multiply_tup[0] < multiply_tup[1]:
610 return '%d%s' % ( base, '.'* dots)
615 self.next_articulation = ''
619 self.parsing_tuplet = 0
626 # return (str, num,den,dots)
627 def parse_duration (str, parser_state):
629 den = parser_state.next_den
630 parser_state.next_den = 1
632 (str, num) = parse_num (str)
637 while str[:1] == '/':
641 (str, d) =parse_num (str)
645 den = den * default_len
647 current_dots = parser_state.next_dots
648 parser_state.next_dots = 0
649 if re.match ('[ \t]*[<>]', str):
650 while str[0] in HSPACE:
654 current_dots = current_dots + 1;
655 parser_state.next_den = parser_state.next_den * 2
660 parser_state.next_dots = parser_state.next_dots + 1
668 if num % multiplier == 0 and den % f == 0:
669 num = num / multiplier
671 current_dots = current_dots + d
673 return (str, num,den,current_dots)
676 def try_parse_rest (str, parser_state):
677 if not str or str[0] <> 'z' and str[0] <> 'x':
680 __main__.lyric_idx = -1
682 if parser_state.next_bar:
683 voices_append(parser_state.next_bar)
684 parser_state.next_bar = ''
692 (str, num,den,d) = parse_duration (str, parser_state)
693 voices_append ('%s%s' % (rest, duration_to_mudela_duration ((num,den), default_len, d)))
694 if parser_state.next_articulation:
695 voices_append (parser_state.next_articulation)
696 parser_state.next_articulation = ''
709 'J' : '', # ignore slide
710 'R' : '', # ignore roll
714 def try_parse_articulation (str, state):
716 while str and artic_tbl.has_key(str[:1]):
717 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
718 if not artic_tbl[str[:1]]:
719 sys.stderr.write("Warning: ignoring %s\n" % str[:1] )
725 # s7m2 input doesnt care about spaces
726 if re.match('[ \t]*\(', str):
727 str = string.lstrip (str)
730 while str[:1] =='(' and str[1] not in DIGITS:
731 slur_begin = slur_begin + 1
732 state.next_articulation = state.next_articulation + '('
738 # remember accidental for rest of bar
740 def set_bar_acc(note, octave, acc, state):
743 n_oct = note + octave * 7
744 state.in_acc[n_oct] = acc
746 # get accidental set in this bar or UNDEF if not set
747 def get_bar_acc(note, octave, state):
748 n_oct = note + octave * 7
749 if state.in_acc.has_key(n_oct):
750 return(state.in_acc[n_oct])
754 def clear_bar_acc(state):
755 for k in state.in_acc.keys():
760 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
761 def try_parse_note (str, parser_state):
780 octave = parser_state.base_octave
781 if str[0] in "ABCDEFG":
782 str = string.lower (str[0]) + str[1:]
787 if str[0] in "abcdefg":
788 notename = (ord(str[0]) - ord('a') + 5)%7
791 return str # failed; not a note!
794 __main__.lyric_idx = -1
796 if parser_state.next_bar:
797 voices_append(parser_state.next_bar)
798 parser_state.next_bar = ''
803 while str[0] == '\'':
807 (str, num,den,current_dots) = parse_duration (str, parser_state)
810 if re.match('[ \t]*\)', str):
811 str = string.lstrip (str)
815 slur_end = slur_end + 1
820 voices_append ('%s' % ')' *slur_end )
822 bar_acc = get_bar_acc(notename, octave, parser_state)
823 pit = pitch_to_mudela_name(notename, acc, bar_acc, global_key[notename])
824 oct = octave_to_mudela_quotes (octave)
825 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
829 voices_append ("%s%s%s%s" %
831 duration_to_mudela_duration ((num,den), default_len, current_dots)))
833 set_bar_acc(notename, octave, acc, parser_state)
834 if parser_state.next_articulation:
835 articulation = articulation + parser_state.next_articulation
836 parser_state.next_articulation = ''
838 voices_append (articulation)
840 if parser_state.parsing_tuplet:
841 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
842 if not parser_state.parsing_tuplet:
845 voices_append ('%s' % '(' * slur_begin )
850 def junk_space (str):
851 while str and str[0] in '\t\n ':
857 def try_parse_guitar_chord (str, state):
861 while str and str[0] != '"':
867 gc = re.sub('#', '\\#', gc) # escape '#'s
868 state.next_articulation = ("-\"%s\"" % gc) + state.next_articulation
871 def try_parse_escape (str):
872 if not str or str [0] != '\\':
877 key_table = compute_key ()
881 # |] thin-thick double bar line
882 # || thin-thin double bar line
883 # [| thick-thin double bar line
886 # :: left-right repeat
903 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
905 def try_parse_bar (str,state):
908 # first try the longer one
909 for trylen in [3,2,1]:
910 if str[:trylen] and bar_dict.has_key (str[:trylen]):
912 bs = "\\bar \"%s\";" % bar_dict[s]
914 sys.stderr.write('Warning kludging for barline `%s\'\n' % s)
919 state.next_bar = '|\n'
923 if bs <> None or state.next_bar != '':
924 if state.parsing_tuplet:
925 state.parsing_tuplet =0
934 def try_parse_tie (str):
937 voices_append (' ~ ')
940 def bracket_escape (str, state):
941 m = re.match ( '^([^\]]*)] *(.*)$', str)
945 try_parse_header_line (cmd, state)
948 def try_parse_chord_delims (str, state):
951 if re.match('[A-Z]:', str): # bracket escape
952 return bracket_escape(str, state)
954 voices_append(state.next_bar)
965 voices_append(state.next_bar)
981 voices_append ("\\spanrequest \\stop \"slur\"" * end);
985 def try_parse_grace_delims (str, state):
988 voices_append(state.next_bar)
991 voices_append ('\\grace { ')
1001 def parse_file (fn):
1005 select_voice('default', '')
1007 sys.stderr.write ("Line ... ")
1009 __main__.state = state_list[current_voice_idx]
1014 if not (lineno % happy_count):
1015 sys.stderr.write ('[%d]'% lineno)
1017 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1020 voices_append ('%% %s\n' % m.group(2))
1025 ln = try_parse_header_line (ln, state)
1027 # Try nibbling characters off until the line doesn't change.
1029 while ln != prev_ln:
1031 ln = try_parse_chord_delims (ln, state)
1032 ln = try_parse_rest (ln, state)
1033 ln = try_parse_articulation (ln,state)
1034 ln = try_parse_note (ln, state)
1035 ln = try_parse_bar (ln, state)
1036 ln = try_parse_tie (ln)
1037 ln = try_parse_escape (ln)
1038 ln = try_parse_guitar_chord (ln, state)
1039 ln = try_parse_tuplet_begin (ln, state)
1040 ln = try_parse_group_end (ln, state)
1041 ln = try_parse_grace_delims (ln, state)
1042 ln = junk_space (ln)
1045 msg = "%s: %d: Huh? Don't understand\n" % (fn, lineno)
1046 sys.stderr.write (msg)
1047 left = orig_ln[0:-len (ln)]
1048 sys.stderr.write (left + '\n')
1049 sys.stderr.write (' ' * len (left) + ln + '\n')
1053 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1057 Convert ABC to Mudela.
1059 Usage: abc2ly [OPTIONS]... ABC-FILE
1062 -h, --help this help
1063 -o, --output=FILE set output filename to FILE
1064 -v, --version version information
1066 This program converts ABC music files (see
1067 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) To LilyPond input.
1070 def print_version ():
1071 print r"""abc2ly (GNU lilypond) %s""" % version
1073 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1079 if o== '--help' or o == '-h':
1082 if o == '--version' or o == '-v':
1086 if o == '--output' or o == '-o':
1094 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1099 sys.stderr.write ('Parsing... [%s]\n' % f)
1102 if not out_filename:
1103 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1104 sys.stderr.write ('Ly output to: %s...' % out_filename)
1105 outf = open (out_filename, 'w')
1107 # dump_global (outf)
1108 dump_header (outf ,header)
1113 sys.stderr.write ('\n')