lilypond-1.3.144
[lilypond.git] / scripts / etf2ly.py
blob563e0308dcb55dae5a4a54d3fb659cfeac1e3a0f
1 #!@PYTHON@
3 # info mostly taken from looking at files. See also
4 # http://www.cs.uu.nl/~hanwen/lily-devel/etf.html
6 # This supports
8 # * notes
9 # * rests
10 # * ties
11 # * slurs
12 # * lyrics
13 # * articulation
14 # * grace notes
15 # * tuplets
18 # todo:
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)
24 # * dynamics
25 # * automatic `deletion' of invalid items
29 program_name = 'etf2ly'
30 version = '@TOPLEVEL_VERSION@'
31 if version == '@' + 'TOPLEVEL_VERSION' + '@':
32 version = '(unknown version)' # uGUHGUHGHGUGH
34 import __main__
35 import getopt
36 import sys
37 import re
38 import string
39 import os
41 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
43 def lily_clef (fin):
44 try:
45 return finale_clefs[fin]
46 except IndexError:
47 sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
49 return 'treble'
53 def gulp_file(f):
54 return open (f).read ()
56 # notename 0 == central C
57 distances = [0, 2, 4, 5, 7, 9, 11, 12]
58 def semitones (name, acc):
59 return (name / 7 ) * 12 + distances[name % 7] + acc
61 # represent pitches as (notename, alteration), relative to C-major scale
62 def transpose(orig, delta):
63 (oname, oacc) = orig
64 (dname, dacc) = delta
66 old_pitch =semitones (oname, oacc)
67 delta_pitch = semitones (dname, dacc)
68 nname = (oname + dname)
69 nacc = oacc
70 new_pitch = semitones (nname, nacc)
72 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
74 return (nname, nacc)
78 # find transposition of C-major scale that belongs here.
79 def interpret_finale_key_sig (finale_id):
80 p = (0,0)
81 if 0 <= finale_id < 7:
82 while finale_id > 0:
83 p = transpose (p, (4,0)) # a fifth up
84 finale_id = finale_id - 1
85 elif 248 < finale_id <= 255:
86 while finale_id < 256:
87 p = transpose (p, (3,0))
88 finale_id = finale_id + 1
90 p = (p[0] % 7, p[1])
91 return p
93 # should cache this.
94 def find_scale (transposition):
95 cscale = map (lambda x: (x,0), range (0,7))
96 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
98 return trscale
99 def EDU_to_duration (edu):
100 log = 1
101 d = 4096
102 while d > edu:
103 d = d >> 1
104 log = log << 1
106 edu = edu - d
107 dots = 0
108 if edu == d /2:
109 dots = 1
110 elif edu == d*3/4:
111 dots = 2
112 return (log, dots)
114 def rat_to_lily_duration (rat):
115 (n,d) = rat
117 basedur = 1
118 while d and d % 2 == 0:
119 basedur = basedur << 1
120 d = d >> 1
122 str = 's%d' % basedur
123 if n <> 1:
124 str = str + '*%d' % n
125 if d <> 1:
126 str = str + '/%d' % d
128 return str
130 def gcd (a,b):
131 if b == 0:
132 return a
133 c = a
134 while c:
135 c = a % b
136 a = b
137 b = c
138 return a
141 def rat_simplify (r):
142 (n,d) = r
143 if d < 0:
144 d = -d
145 n = -n
146 if n == 0:
147 return (0,1)
148 else:
149 g = gcd (n, d)
150 return (n/g, d/g)
152 def rat_multiply (a,b):
153 (x,y) = a
154 (p,q) = b
156 return rat_simplify ((x*p, y*q))
158 def rat_add (a,b):
159 (x,y) = a
160 (p,q) = b
162 return rat_simplify ((x*q + p*y, y*q))
164 def rat_neg (a):
165 (p,q) = a
166 return (-p,q)
170 def rat_subtract (a,b ):
171 return rat_add (a, rat_neg (b))
173 def lily_notename (tuple2):
174 (n, a) = tuple2
175 nn = chr ((n+ 2)%7 + ord ('a'))
177 if a == -1:
178 nn = nn + 'es'
179 elif a == -2:
180 nn = nn + 'eses'
181 elif a == 1:
182 nn = nn + 'is'
183 elif a == 2:
184 nn = nn + 'isis'
186 return nn
189 class Tuplet:
190 def __init__ (self, number):
191 self.start_note = number
192 self.finale = []
194 def append_finale (self, fin):
195 self.finale.append (fin)
197 def factor (self):
198 n = self.finale[0][2]*self.finale[0][3]
199 d = self.finale[0][0]*self.finale[0][1]
200 return rat_simplify( (n, d))
202 def dump_start (self):
203 return '\\times %d/%d { ' % self.factor ()
205 def dump_end (self):
206 return ' }'
208 def calculate (self, chords):
209 edu_left = self.finale[0][0] * self.finale[0][1]
211 startch = chords[self.start_note]
212 c = startch
213 while c and edu_left:
214 c.tuplet = self
215 if c == startch:
216 c.chord_prefix = self.dump_start () + c.chord_prefix
218 if not c.grace:
219 edu_left = edu_left - c.EDU_duration ()
220 if edu_left == 0:
221 c.chord_suffix = c.chord_suffix+ self.dump_end ()
222 c = c.next
224 if edu_left:
225 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
227 class Slur:
228 def __init__ (self, number):
229 self.number = number
230 self.finale = []
232 def append_entry (self, finale_e):
233 self.finale.append (finale_e)
235 def calculate (self, chords):
236 startnote = self.finale[0][5]
237 endnote = self.finale[3][2]
238 try:
239 cs = chords[startnote]
240 ce = chords[endnote]
242 if not cs or not ce:
243 raise IndexError
245 cs.note_suffix = '(' + cs.note_suffix
246 ce.note_prefix = ce.note_prefix + ')'
247 except IndexError:
248 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
251 class Global_measure:
252 def __init__ (self, number):
253 self.timesig = ''
254 self.number = number
255 self.keysignature = None
256 self.scale = None
258 self.finale = []
260 def __str__ (self):
261 return `self.finale `
263 def set_timesig (self, finale):
264 (beats, fdur) = finale
265 (log, dots) = EDU_to_duration (fdur)
266 assert dots == 0
267 self.timesig = (beats, log)
269 def length (self):
270 return self.timesig
272 def set_keysig (self, finale):
273 k = interpret_finale_key_sig (finale)
274 self.keysignature = k
275 self.scale = find_scale (k)
278 articulation_dict ={
279 11: '\\prall',
280 12: '\\mordent',
281 8: '\\fermata',
282 4: '^',
283 1: '.',
284 3: '>',
285 18: '"arp"' , # arpeggio
288 class Articulation:
289 def __init__ (self, a,b, finale):
290 self.type = finale[0]
291 self.notenumber = b
292 def calculate (self, chords):
293 c = chords[self.notenumber]
295 try:
296 a = articulation_dict[self.type]
297 except KeyError:
298 sys.stderr.write ("\nUnknown articulation no. %d on note no. %d" % (self.type, self.notenumber))
299 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
300 a = '"art"'
302 c.note_suffix = '-' + a + c.note_suffix
304 class Syllable:
305 def __init__ (self, a,b , finale):
306 self.chordnum = b
307 self.syllable = finale[1]
308 self.verse = finale[0]
309 def calculate (self, chords, lyrics):
310 self.chord = chords[self.chordnum]
312 class Verse:
313 def __init__ (self, number, body):
314 self.body = body
315 self.number = number
316 self.split_syllables ()
317 def split_syllables (self):
318 ss = re.split ('(-| +)', self.body)
320 sep = 0
321 syls = [None]
322 for s in ss:
323 if sep:
324 septor = re.sub (" +", "", s)
325 septor = re.sub ("-", " -- ", septor)
326 syls[-1] = syls[-1] + septor
327 else:
328 syls.append (s)
330 sep = not sep
332 self.syllables = syls
334 def dump (self):
335 str = ''
336 line = ''
337 for s in self.syllables[1:]:
338 line = line + ' ' + s
339 if len (line) > 72:
340 str = str + ' ' * 4 + line + '\n'
341 line = ''
343 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self.number - 1) ,str)
344 return str
347 class Measure:
348 def __init__(self, no):
349 self.number = no
350 self.frames = [0] * 4
351 self.flags = 0
352 self.clef = 0
353 self.finale = []
354 self.global_measure = None
355 self.staff = None
356 self.valid = 1
358 def add_finale_entry (self, entry):
359 self.finale.append (entry)
361 def valid (self):
362 return self.valid
363 def calculate (self):
364 fs = []
366 if len (self.finale) < 2:
367 fs = self.finale[0]
368 fs = map (string.atoi, list (fs))
369 self.clef = fs[1]
370 self.frames = [fs[0]]
371 else:
372 fs = self.finale[0] + self.finale[1]
374 fs = map (string.atoi, list (fs))
375 self.clef = fs[0]
376 self.flags = fs[1]
377 self.frames = fs[2:]
380 class Frame:
381 def __init__ (self, finale):
382 self.measure = None
383 self.finale = finale
384 (number, start, end ) = finale
385 self.number = number
386 self.start = start
387 self.end = end
388 self.chords = []
390 def set_measure (self, m):
391 self.measure = m
393 def calculate (self):
395 # do grace notes.
396 lastch = None
397 for c in self.chords:
398 if c.grace and (lastch == None or (not lastch.grace)):
399 c.chord_prefix = r'\grace {' + c.chord_prefix
400 elif not c.grace and lastch and lastch.grace:
401 lastch.chord_suffix = lastch.chord_suffix + ' } '
403 lastch = c
407 def dump (self):
408 str = '%% FR(%d)\n' % self.number
409 left = self.measure.global_measure.length ()
412 ln = ''
413 for c in self.chords:
414 add = c.ly_string () + ' '
415 if len (ln) + len(add) > 72:
416 str = str + ln + '\n'
417 ln = ''
418 ln = ln + add
419 left = rat_subtract (left, c.length ())
421 str = str + ln
423 if left[0] < 0:
424 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
425 left = (0,1)
426 if left[0]:
427 str = str + rat_to_lily_duration (left)
429 str = str + ' | \n'
430 return str
432 def encodeint (i):
433 return chr ( i + ord ('A'))
435 class Staff:
436 def __init__ (self, number):
437 self.number = number
438 self.measures = []
440 def get_measure (self, no):
441 if len (self.measures) <= no:
442 self.measures = self.measures + [None]* (1 + no - len (self.measures))
444 if self.measures[no] == None:
445 m = Measure (no)
446 self.measures [no] =m
447 m.staff = self
450 return self.measures[no]
451 def staffid (self):
452 return 'staff' + encodeint (self.number - 1)
453 def layerid (self, l):
454 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
456 def dump_time_key_sigs (self):
457 k = ''
458 last_key = None
459 last_time = None
460 last_clef = None
461 gap = (0,1)
462 for m in self.measures[1:]:
463 if not m or not m.valid:
464 continue # ugh.
466 g = m.global_measure
467 e = ''
468 if g and last_key <> g.keysignature:
469 e = e + "\\key %s \\major; " % lily_notename (g.keysignature)
470 last_key = g.keysignature
471 if g and last_time <> g.timesig :
472 e = e + "\\time %d/%d; " % g.timesig
473 last_time = g.timesig
476 if last_clef <> m.clef :
477 e = e + '\\clef "%s";' % lily_clef (m.clef)
478 last_clef = m.clef
479 if e:
480 if gap <> (0,1):
481 k = k +' ' + rat_to_lily_duration (gap) + '\n'
482 gap = (0,1)
483 k = k + e
485 if g:
486 gap = rat_add (gap, g.length ())
489 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
490 return k
492 def dump (self):
493 str = ''
496 layerids = []
497 for x in range (1,5): # 4 layers.
498 laystr = ''
499 last_frame = None
500 first_frame = None
501 gap = (0,1)
502 for m in self.measures[1:]:
503 if not m or not m.valid:
504 sys.stderr.write ("Skipping non-existant measure")
505 continue
507 fr = None
508 try:
509 fr = m.frames[x]
510 except IndexError:
512 sys.stderr.write ("Skipping nonexistent frame")
513 laystr = laystr + "% FOOBAR ! \n"
514 print laystr
515 if fr:
516 first_frame = fr
517 if gap <> (0,1):
518 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
519 gap = (0,1)
520 laystr = laystr + fr.dump ()
521 else:
522 if m.global_measure :
523 gap = rat_add (gap, m.global_measure.length ())
524 else:
525 sys.stderr.write ( \
526 "No global measure for staff %d measure %d\n"
527 % (self.number, m.number))
528 if first_frame:
529 l = self.layerid (x)
530 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
531 str = str + laystr
532 layerids.append (l)
534 str = str + self.dump_time_key_sigs ()
535 stafdef = '\\%sglobal' % self.staffid ()
536 for i in layerids:
537 stafdef = stafdef + ' \\' + i
540 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
541 (self.staffid (), self.staffid (), stafdef)
542 return str
547 class Chord:
548 def __init__ (self, finale_entry):
549 self.pitches = []
550 self.frame = None
551 self.finale = finale_entry
552 self.duration = None
553 self.next = None
554 self.prev = None
555 self.note_prefix= ''
556 self.note_suffix = ''
557 self.chord_suffix = ''
558 self.chord_prefix = ''
559 self.tuplet = None
560 self.grace = 0
562 def measure (self):
563 if not self.frame:
564 return None
565 return self.frame.measure
567 def length (self):
568 if self.grace:
569 return (0,1)
571 l = (1, self.duration[0])
573 d = 1 << self.duration[1]
575 dotfact = rat_subtract ((2,1), (1,d))
576 mylen = rat_multiply (dotfact, l)
578 if self.tuplet:
579 mylen = rat_multiply (mylen, self.tuplet.factor())
580 return mylen
582 def number (self):
583 return self.finale[0][0]
585 def EDU_duration (self):
586 return self.finale[0][3]
587 def set_duration (self):
588 self.duration = EDU_to_duration(self.EDU_duration ())
589 def calculate (self):
590 self.find_realpitch ()
591 self.set_duration ()
593 flag = self.finale[0][5]
594 if Chord.GRACE_MASK & flag:
595 self.grace = 1
598 def find_realpitch (self):
600 ((no, prev, next, dur, pos, entryflag, extended, follow), notelist) = self.finale
602 meas = self.measure ()
603 tiestart = 0
604 if not meas or not meas.global_measure :
605 print 'note %d not in measure' % self.number ()
606 elif not meas.global_measure.scale:
607 print 'note %d: no scale in this measure.' % self.number ()
608 else:
609 for p in notelist:
610 (pitch, flag) = p
612 nib1 = pitch & 0x0f
613 if nib1 > 8:
614 nib1 = -(nib1 - 8)
615 rest = pitch / 16
617 scale = meas.global_measure.scale
618 (sn, sa) =scale[rest % 7]
619 sn = sn + (rest - (rest%7)) + 7
620 acc = sa + nib1
621 self.pitches.append ((sn, acc))
622 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
623 if tiestart :
624 self.chord_suffix = self.chord_suffix + ' ~ '
626 REST_MASK = 0x40000000L
627 TIE_START_MASK = 0x40000000L
628 GRACE_MASK = 0x00800000L
630 def ly_string (self):
631 s = ''
633 rest = ''
635 if not (self.finale[0][5] & Chord.REST_MASK):
636 rest = 'r'
638 for p in self.pitches:
639 (n,a) = p
640 o = n/ 7
641 n = n % 7
643 nn = lily_notename ((n,a))
645 if o < 0:
646 nn = nn + (',' * -o)
647 elif o > 0:
648 nn = nn + ('\'' * o)
650 if s:
651 s = s + ' '
653 if rest:
654 nn = rest
656 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
658 if not self.pitches:
659 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
660 s = self.note_prefix + s + self.note_suffix
661 if len (self.pitches) > 1:
662 s = '<%s>' % s
664 s = self.chord_prefix + s + self.chord_suffix
665 return s
667 GFre = re.compile(r"""^\^GF\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
668 BCre = re.compile (r"""^\^BC\(([0-9-]+)\) ([0-9-]+) .*$""")
669 eEre = re.compile(r"""^\^eE\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) \$([0-9A-Fa-f]+) ([0-9-]+) ([0-9-]+)""")
670 FRre = re.compile (r"""^\^FR\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
671 MSre = re.compile (r"""^\^MS\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
672 note_re = re.compile (r"""^ +([0-9-]+) \$([A-Fa-f0-9]+)""")
673 Sxre = re.compile (r"""^\^Sx\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
674 IMre = re.compile (r"""^\^IM\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
675 vere = re.compile(r"""^\^(ve|ch|se)\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
676 versere = re.compile(r"""^\^verse\(([0-9]+)\)(.*)\^end""")
678 TPre = re.compile(r"""^\^TP\(([0-9]+),([0-9]+)\) *([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
681 class Etf_file:
682 def __init__ (self, name):
683 self.measures = [None]
684 self.entries = [None]
685 self.chords = [None]
686 self.frames = [None]
687 self.tuplets = [None]
688 self.staffs = [None]
689 self.slur_dict = {}
690 self.articulations = [None]
691 self.syllables = [None]
692 self.verses = [None]
694 ## do it
695 self.parse (name)
697 def get_global_measure (self, no):
698 if len (self.measures) <= no:
699 self.measures = self.measures + [None]* (1 + no - len (self.measures))
701 if self.measures[no] == None:
702 self.measures [no] = Global_measure (no)
704 return self.measures[no]
707 def get_staff(self,staffno):
708 if len (self.staffs) <= staffno:
709 self.staffs = self.staffs + [None] * (1 + staffno - len (self.staffs))
711 if self.staffs[staffno] == None:
712 self.staffs[staffno] = Staff (staffno)
714 return self.staffs[staffno]
716 # staff-spec
717 def try_IS (self, l):
718 pass
720 def try_BC (self, l):
721 m = BCre.match (l)
722 if m:
723 bn = string.atoi (m.group (1))
724 where = string.atoi (m.group (2)) / 1024.0
725 return m
726 def try_TP(self, l):
727 m = TPre.match (l)
728 if m:
729 (nil, num) = map (string.atoi, (m.groups ()[0:2]))
730 entries = map (string.atoi, (m.groups ()[2:]))
732 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
733 self.tuplets.append (Tuplet (num))
735 self.tuplets[-1].append_finale (entries)
737 def try_IM (self, l):
738 m = IMre.match (l)
739 if m:
740 a = string.atoi (m.group (1))
741 b = string.atoi (m.group (2))
743 fin = map (string.atoi, m.groups ()[2:])
745 self.articulations.append (Articulation (a,b,fin))
746 return m
747 def try_verse (self,l):
748 m = versere .match (l)
749 if m:
750 a = string.atoi (m.group (1))
751 body =m.group (2)
753 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
754 body = re.sub ("\^[a-z]+", "", body)
755 self.verses.append (Verse (a, body))
757 return m
758 def try_ve (self,l):
759 m = vere .match (l)
760 if m:
761 a = string.atoi (m.group (1))
762 b = string.atoi (m.group (2))
764 fin = map (string.atoi, m.groups ()[2:])
766 self.syllables.append (Syllable (a,b,fin))
767 return m
768 def try_eE (self, l):
769 m = eEre.match (l)
770 if m:
771 tup = m.groups()
772 (no, prev, next, dur, pos, entryflag, extended, follow) = tup
773 (no, prev, next, dur, pos,extended, follow) \
774 = tuple (map (string.atoi, [no,prev,next,dur,pos,extended,follow]))
776 entryflag = string.atol (entryflag,16)
777 if len (self.entries) <= no:
778 # missing entries seem to be quite common.
779 # we fill'em up with None.
780 self.entries = self.entries + [None] * (no - len (self.entries) + 1)
782 current_entry = ((no, prev, next, dur, pos, entryflag, extended, follow), [])
783 self.entries[no] = current_entry
784 return m
786 def try_Sx(self,l):
787 m = Sxre.match (l)
788 if m:
789 slurno = string.atoi (m.group (1))
791 sl = None
792 try:
793 sl = self.slur_dict[slurno]
794 except KeyError:
795 sl = Slur (slurno)
796 self.slur_dict[slurno] = sl
798 params = list (m.groups ()[1:])
799 params = map (string.atoi, params)
800 sl.append_entry (params)
802 return m
803 def try_GF(self, l):
804 m = GFre.match (l)
805 if m:
806 (staffno,measno) = m.groups ()[0:2]
807 s = string.atoi (staffno)
808 me = string.atoi (measno)
810 entry = m.groups () [2:]
811 st = self.get_staff (s)
812 meas = st.get_measure (me)
813 meas.add_finale_entry (entry)
815 # frame ?
816 def try_FR(self, l):
817 m = FRre.match (l)
818 if m:
819 (frameno, startnote, endnote, foo, bar) = m.groups ()
820 (frameno, startnote, endnote) = tuple (map (string.atoi, [frameno, startnote, endnote]))
821 if len (self.frames) <= frameno:
822 self.frames = self.frames + [None] * (frameno - len(self.frames) + 1)
824 self.frames[frameno] = Frame ((frameno, startnote, endnote))
826 return m
828 def try_MS (self, l):
829 m = MSre.match (l)
830 if m:
831 measno = string.atoi (m.group (1))
832 keynum = string.atoi (m.group (3))
833 meas =self. get_global_measure (measno)
834 meas.set_keysig (keynum)
836 beats = string.atoi (m.group (4))
837 beatlen = string.atoi (m.group (5))
838 meas.set_timesig ((beats, beatlen))
840 return m
842 def try_note (self, l):
843 m = note_re.match (l)
844 if m:
845 (pitch, flag) = m.groups ()
846 pitch = string.atoi (pitch)
847 flag = string.atol (flag,16)
848 self.entries[-1][1].append ((pitch,flag))
850 def parse (self, name):
851 sys.stderr.write ('parsing ...')
852 sys.stderr.flush ()
854 gulp = open (name).read ()
856 gulp = re.sub ('[\n\r]+', '\n', gulp)
857 ls = string.split (gulp, '\n')
859 for l in ls:
860 m = None
861 if not m:
862 m = self.try_MS (l)
863 if not m:
864 m = self.try_FR (l)
865 if not m:
866 m = self.try_GF (l)
867 if not m:
868 m = self.try_note (l)
869 if not m:
870 m = self.try_eE (l)
871 if not m:
872 m = self.try_IM (l)
873 if not m:
874 m = self.try_Sx (l)
875 if not m:
876 m = self.try_TP (l)
877 if not m:
878 m = self.try_verse (l)
880 sys.stderr.write ('processing ...')
881 sys.stderr.flush ()
883 self.unthread_entries ()
885 for st in self.staffs[1:]:
886 if not st:
887 continue
888 mno = 1
889 for m in st.measures[1:]:
890 if not m:
891 continue
893 m.calculate()
894 try:
895 m.global_measure = self.measures[mno]
896 except IndexError:
897 sys.stderr.write ("Non-existent global measure %d" % mno)
898 continue
900 frame_obj_list = [None]
901 for frno in m.frames:
902 fr = self.frames[frno]
903 frame_obj_list.append (fr)
905 m.frames = frame_obj_list
906 for fr in frame_obj_list[1:]:
907 if not fr:
908 continue
910 fr.set_measure (m)
912 fr.chords = self.get_thread (fr.start, fr.end)
913 for c in fr.chords:
914 c.frame = fr
915 mno = mno + 1
917 for c in self.chords[1:]:
918 if c:
919 c.calculate()
921 for f in self.frames[1:]:
922 if f:
923 f.calculate ()
925 for t in self.tuplets[1:]:
926 t.calculate (self.chords)
928 for s in self.slur_dict.values():
929 s.calculate (self.chords)
930 for s in self.articulations[1:]:
931 s.calculate (self.chords)
933 def get_thread (self, startno, endno):
935 thread = []
937 c = None
938 try:
939 c = self.chords[startno]
940 except IndexError:
941 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
942 return []
945 while c and c.number () <> endno:
946 thread.append (c)
947 c = c.next
949 if c:
950 thread.append (c)
952 return thread
954 def dump (self):
955 str = ''
956 staffs = []
957 for s in self.staffs[1:]:
958 if s:
959 str = str + '\n\n' + s.dump ()
960 staffs.append ('\\' + s.staffid ())
963 # should use \addlyrics ?
965 for v in self.verses[1:]:
966 str = str + v.dump()
968 if len (self.verses) > 1:
969 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
971 if staffs:
972 str = str + '\\score { < %s > } ' % string.join (staffs)
974 return str
977 def __str__ (self):
978 return 'ETF FILE %s %s' % (self.measures, self.entries)
980 def unthread_entries (self):
981 self.chords = [None]
982 for e in self.entries[1:]:
983 ch = None
984 if e:
985 ch = Chord (e)
986 self.chords.append (ch)
988 for e in self.chords[1:]:
989 if not e:
990 continue
991 e.prev = self.chords[e.finale[0][1]]
992 e.next = self.chords[e.finale[0][2]]
994 def identify():
995 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
997 def help ():
998 print """Usage: etf2ly [OPTION]... ETF-FILE
1000 Convert ETF to LilyPond.
1002 Options:
1003 -h,--help this help
1004 -o,--output=FILE set output filename to FILE
1005 -v,--version version information
1007 Enigma Transport Format is a format used by Coda Music Technology's
1008 Finale product. This program will convert a subset of ETF to a
1009 ready-to-use lilypond file.
1011 Report bugs to bug-gnu-music@gnu.org
1013 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1016 def print_version ():
1017 print r"""etf2ly (GNU lilypond) %s
1019 This is free software. It is covered by the GNU General Public License,
1020 and you are welcome to change it and/or distribute copies of it under
1021 certain conditions. Invoke as `midi2ly --warranty' for more information.
1023 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1024 """ % version
1028 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1029 out_filename = None
1031 for opt in options:
1032 o = opt[0]
1033 a = opt[1]
1034 if o== '--help' or o == '-h':
1035 help ()
1036 sys.exit (0)
1037 if o == '--version' or o == '-v':
1038 print_version ()
1039 sys.exit(0)
1041 if o == '--output' or o == '-o':
1042 out_filename = a
1043 else:
1044 print o
1045 raise getopt.error
1047 identify()
1049 e = None
1050 for f in files:
1051 if f == '-':
1052 f = ''
1054 sys.stderr.write ('Processing `%s\'\n' % f)
1055 e = Etf_file(f)
1056 if not out_filename:
1057 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1059 if out_filename == f:
1060 out_filename = os.path.basename (f + '.ly')
1062 sys.stderr.write ('Writing `%s\'' % out_filename)
1063 ly = e.dump()
1067 fo = open (out_filename, 'w')
1068 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)
1069 fo.write(ly)
1070 fo.close ()