summaryrefslogtreecommitdiff
path: root/pykfx.py
blob: ea4e0d32c574358cde594cb0c6074e49d9076b32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import re

class StyleException(Exception): pass
class EventException(Exception): pass
class ScriptException(Exception): pass

class ScriptInfo:
	def __init__(self, f = None):
		# original case keys used for writing
		self.ock = {}
		self.info = {}
		if f:
			self.read(f)

	def __getitem__(self, key):
		try:
			return self.info[key.lower()]
		except ValueError:
			raise KeyError

	def read(self, f):
		s = f.readline().strip()
		while s:
			if not s.startswith(';'):
				k, v = s.split(': ', 1)
				self.ock[k.lower()] = k
				self.info[k.lower()] = v
			s = f.readline().strip()

	def write(self, f):
			f.write('[Script Info]\n')
			f.writelines(['%s: %s\n' % (self.ock[k], self.info[k]) for k in self.info.keys()])

class Style:
	def __init__(self, format, s = None):
		self.format = format
		if s:
			self.parse(s)

	def __str__(self):
		return 'Style: %s' % ','.join([getattr(self, x.lower()) for x in self.format])

	def parse(self, s):
		s = s.split(': ', 1)
		if s[0] != 'Style':
			raise StyleException('invalid style line')
		s = s[1].split(',')
		for k, v in zip(self.format, s):
			setattr(self, k.lower(), v)

class Styles:
	def __init__(self, f = None):
		self.format, self.styles = [], {}
		if f:
			self.read(f)

	def __getitem__(self, key):
		if self.styles.has_key(key.lower()):
			return self.styles[key]
		else:
			raise KeyError('style "%s" not found' % key)

	def read(self, f):
		s = f.readline().strip()
		s = s.split(': ', 1)
		if s[0] != 'Format':
			raise StyleException('format line not found')
		self.format = s[1].split(', ')

		s = f.readline().strip()
		while s:
			s = Style(self.format, s)
			self.styles[s.name.lower()] = s
			s = f.readline().split()

	def write(self, f):
		f.write('[V4 Styles]\n')
		f.write('Format: %s\n' % ', '.join(self.format))
		f.writelines(['%s\n' % str(s) for s in self.styles.values()])

class Syllable:
	def __init__(self, start, end, text):
		self.start, self.end, self.dur, self.text = start, end, end - start, text

	def __str__(self):
		return '{\\k%d}%s' % (self.dur / 10, self.text)

class Event:
	def __init__(self, format, s = None):
		self.karaoke = []
		self.format = format
		if s:
			self.parse(s)

	def __getitem__(self, key):
		if type(key) is int:
			return self.karaoke[key]
		else:
			raise TypeError('key must be int')

	def __str__(self):
		return '%s: %s' % (self.kind.capitalize(), ','.join([getattr(self, x.lower()) for x in self.format]))

	def parse(self, s):
		s = s.split(': ', 1)
		self.kind = s[0].lower()
		s = s[1].split(',')
		for k, v in zip(self.format, s):
			setattr(self, k.lower(), v)
		if self.kind == 'dialogue' and self.text.find('\\k') > -1:
			self.parse_karaoke()

	def parse_karaoke(self):
		s = self.text
		i = 0
		tot = 0
		while i < len(s):
			i = s.find('\\k', i)
			# break if no more \k's (end-of-line-text is added at the end of the loop)
			if i == -1:
				break
			i += 2
			ms = ''
			while s[i].isdigit():
				ms += s[i]
				i += 1
			ms = int(ms) * 10
			tot += ms
			# unless next is another override, skip one char (past '}')
			if s[i] != '\\':
				i += 1
			n = s.find('\\k', i)
			if n > -1:
				part = s[i:n-1] # get text up to next \k
			else:
				part = s[i:] # end of line

			# go to next if part is empty
			if not part.strip():
				continue

			self.karaoke.append(Syllable(tot - ms, tot, part))

	def add_lead_in(self, s):
		t = self.start.split(':')
		ts = float(t[-1]) + 60 * int(t[-2]) + 3600 * int(t[-3]) - s
		th, ts = int(ts / 3600), ts % 3600
		tm, ts = int(ts / 60), ts % 60
		self.start = '%01d:%02d:%05.2f' % (th, tm, ts)
 
	def add_lead_out(self, s):
		t = self.snd.split(':')
		ts = float(t[-1]) + 60 * int(t[-2]) + 3600 * int(t[-3]) + s
		th, ts = int(ts / 3600), ts % 3600
		tm, ts = int(ts / 60), ts % 60
		self.end = '%01d:%02d:%05.2f' % (th, tm, ts)

class Events:
	def __init__(self, f = None):
		self.format, self.events = [], []
		if f:
			self.read(f)

	def __getitem__(self, key):
		if type(key) is int:
			return self.events[key]
		else:
			raise TypeError('key must be int')

	def read(self, f):
		s = f.readline().strip()
		s = s.split(': ', 1)
		if s[0] != 'Format':
			raise EventException('format line not found')
		self.format = s[1].split(', ')

		s = f.readline().strip()
		while s:
			self.events.append(Event(self.format, s))
			s = f.readline().strip()

	def write(self, f):
		f.write('[Events]\n')
		f.write('Format: %s\n' % ', '.join(self.format))
		f.writelines(['%s\n' % str(e) for e in self.events])

class Script:
	def __init__(self, f = None):
		if f:
			self.read(f)

	def read(self, f):
		f = open(f, 'r')

		s = f.readline().strip()
		if s.startswith('\xef\xbb\xbf'):
			s = s[3:]
		if s == '[Script Info]':
			self.info = ScriptInfo(f)
		else:
			raise ScriptException('script info not found')

		s = f.readline().strip()
		if re.match('\[V4\+? Styles\]', s):
			self.styles = Styles(f)
		else:
			raise ScriptException('script styles not found')

		s = f.readline().strip()
		if s == '[Events]':
			self.events = Events(f)
		else:
			raise ScriptException('script events not found')

	def write(self, f):
		f = open(f, 'w')
		self.info.write(f)
		f.write('\n')
		self.styles.write(f)
		f.write('\n')
		self.events.write(f)
		f.write('\n')