3 # info mostly taken from looking at files. See also
4 # http://www.cs.uu.nl/~hanwen/lily-devel/etf.html
19 # * slur/stem directions
20 # * voices (2nd half of frame?)
21 # * more intelligent lyrics
22 # * beams (better use autobeam?)
23 # * more robust: try entertainer.etf (freenote)
27 program_name = 'etf2ly'
28 version = '@TOPLEVEL_VERSION@'
29 if version == '@' + 'TOPLEVEL_VERSION' + '@':
30 version = '(unknown version)' # uGUHGUHGHGUGH
39 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble8vb', 'bass8vb', 'baritone']
42 return finale_clefs[fin]
45 return open (f).read ()
47 # notename 0 == central C
48 distances = [0, 2, 4, 5, 7, 9, 11, 12]
49 def semitones (name, acc):
50 return (name / 7 ) * 12 + distances[name % 7] + acc
52 # represent pitches as (notename, alteration), relative to C-major scale
53 def transpose(orig, delta):
57 old_pitch =semitones (oname, oacc)
58 delta_pitch = semitones (dname, dacc)
59 nname = (oname + dname)
61 new_pitch = semitones (nname, nacc)
63 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
69 # find transposition of C-major scale that belongs here.
70 def interpret_finale_key_sig (finale_id):
72 if 0 <= finale_id < 7:
74 p = transpose (p, (4,0)) # a fifth up
75 finale_id = finale_id - 1
76 elif 248 < finale_id <= 255:
77 while finale_id < 256:
78 p = transpose (p, (3,0))
79 finale_id = finale_id + 1
85 def find_scale (transposition):
86 cscale = map (lambda x: (x,0), range (0,7))
87 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
102 def rat_simplify (r):
113 def rat_multiply (a,b):
117 return rat_simplify ((x*p, y*q))
123 return rat_simplify ((x*q + p*y, y*q))
129 def rat_subtract (a,b ):
130 return rat_add (a, rat_neg (b))
132 def lily_notename (tuple2):
134 nn = chr ((n+ 2)%7 + ord ('a'))
149 def __init__ (self, number):
150 self.start_note = number
153 def append_finale (self, fin):
154 self.finale.append (fin)
157 n = self.finale[0][2]*self.finale[0][3]
158 d = self.finale[0][0]*self.finale[0][1]
159 return rat_simplify( (n, d))
161 def dump_start (self):
162 return '\\times %d/%d { ' % self.factor ()
167 def calculate (self, chords):
168 edu_left = self.finale[0][0] * self.finale[0][1]
170 startch = chords[self.start_note]
172 while c and edu_left:
175 c.chord_prefix = self.dump_start () + c.chord_prefix
178 edu_left = edu_left - c.EDU_duration ()
180 c.chord_suffix = c.chord_suffix+ self.dump_end ()
184 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
187 def __init__ (self, number):
191 def append_entry (self, finale_e):
192 self.finale.append (finale_e)
194 def calculate (self, chords):
195 startnote = self.finale[0][5]
196 endnote = self.finale[3][2]
198 cs = chords[startnote]
204 cs.note_suffix = '(' + cs.note_suffix
205 ce.note_prefix = ce.note_prefix + ')'
207 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
210 class Global_measure:
211 def __init__ (self, number):
214 self.keysignature = None
220 return `self.finale `
222 def set_timesig (self, finale):
223 (beats, fdur) = finale
224 (log, dots) = EDU_to_duration (fdur)
226 self.timesig = (beats, log)
231 def set_keysig (self, finale):
232 k = interpret_finale_key_sig (finale)
233 self.keysignature = k
234 self.scale = find_scale (k)
244 18: '"arp"' , # arpeggio
248 def __init__ (self, a,b, finale):
249 self.type = finale[0]
251 def calculate (self, chords):
252 c = chords[self.notenumber]
255 a = articulation_dict[self.type]
257 sys.stderr.write ("\nUnknown articulation no. %d on note no. %d" % (self.type, self.notenumber))
260 c.note_suffix = '-' + a + c.note_suffix
263 def __init__ (self, a,b , finale):
265 self.syllable = finale[1]
266 self.verse = finale[0]
267 def calculate (self, chords, lyrics):
268 self.chord = chords[self.chordnum]
271 def __init__ (self, number, body):
274 self.split_syllables ()
275 def split_syllables (self):
276 ss = re.split ('(-| +)', self.body)
282 septor = re.sub (" +", "", s)
283 septor = re.sub ("-", " -- ", septor)
284 syls[-1] = syls[-1] + septor
290 self.syllables = syls
295 for s in self.syllables[1:]:
296 line = line + ' ' + s
298 str = str + ' ' * 4 + line + '\n'
301 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self.number - 1) ,str)
306 def __init__(self, no):
308 self.frames = [0] * 4
312 self.global_measure = None
315 def add_finale_entry (self, entry):
316 self.finale.append (entry)
318 def calculate (self):
319 if len (self.finale) < 2:
320 sys.stderr.write ("Measure %d in staff %d has incomplete information.\n" % (self.number, self.staff.number))
327 self.clef = string.atoi (f0[0])
328 self.flags = string.atoi (f0[1])
329 fs = map (string.atoi, list (f0[2:]) + [f1[0]])
334 def __init__ (self, finale):
337 (number, start, end ) = finale
343 def set_measure (self, m):
346 def calculate (self):
350 for c in self.chords:
351 if c.grace and (lastch == None or (not lastch.grace)):
352 c.chord_prefix = r'\grace {' + c.chord_prefix
353 elif not c.grace and lastch and lastch.grace:
354 lastch.chord_suffix = lastch.chord_suffix + ' } '
361 str = '%% FR(%d)\n' % self.number
362 left = self.measure.global_measure.length ()
366 for c in self.chords:
367 add = c.ly_string () + ' '
368 if len (ln) + len(add) > 72:
369 str = str + ln + '\n'
372 left = rat_subtract (left, c.length ())
377 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
380 str = str + rat_to_lily_duration (left)
386 return chr ( i + ord ('A'))
389 def __init__ (self, number):
393 def get_measure (self, no):
394 if len (self.measures) <= no:
395 self.measures = self.measures + [None]* (1 + no - len (self.measures))
397 if self.measures[no] == None:
399 self.measures [no] =m
403 return self.measures[no]
405 return 'staff' + encodeint (self.number - 1)
406 def layerid (self, l):
407 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
409 def dump_time_key_sigs (self):
415 for m in self.measures[1:]:
421 if last_key <> g.keysignature:
422 e = e + "\\key %s \\major; " % lily_notename (g.keysignature)
423 last_key = g.keysignature
424 if last_time <> g.timesig :
425 e = e + "\\time %d/%d; " % g.timesig
426 last_time = g.timesig
427 if last_clef <> m.clef :
428 e = e + '\\clef %s;' % lily_clef (m.clef)
432 k = k +' ' + rat_to_lily_duration (gap) + '\n'
436 gap = rat_add (gap, g.length ())
439 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
447 for x in range (1,5): # 4 layers.
452 for m in self.measures[1:]:
461 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
463 laystr = laystr + fr.dump ()
465 gap = rat_add (gap, m.global_measure.length ())
469 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
473 str = str + self.dump_time_key_sigs ()
474 stafdef = '\\%sglobal' % self.staffid ()
476 stafdef = stafdef + ' \\' + i
479 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
480 (self.staffid (), self.staffid (), stafdef)
484 def EDU_to_duration (edu):
499 def rat_to_lily_duration (rat):
503 while d and d % 2 == 0:
504 basedur = basedur << 1
507 str = 's%d' % basedur
509 str = str + '*%d' % n
511 str = str + '/%d' % d
517 def __init__ (self, finale_entry):
520 self.finale = finale_entry
525 self.note_suffix = ''
526 self.chord_suffix = ''
527 self.chord_prefix = ''
534 return self.frame.measure
540 l = (1, self.duration[0])
542 d = 1 << self.duration[1]
544 dotfact = rat_subtract ((2,1), (1,d))
545 mylen = rat_multiply (dotfact, l)
548 mylen = rat_multiply (mylen, self.tuplet.factor())
552 return self.finale[0][0]
554 def EDU_duration (self):
555 return self.finale[0][3]
556 def set_duration (self):
557 self.duration = EDU_to_duration(self.EDU_duration ())
558 def calculate (self):
559 self.find_realpitch ()
562 flag = self.finale[0][5]
563 if Chord.GRACE_MASK & flag:
567 def find_realpitch (self):
569 ((no, prev, next, dur, pos, entryflag, extended, follow), notelist) = self.finale
571 meas = self.measure ()
573 if not meas or not meas.global_measure :
574 print 'note %d not in measure' % self.number ()
575 elif not meas.global_measure.scale:
576 print 'note %d: no scale in this measure.' % self.number ()
586 scale = meas.global_measure.scale
587 (sn, sa) =scale[rest % 7]
588 sn = sn + (rest - (rest%7)) + 7
590 self.pitches.append ((sn, acc))
591 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
593 self.chord_suffix = self.chord_suffix + ' ~ '
595 REST_MASK = 0x40000000L
596 TIE_START_MASK = 0x40000000L
597 GRACE_MASK = 0x00800000L
599 def ly_string (self):
604 if not (self.finale[0][5] & Chord.REST_MASK):
607 for p in self.pitches:
612 nn = lily_notename ((n,a))
625 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
628 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
629 s = self.note_prefix + s + self.note_suffix
630 if len (self.pitches) > 1:
633 s = self.chord_prefix + s + self.chord_suffix
636 GFre = re.compile(r"""^\^GF\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
637 BCre = re.compile (r"""^\^BC\(([0-9-]+)\) ([0-9-]+) .*$""")
638 eEre = re.compile(r"""^\^eE\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) \$([0-9A-Fa-f]+) ([0-9-]+) ([0-9-]+)""")
639 FRre = re.compile (r"""^\^FR\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
640 MSre = re.compile (r"""^\^MS\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
641 note_re = re.compile (r"""^ +([0-9-]+) \$([A-Fa-f0-9]+)""")
642 Sxre = re.compile (r"""^\^Sx\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
643 IMre = re.compile (r"""^\^IM\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
644 vere = re.compile(r"""^\^(ve|ch|se)\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
645 versere = re.compile(r"""^\^verse\(([0-9]+)\)(.*)\^end""")
647 TPre = re.compile(r"""^\^TP\(([0-9]+),([0-9]+)\) *([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
651 def __init__ (self, name):
652 self.measures = [None]
653 self.entries = [None]
656 self.tuplets = [None]
659 self.articulations = [None]
660 self.syllables = [None]
666 def get_global_measure (self, no):
667 if len (self.measures) <= no:
668 self.measures = self.measures + [None]* (1 + no - len (self.measures))
670 if self.measures[no] == None:
671 self.measures [no] = Global_measure (no)
673 return self.measures[no]
676 def get_staff(self,staffno):
677 if len (self.staffs) <= staffno:
678 self.staffs = self.staffs + [None] * (1 + staffno - len (self.staffs))
680 if self.staffs[staffno] == None:
681 self.staffs[staffno] = Staff (staffno)
683 return self.staffs[staffno]
686 def try_IS (self, l):
689 def try_BC (self, l):
692 bn = string.atoi (m.group (1))
693 where = string.atoi (m.group (2)) / 1024.0
698 (nil, num) = map (string.atoi, (m.groups ()[0:2]))
699 entries = map (string.atoi, (m.groups ()[2:]))
701 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
702 self.tuplets.append (Tuplet (num))
704 self.tuplets[-1].append_finale (entries)
706 def try_IM (self, l):
709 a = string.atoi (m.group (1))
710 b = string.atoi (m.group (2))
712 fin = map (string.atoi, m.groups ()[2:])
714 self.articulations.append (Articulation (a,b,fin))
716 def try_verse (self,l):
717 m = versere .match (l)
719 a = string.atoi (m.group (1))
722 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
723 body = re.sub ("\^[a-z]+", "", body)
724 self.verses.append (Verse (a, body))
730 a = string.atoi (m.group (1))
731 b = string.atoi (m.group (2))
733 fin = map (string.atoi, m.groups ()[2:])
735 self.syllables.append (Syllable (a,b,fin))
737 def try_eE (self, l):
741 (no, prev, next, dur, pos, entryflag, extended, follow) = tup
742 (no, prev, next, dur, pos,extended, follow) \
743 = tuple (map (string.atoi, [no,prev,next,dur,pos,extended,follow]))
745 entryflag = string.atol (entryflag,16)
746 if no > len (self.entries):
747 sys.stderr.write ("\nHuh? Entry number to large,\nexpected %d got %d. Filling with void entries.\n" % (len(self.entries), no ))
748 while len (self.entries) <> no:
749 c = ((len (self.entries), 0, 0, 0, 0, 0L, 0, 0), [])
750 self.entries.append (c)
752 current_entry = ((no, prev, next, dur, pos, entryflag, extended, follow), [])
753 self.entries.append (current_entry)
759 slurno = string.atoi (m.group (1))
761 if len (self.slurs) == slurno:
762 self.slurs.append (Slur (slurno))
764 params = list (m.groups ()[1:])
765 params = map (string.atoi, params)
766 self.slurs[-1].append_entry (params)
772 (staffno,measno) = m.groups ()[0:2]
773 s = string.atoi (staffno)
774 me = string.atoi (measno)
776 entry = m.groups () [2:]
777 st = self.get_staff (s)
778 meas = st.get_measure (me)
779 meas.add_finale_entry (entry)
785 (frameno, startnote, endnote, foo, bar) = m.groups ()
786 (frameno, startnote, endnote) = tuple (map (string.atoi, [frameno, startnote, endnote]))
787 if frameno > len (self.frames):
788 sys.stderr.write ("Frame no %d missing, filling up to %d\n" % (len(self.frames), frameno))
789 while frameno <> len (self.frames):
790 self.frames.append (Frame ((len (self.frames), 0,0) ))
792 self.frames.append (Frame ((frameno, startnote, endnote)))
795 def try_MS (self, l):
798 measno = string.atoi (m.group (1))
799 keynum = string.atoi (m.group (3))
800 meas =self. get_global_measure (measno)
801 meas.set_keysig (keynum)
803 beats = string.atoi (m.group (4))
804 beatlen = string.atoi (m.group (5))
805 meas.set_timesig ((beats, beatlen))
809 def try_note (self, l):
810 m = note_re.match (l)
812 (pitch, flag) = m.groups ()
813 pitch = string.atoi (pitch)
814 flag = string.atol (flag,16)
815 self.entries[-1][1].append ((pitch,flag))
817 def parse (self, name):
818 sys.stderr.write ('parsing ...')
821 gulp = open (name).read ()
823 gulp = re.sub ('[\n\r]+', '\n', gulp)
824 ls = string.split (gulp, '\n')
835 m = self.try_note (l)
845 m = self.try_verse (l)
847 sys.stderr.write ('processing ...')
850 self.unthread_entries ()
852 for st in self.staffs[1:]:
856 for m in st.measures[1:]:
860 m.global_measure = self.measures[mno]
863 frame_obj_list = [None]
864 for frno in m.frames:
865 fr = self.frames[frno]
866 frame_obj_list.append (fr)
868 m.frames = frame_obj_list
869 for fr in frame_obj_list[1:]:
875 fr.chords = self.get_thread (fr.start, fr.end)
880 for c in self.chords[1:]:
883 for f in self.frames[1:]:
886 for t in self.tuplets[1:]:
887 t.calculate (self.chords)
889 for s in self.slurs [1:]:
890 s.calculate (self.chords)
891 for s in self.articulations[1:]:
892 s.calculate (self.chords)
894 def get_thread (self, startno, endno):
897 c = self.chords[startno]
898 while c and c.number () <> endno:
910 for s in self.staffs[1:]:
912 str = str + '\n\n' + s.dump ()
913 staffs.append ('\\' + s.staffid ())
916 # should use \addlyrics ?
918 for v in self.verses[1:]:
921 if len (self.verses) > 1:
922 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
925 str = str + '\\score { < %s > } ' % string.join (staffs)
931 return 'ETF FILE %s %s' % (self.measures, self.entries)
933 def unthread_entries (self):
935 for e in self.entries[1:]:
936 self.chords.append (Chord (e))
938 for e in self.chords[1:]:
939 e.prev = self.chords[e.finale[0][1]]
940 e.next = self.chords[e.finale[0][2]]
948 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
952 Convert ETF to LilyPond.
954 Usage: etf2ly [OPTION]... ETF-FILE
958 -o, --output=FILE set output filename to FILE
959 -v, --version version information
961 Enigma Transport Format is a format used by Coda Music Technology's
962 Finale product. This program will convert a subset of ETF to a
963 ready-to-use lilypond file.
968 def print_version ():
969 print r"""etf2ly (GNU lilypond) %s""" % version
973 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
979 if o== '--help' or o == '-h':
982 if o == '--version' or o == '-v':
986 if o == '--output' or o == '-o':
994 # header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
999 sys.stderr.write ('Processing `%s\'\n' % f)
1001 if not out_filename:
1002 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1004 if out_filename == f:
1005 out_filename = os.path.basename (f + '.ly')
1007 sys.stderr.write ('Writing `%s\'' % out_filename)
1012 fo = open (out_filename, 'w')
1013 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)