-
Notifications
You must be signed in to change notification settings - Fork 46
/
task.py
389 lines (371 loc) · 17.8 KB
/
task.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
383
384
385
386
387
388
389
import collections
import subprocess
import io
import math
import os
import re
import shlex
import shutil
import tempfile
import time
import threading
import traceback
import typing
from PIL import Image
from PIL import ImageFilter
from PIL import ImageSequence
import define
import param
class AbstractTask:
def __init__(self, outputCallback: typing.Callable[[str], None]) -> None:
self.outputCallback = outputCallback
def run(self) -> None:
pass
class RESpawnTask(AbstractTask):
def __init__(
self,
outputCallback: typing.Callable[[str], None],
progressValue: list[int | float],
inputPath: str, outputPath: str,
config: param.REConfigParams,
removeInput: bool = False,
) -> None:
super().__init__(outputCallback)
self.progressValue = progressValue
self.inputPath = inputPath
self.outputPath = outputPath
self.config = config
self.removeInput = removeInput
def run(self) -> None:
self.outputCallback(f'Using executable: {define.RE_PATH}\n')
self.progressValue[0] = 0
with Image.open(self.inputPath) as img:
srcWidth, srcHeight = img.size
srcRatio = srcWidth / srcHeight
if img.mode == 'P':
self.inputPath = tempfile.mktemp('.png')
img.convert('RGBA').save(self.inputPath)
self.removeInput = True
resizeMode = self.config.resizeMode
if (
(resizeMode == param.ResizeMode.LONGEST_SIDE and srcWidth >= srcHeight)
or (resizeMode == param.ResizeMode.SHORTEST_SIDE and srcWidth <= srcHeight)
):
resizeMode = param.ResizeMode.WIDTH
elif (
(resizeMode == param.ResizeMode.LONGEST_SIDE and srcHeight >= srcWidth)
or (resizeMode == param.ResizeMode.SHORTEST_SIDE and srcHeight <= srcWidth)
):
resizeMode = param.ResizeMode.HEIGHT
match resizeMode:
case param.ResizeMode.RATIO:
dstWidth = srcWidth * self.config.resizeModeValue
dstHeight = srcHeight * self.config.resizeModeValue
case param.ResizeMode.WIDTH:
dstWidth = self.config.resizeModeValue
dstHeight = round(dstWidth / srcRatio)
case param.ResizeMode.HEIGHT:
dstHeight = self.config.resizeModeValue
dstWidth = round(dstHeight * srcRatio)
inputPathPreupscaled: str = None
if self.config.preupscale:
match resizeMode:
case param.ResizeMode.RATIO:
scaleRatio = self.config.resizeModeValue
case param.ResizeMode.WIDTH:
scaleRatio = self.config.resizeModeValue / srcWidth
case param.ResizeMode.HEIGHT:
scaleRatio = self.config.resizeModeValue / srcHeight
frac, intg = math.modf(math.log(scaleRatio, self.config.modelFactor))
preWidth = math.ceil(dstWidth / (self.config.modelFactor ** intg))
preHeight = math.ceil(dstHeight / (self.config.modelFactor ** intg))
if frac < .5 and (srcWidth != preWidth or srcHeight != preHeight):
self.outputCallback(f'Pre-upscale from {srcWidth}x{srcHeight} to {preWidth}x{preHeight}.\n')
inputPathPreupscaled = tempfile.mktemp('.webp' if os.path.splitext(self.inputPath)[1] == '.webp' else '.png')
with Image.open(self.inputPath) as img:
resized = img.resize((preWidth, preHeight), Image.LANCZOS)
resized.save(inputPathPreupscaled, lossless=True)
resized.close()
srcWidth, srcHeight = preWidth, preHeight
scalePass = 0
while srcWidth < dstWidth and srcHeight < dstHeight:
scalePass += 1
srcWidth *= self.config.modelFactor
srcHeight *= self.config.modelFactor
# input -> output
# input -> temp0 -> output
# input -> temp0 -> temp1 -> output
outputExt = os.path.splitext(self.outputPath)[1]
files = (inputPathPreupscaled or self.inputPath, *(tempfile.mktemp(outputExt) for _ in range(scalePass)))
for i in range(len(files) - 1):
inputPath, outputPath = files[i:(i + 2)]
alphaOverridePath = None
if os.path.splitext(os.path.split(define.RE_PATH)[1])[0] == 'realcugan-ncnn-vulkan':
model, modelFilename = self.config.model.split('#', 1)
denoiseLevel = {
'conservative': -1,
'no-denoise': 0,
**{f'denoise{i}x': i for i in range(1, 4)},
}[modelFilename.split('-', 1)[1]]
cmd = (
define.RE_PATH,
'-v',
'-i', inputPath,
'-o', outputPath,
'-s', str(self.config.modelFactor),
'-t', str(self.config.tileSize),
'-m', os.path.join(self.config.modelDir, model),
'-n', str(denoiseLevel),
'-g', 'auto' if self.config.gpuID < 0 else str(self.config.gpuID),
'-c', '1', # accurate sync
*(('-x', ) if self.config.useTTA else ()),
)
else:
cmd = (
define.RE_PATH,
'-v',
'-i', inputPath,
'-o', outputPath,
'-s', str(self.config.modelFactor),
*(('-z', str(self.config.modelFactor)) if os.path.splitext(os.path.split(define.RE_PATH)[1])[0] == 'upscayl-bin' else ()),
'-t', str(self.config.tileSize),
'-n', self.config.model,
'-g', 'auto' if self.config.gpuID < 0 else str(self.config.gpuID),
*(('-x', ) if self.config.useTTA else ()),
)
with subprocess.Popen(
cmd,
stderr=subprocess.PIPE,
universal_newlines=True,
encoding='utf-8' if os.path.splitext(os.path.split(define.RE_PATH)[1])[0] == 'upscayl-bin' else None,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0,
) as p:
for line in p.stderr:
# 如果输入文件是有alpha通道的图片,但是输出扩展名又是JPG
# Real-ESRGAN会强行给输出的文件名加上PNG的扩展名,导致后续处理找不到文件
# 这里额外加了一个重命名为原来的输出文件名的操作
# https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan/blob/37026f49824c5cf84062e7c6a5dd71445dcf610f/src/main.cpp#L283
if m := re.search(r'^image .+? has alpha channel ! .+? will output (.+?)$', line, re.M):
alphaOverridePath = m.group(1)
elif m := re.search(r'(\d+[.,]\d+)%', line):
self.progressValue[0] = (i + float(m.group(1).replace(',', '.')) / 100) / (len(files) - 1)
elif m := re.search(r'^.+? -> .+? done$', line, re.M):
self.progressValue[0] = (i + 1) / (len(files) - 1)
self.outputCallback(line)
if p.returncode:
raise subprocess.CalledProcessError(p.returncode, cmd)
if i > 0 or inputPath == inputPathPreupscaled or self.removeInput:
os.remove(inputPath)
if alphaOverridePath:
shutil.move(alphaOverridePath, outputPath)
self.outputCallback(f'Rename {alphaOverridePath} to {outputPath}\n')
os.makedirs(os.path.split(self.outputPath)[0], exist_ok=True)
if srcWidth == dstWidth and srcHeight == dstHeight:
if os.path.exists(self.outputPath):
os.remove(self.outputPath)
shutil.move(files[-1], self.outputPath)
else:
with Image.open(files[-1]) as img:
self.outputCallback(f'Downsample from {img.size[0]}x{img.size[1]} to {dstWidth}x{dstHeight}.\n')
resized = img.resize((dstWidth, dstHeight), self.config.downsample)
resized.save(self.outputPath)
resized.close()
if scalePass:
os.remove(files[-1])
self.progressValue[0] = 0
self.progressValue[1] += 1
class MergeGIFTask(AbstractTask):
def __init__(
self,
outputCallback: typing.Callable[[str], None],
outputPath: str,
frames: tuple[str, ...],
durations: tuple[int, ...],
optimizeTransparency: bool,
) -> None:
super().__init__(outputCallback)
self.outputPath = outputPath
self.frames = frames
self.durations = durations
self.optimizeTransparency = optimizeTransparency
def run(self) -> None:
self.outputCallback(f'Merging {len(self.frames)} frames to {self.outputPath}\n')
frameImgs: list[Image.Image] = []
for f in self.frames:
b = io.BytesIO()
with Image.open(f) as img:
if self.optimizeTransparency:
# LUT from Photoshop curve: (209, 182) (237, 245)
img.putalpha(img.split()[-1].filter(ImageFilter.GaussianBlur(3)).point((
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06,
0x06, 0x07, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x09, 0x09, 0x09, 0x0A, 0x0A, 0x0A, 0x0B, 0x0B,
0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0E, 0x0E, 0x0F, 0x0F, 0x10, 0x10, 0x10, 0x11, 0x12, 0x12, 0x13,
0x13, 0x14, 0x14, 0x15, 0x15, 0x16, 0x17, 0x17, 0x18, 0x19, 0x19, 0x1A, 0x1B, 0x1B, 0x1C, 0x1D,
0x1E, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x29, 0x2A,
0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3B, 0x3C,
0x3D, 0x3E, 0x40, 0x41, 0x42, 0x43, 0x45, 0x46, 0x47, 0x49, 0x4A, 0x4C, 0x4D, 0x4F, 0x50, 0x51,
0x53, 0x55, 0x56, 0x58, 0x59, 0x5B, 0x5C, 0x5E, 0x60, 0x61, 0x63, 0x65, 0x67, 0x68, 0x6A, 0x6C,
0x6E, 0x70, 0x71, 0x73, 0x75, 0x77, 0x79, 0x7B, 0x7D, 0x7F, 0x81, 0x83, 0x85, 0x87, 0x89, 0x8C,
0x8E, 0x90, 0x92, 0x94, 0x97, 0x99, 0x9B, 0x9D, 0xA0, 0xA2, 0xA5, 0xA7, 0xA9, 0xAC, 0xAE, 0xB1,
0xB3, 0xB6, 0xB9, 0xBB, 0xBE, 0xC0, 0xC3, 0xC6, 0xC8, 0xCB, 0xCE, 0xD0, 0xD3, 0xD5, 0xD8, 0xDA,
0xDC, 0xDF, 0xE1, 0xE3, 0xE5, 0xE8, 0xEA, 0xEB, 0xED, 0xEF, 0xF1, 0xF2, 0xF4, 0xF5, 0xF6, 0xF7,
0xF8, 0xF9, 0xFA, 0xFB, 0xFB, 0xFC, 0xFC, 0xFD, 0xFD, 0xFE, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF,
)).convert('1'))
img.save(b, 'gif')
os.remove(f)
img = Image.open(b)
if 'transparency' in img.info:
paletteMap = list(range(256))
paletteMap[0], paletteMap[img.info['transparency']] = paletteMap[img.info['transparency']], paletteMap[0]
img = img.remap_palette(paletteMap)
img.info['transparency'] = 0
frameImgs.append(img)
os.makedirs(os.path.split(self.outputPath)[0], exist_ok=True)
frameImgs[0].save(self.outputPath, save_all=True, optimize=True, loop=0, duration=self.durations, append_images=frameImgs[1:], disposal=2)
class SplitGIFTask(AbstractTask):
def __init__(
self,
outputCallback: typing.Callable[[str], None],
progressValue: list[int | float],
inputPath: str, outputPath: str,
config: param.REConfigParams,
queue: collections.deque[AbstractTask],
optimizeTransparency: bool,
) -> None:
super().__init__(outputCallback)
self.progressValue = progressValue
self.inputPath = inputPath
self.outputPath = outputPath
self.config = config
self.queue = queue
self.optimizeTransparency = optimizeTransparency
def run(self) -> None:
frames = []
durations = []
tasks = []
with Image.open(self.inputPath) as img:
for f in ImageSequence.Iterator(img):
f: Image.Image
frameSrcPath = tempfile.mktemp('.png' if self.optimizeTransparency else '.webp')
frameDstPath = tempfile.mktemp('.png' if self.optimizeTransparency else '.webp')
d = f.info.get('duration', 0)
if self.optimizeTransparency:
f = f.convert('RGBA')
with Image.new('RGBA', img.size, (255, 255, 255, 255)) as g:
g.alpha_composite(f)
g.putalpha(f.split()[-1])
g.save(frameSrcPath, lossless=True)
else:
f.save(frameSrcPath, lossless=True)
self.outputCallback(f'Frame #{len(frames)}: {frameSrcPath} -> {frameDstPath} Duration: {d}\n')
frames.append(frameDstPath)
durations.append(d)
tasks.append(RESpawnTask(self.outputCallback, self.progressValue, frameSrcPath, frameDstPath, self.config, True))
self.progressValue[2] += 1
self.progressValue[2] -= 1
if self.config.customCommand:
t = tempfile.mktemp('.gif')
tasks.append(MergeGIFTask(self.outputCallback, t, frames, durations, self.optimizeTransparency))
tasks.append(CustomCompressTask(self.outputCallback, t, self.outputPath, self.config.customCommand, True))
else:
tasks.append(MergeGIFTask(self.outputCallback, self.outputPath, frames, durations, self.optimizeTransparency))
tasks.reverse()
for t in tasks:
self.queue.appendleft(t)
class LossyCompressTask(AbstractTask):
def __init__(
self,
outputCallback: typing.Callable[[str], None],
inputPath: str, outputPath: str,
quality: int,
removeInput: bool = False,
) -> None:
super().__init__(outputCallback)
self.inputPath = inputPath
self.outputPath = outputPath
self.quality = quality
self.removeInput = removeInput
def run(self) -> None:
self.outputCallback(f'Compressing {self.inputPath} to {self.outputPath} with quality {self.quality}\n')
os.makedirs(os.path.split(self.outputPath)[0], exist_ok=True)
with Image.open(self.inputPath) as img:
match os.path.splitext(self.outputPath)[1].lower():
case '.webp':
img.save(self.outputPath, quality=self.quality, method=6)
case '.jpg' | '.jpeg':
if img.mode == 'RGBA':
img = img.convert('RGB')
self.outputCallback('Discarding alpha channel to compress the RGBA image to JPEG\n')
img.save(self.outputPath, quality=self.quality, optimize=True, progressive=True)
if self.removeInput:
os.remove(self.inputPath)
class CustomCompressTask(AbstractTask):
def __init__(
self,
outputCallback: typing.Callable[[str], None],
inputPath: str, outputPath: str,
commandTemplate: str,
removeInput: bool = False,
) -> None:
super().__init__(outputCallback)
self.inputPath = inputPath
self.outputPath = outputPath
self.commandTemplate = commandTemplate
self.removeInput = removeInput
def run(self) -> None:
cmd = []
for x in shlex.split(self.commandTemplate):
if x == '{input}':
cmd.append(self.inputPath)
elif x == '{output}':
cmd.append(self.outputPath)
elif (m := re.search(r'^{output:(.+)}$', x)):
cmd.append(f'{os.path.splitext(self.outputPath)[0]}.{m.group(1)}')
else:
cmd.append(x)
self.outputCallback(f'Compressing {self.inputPath} with command: {shlex.join(cmd)}\n')
os.makedirs(os.path.split(self.outputPath)[0], exist_ok=True)
with subprocess.Popen(
cmd,
stderr=subprocess.PIPE,
universal_newlines=True,
encoding='utf-8',
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0,
) as p:
for line in p.stderr:
self.outputCallback(line)
if p.returncode:
raise subprocess.CalledProcessError(p.returncode, cmd)
if self.removeInput:
os.remove(self.inputPath)
def taskRunner(
queue: collections.deque[AbstractTask],
pauseEvent: threading.Event,
outputCallback: typing.Callable[[str], None],
completeCallback: typing.Callable[[bool], None],
failCallback: typing.Callable[[Exception], None],
finallyCallback: typing.Callable[[], None],
ignoreError: bool,
) -> None:
counter = 0
withError = False
while queue:
try:
pauseEvent.wait()
ts = time.perf_counter()
queue.popleft().run()
te = time.perf_counter()
outputCallback(f'Task #{counter} completed in {round((te - ts) * 1000)}ms.\n')
counter += 1
except Exception as ex:
withError = True
outputCallback(traceback.format_exc())
failCallback(ex)
if not ignoreError:
finallyCallback()
return
completeCallback(withError)
finallyCallback()