forked from mutantstandard/orxporter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexport_thread.py
382 lines (299 loc) · 13.1 KB
/
export_thread.py
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import os
import pathlib
import queue
import subprocess
import threading
from exception import FilterException
from paths import format_path
import svg
import log
class ExportThread:
"""
A class representing and managing a single thread that executes
exporting tasks from the export queue.
"""
def __init__(self, queue, name, total, m, input_path, formats, path,
renderer):
self.queue = queue
self.name = name
self.total = total
self.m = m
self.input_path = input_path
self.formats = formats
self.path = path
self.renderer = renderer
self.err = None
# this essentially tells self.run() to stop running if it is
self.kill_flag = False
# the actual thread part of this thread
self.thread = threading.Thread(target=self.run)
# start the thread part of this thread!
self.thread.start()
def kill(self):
"""
Requests this thread to be teriminated by activating the self.kill_flag flag.
(This effectively stops self.run() from running)
"""
self.kill_flag = True
def join(self):
"""
Wait for this thread to finish and merge it.
"""
self.thread.join()
def msg(self, s, color=37, indent=0):
log.out(s, color, indent, self.name)
def export_svg(self, emoji_svg, path, license=None):
"""
SVG exporting function
"""
if license:
final_svg = svg.add_license(emoji_svg, license)
else:
final_svg = emoji_svg
# write SVG out to file
try:
out = open(path, 'w')
out.write(final_svg)
out.close()
except Exception:
raise Exception('Could not write to file: ' + path)
def export_png(self, emoji_svg, size, path):
# saving SVG to a temporary file
tmp_name = '.tmp' + self.name + '.svg'
try:
f = open(tmp_name, 'w')
f.write(emoji_svg)
f.close()
except IOError:
raise Exception('Could not write to temporary file: ' + tmp_name)
# export the SVG to a PNG based on the user's renderer
if self.renderer == 'inkscape':
cmd = ['inkscape', os.path.abspath(tmp_name),
'--export-png=' + os.path.abspath(path),
'-h', str(size), '-w', str(size)]
elif self.renderer == 'rendersvg':
cmd = ['rendersvg', '-w', str(size), '-h', str(size),
os.path.abspath(tmp_name), os.path.abspath(path)]
elif self.renderer == 'imagemagick':
cmd = ['convert', '-background', 'none', '-density', str(size / 32 * 128),
'-resize', str(size) + 'x' + str(size), os.path.abspath(tmp_name), os.path.abspath(path)]
else:
raise AssertionError
try:
r = subprocess.run(cmd, stdout=subprocess.DEVNULL).returncode
except Exception as e:
raise Exception('Rasteriser invocation failed: ' + str(e))
if r:
raise Exception('Rasteriser returned error code: ' + str(r))
# delete temporary files
os.remove(tmp_name)
def export_flif(self, emoji_svg, size, path):
"""
FLIF Exporting function. Creates temporary PNGs first before converting to WebP.
"""
tmp_svg_name = '.tmp' + self.name + '.svg'
tmp_png_name = '.tmp' + self.name + '.png'
# try to write temporary SVG
try:
f = open(tmp_svg_name, 'w')
f.write(emoji_svg)
f.close()
except IOError:
raise Exception('Could not write to temporary file: ' + tmp_svg_name)
# export the SVG to a temporary PNG based on the user's renderer
if self.renderer == 'inkscape':
cmd_png = ['inkscape', os.path.abspath(tmp_svg_name),
'--export-png=' + os.path.abspath(tmp_png_name),
'-h', str(size), '-w', str(size)]
elif self.renderer == 'rendersvg':
cmd_png = ['rendersvg', '-w', str(size), '-h', str(size),
os.path.abspath(tmp_svg_name), os.path.abspath(tmp_png_name)]
elif self.renderer == 'imagemagick':
cmd_png = ['convert', '-background', 'none', '-density', str(size / 32 * 128),
'-resize', str(size) + 'x' + str(size), os.path.abspath(tmp_svg_name), os.path.abspath(tmp_png_name)]
else:
raise AssertionError
try:
r = subprocess.run(cmd_png, stdout=subprocess.DEVNULL).returncode
except Exception as e:
raise Exception('PNG rasteriser invocation failed: ' + str(e))
if r:
raise Exception('PNG rasteriser returned error code: ' + str(r))
# try to export FLIF
cmd_flif = ['flif', '-e', '--overwrite', '-Q100', os.path.abspath(tmp_png_name), os.path.abspath(path)]
try:
r = subprocess.run(cmd_flif, stdout=subprocess.DEVNULL).returncode
except Exception as e:
raise Exception('FLIF converter invocation failed: ' + str(e))
if r:
raise Exception('FLIF converter returned error code: ' + str(r))
# delete temporary files
os.remove(tmp_svg_name)
os.remove(tmp_png_name)
def export_webp(self, emoji_svg, size, path):
"""
WebP Exporting function. Creates temporary PNGs first before converting to WebP.
"""
tmp_svg_name = '.tmp' + self.name + '.svg'
tmp_png_name = '.tmp' + self.name + '.png'
# try to write a temporary SVG
try:
f = open(tmp_svg_name, 'w')
f.write(emoji_svg)
f.close()
except IOError:
raise Exception('Could not write to temporary file: ' + tmp_svg_name)
# export the SVG to a temporary PNG based on the user's renderer
if self.renderer == 'inkscape':
cmd_png = ['inkscape', os.path.abspath(tmp_svg_name),
'--export-png=' + os.path.abspath(tmp_png_name),
'-h', str(size), '-w', str(size)]
elif self.renderer == 'rendersvg':
cmd_png = ['rendersvg', '-w', str(size), '-h', str(size),
os.path.abspath(tmp_svg_name), os.path.abspath(tmp_png_name)]
elif self.renderer == 'imagemagick':
cmd_png = ['convert', '-background', 'none', '-density', str(size / 32 * 128),
'-resize', str(size) + 'x' + str(size), os.path.abspath(tmp_svg_name), os.path.abspath(tmp_png_name)]
else:
raise AssertionError
try:
r = subprocess.run(cmd_png, stdout=subprocess.DEVNULL).returncode
except Exception as e:
raise Exception('PNG rasteriser invocation failed: ' + str(e))
if r:
raise Exception('PNG rasteriser returned error code: ' + str(r))
# try to export WebP
cmd_webp = ['cwebp', '-lossless', '-quiet', os.path.abspath(tmp_png_name), '-o', os.path.abspath(path)]
try:
r = subprocess.run(cmd_webp, stdout=subprocess.DEVNULL).returncode
except Exception as e:
raise Exception('WebP converter invocation failed: ' + str(e))
if r:
raise Exception('WebP converter returned error code: ' + str(r))
# delete temporary files
os.remove(tmp_svg_name)
os.remove(tmp_png_name)
def export_avif(self, emoji_svg, size, path):
"""
Lossless AVIF Exporting function. Creates temporary PNGs first before converting to AVIF.
"""
tmp_svg_name = '.tmp' + self.name + '.svg'
tmp_png_name = '.tmp' + self.name + '.png'
# try to write a temporary SVG
try:
f = open(tmp_svg_name, 'w')
f.write(emoji_svg)
f.close()
except IOError:
raise Exception('Could not write to temporary file: ' + tmp_svg_name)
# export the SVG to a temporary PNG based on the user's renderer
if self.renderer == 'inkscape':
cmd_png = ['inkscape', os.path.abspath(tmp_svg_name),
'--export-png=' + os.path.abspath(tmp_png_name),
'-h', str(size), '-w', str(size)]
elif self.renderer == 'rendersvg':
cmd_png = ['rendersvg', '-w', str(size), '-h', str(size),
os.path.abspath(tmp_svg_name), os.path.abspath(tmp_png_name)]
elif self.renderer == 'imagemagick':
cmd_png = ['convert', '-background', 'none', '-density', str(size / 32 * 128),
'-resize', str(size) + 'x' + str(size), os.path.abspath(tmp_svg_name), os.path.abspath(tmp_png_name)]
else:
raise AssertionError
try:
r = subprocess.run(cmd_png, stdout=subprocess.DEVNULL).returncode
except Exception as e:
raise Exception('PNG rasteriser invocation failed: ' + str(e))
if r:
raise Exception('PNG rasteriser returned error code: ' + str(r))
# try to export AVIF
cmd_avif = ['avif', '-e', os.path.abspath(tmp_png_name), '-o', os.path.abspath(path), '--lossless']
try:
r = subprocess.run(cmd_avif, stdout=subprocess.DEVNULL).returncode
except Exception as e:
raise Exception('AVIF converter invocation failed: ' + str(e))
if r:
raise Exception('AVIF converter returned error code: ' + str(r))
# delete temporary files
os.remove(tmp_svg_name)
os.remove(tmp_png_name)
def export_emoji(self, emoji, emoji_svg, f, path, license):
"""
Runs a single export batch.
"""
final_path = format_path(path, emoji, f)
# try to make the directory for this particular export batch.
try:
dirname = os.path.dirname(final_path)
if dirname:
os.makedirs(dirname, exist_ok=True)
except IOError:
raise Exception('Could not create directory: ' + dirname)
# run a format-specific export task on the emoji.
if f == 'svg':
self.export_svg(emoji_svg, final_path, license.get('svg'))
elif f.startswith('png-'):
try:
size = int(f[4:])
except ValueError:
raise ValueError(f"The end ('{f[4:]}') of a format you gave ('{f}') isn't a number. It must be a number.")
self.export_png(emoji_svg, size, final_path)
elif f.startswith('flif-'):
try:
size = int(f[5:])
except ValueError:
raise ValueError(f"The end ('{f[5:]}') of a format you gave ('{f}') isn't a number. It must be a number.")
self.export_flif(emoji_svg, size, final_path)
elif f.startswith('webp-'):
try:
size = int(f[5:])
except ValueError:
raise ValueError(f"The end ('{f[5:]}') of a format you gave ('{f}') isn't a number. It must be a number.")
self.export_webp(emoji_svg, size, final_path)
elif f.startswith('avif-'):
try:
size = int(f[5:])
except ValueError:
raise ValueError(f"The end ('{f[5:]}') of a format you gave ('{f}') isn't a number. It must be a number.")
self.export_avif(emoji_svg, size, final_path)
else:
raise ValueError('Invalid format: ' + f)
def run(self):
"""
The process of getting and executing a single export task in
the queue.
This is what the actual thread part of this class is tasked
with working on.
"""
try:
# basically: do stuff as long as it's not requested to
# be killed by the class
while not self.kill_flag:
# try to get an item from the queue.
try:
i, emoji = self.queue.get_nowait()
except queue.Empty:
break
# compose the file path of the emoji.
format_path(self.path, emoji, 'svg')
if 'src' not in emoji:
raise ValueError('Missing src attribute')
srcpath = os.path.join(self.m.homedir, self.input_path,
emoji['src'])
# load the SVG source file
try:
emoji_svg = open(srcpath, 'r').read()
except Exception:
raise ValueError('Could not load file: ' + srcpath)
# convert colormaps (if applicable)
if 'color' in emoji:
cmap = self.m.colormaps[emoji['color']]
pfrom = self.m.palettes[cmap['src']]
pto = self.m.palettes[cmap['dst']]
emoji_svg = svg.translate_color(emoji_svg, pfrom, pto)
# for each format in the emoji, export it as that
for f in self.formats:
self.export_emoji(emoji, emoji_svg, f, self.path, self.m.license)
# tell the progress bar that this task has been completed.
log.export_task_count += 1
except Exception as e:
self.err = e