-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
356 lines (309 loc) · 12.2 KB
/
main.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
"""
The Anime Scripter is a tool that allows you to automate the process of
Video Upscaling, Interpolating and many more all inside of the Adobe Suite
Copyright (C) 2023-present Nilas Tiago
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/NevermindNilas/TheAnimeScripter
"""
import os
import sys
import logging
import warnings
from platform import system
from signal import signal, SIGINT, SIG_DFL
from time import time
from concurrent.futures import ThreadPoolExecutor
from src.utils.argumentsChecker import createParser
from src.utils.getVideoMetadata import getVideoMetadata
from src.utils.initializeModels import initializeModels, Segment, Depth, AutoClip
from src.utils.ffmpegSettings import BuildBuffer, WriteBuffer
from src.utils.coloredPrints import green
from src.utils.inputOutputHandler import handleInputOutputs
from src.utils.progressBarLogic import ProgressBarLogic
from queue import Queue
warnings.filterwarnings("ignore")
class VideoProcessor:
def __init__(
self,
args,
results=None,
width: int = None,
height: int = None,
fps: float = None,
totalFrames: int = None,
audio: bool = None,
outputFPS: float = None,
):
self.input = results["videoPath"]
self.output = results["outputPath"]
self.encode_method = results["encodeMethod"]
self.custom_encoder = results["customEncoder"]
self.interpolate = args.interpolate
self.interpolate_factor = args.interpolate_factor
self.interpolate_method = args.interpolate_method
self.upscale = args.upscale
self.upscale_factor = args.upscale_factor
self.upscale_method = args.upscale_method
self.dedup = args.dedup
self.dedup_method = args.dedup_method
self.dedup_sens = args.dedup_sens
self.half = args.half
self.inpoint = args.inpoint
self.outpoint = args.outpoint
self.sharpen = args.sharpen
self.sharpen_sens = args.sharpen_sens
self.segment = args.segment
self.autoclip = args.autoclip
self.autoclip_sens = args.autoclip_sens
self.depth = args.depth
self.depth_method = args.depth_method
self.ffmpeg_path = args.ffmpeg_path
self.ensemble = args.ensemble
self.resize = args.resize
self.resize_factor = args.resize_factor
self.resize_method = args.resize_method
self.custom_model = args.custom_model
self.buffer_limit = args.buffer_limit
self.restore = args.restore
self.restore_method = args.restore_method
self.benchmark = args.benchmark
self.segment_method = args.segment_method
self.scenechange = args.scenechange
self.scenechange_sens = args.scenechange_sens
self.scenechange_method = args.scenechange_method
self.upscale_skip = args.upscale_skip
self.bit_depth = args.bit_depth
self.preview = args.preview
self.forceStatic = args.static
self.depth_quality = args.depth_quality
self.interpolate_skip = args.interpolate_skip
self.decode_threads = args.decode_threads
# Video Metadata
self.width = width
self.height = height
self.fps = fps
self.totalFrames = totalFrames
self.audio = audio
self.outputFPS = outputFPS
logging.info("\n============== Processing Outputs ==============")
if self.resize:
aspectRatio = self.width / self.height
self.width = round(self.width * self.resize_factor / 2) * 2
self.height = round(self.width / aspectRatio / 2) * 2
logging.info(
f"Resizing to {self.width}x{self.height} using {self.resize_method}"
)
if self.autoclip:
logging.info("Detecting scene changes")
AutoClip(self, mainPath)
elif self.depth:
logging.info("Depth Estimation")
Depth(self, mainPath)
elif self.segment:
logging.info("Segmenting video")
Segment(self, mainPath)
else:
self.start()
def processFrame(self, frame):
if self.dedup:
if self.dedup_process(frame):
self.dedupCount += 1
return
if self.scenechange:
self.isSceneChange = self.scenechange_process(frame)
if self.isSceneChange:
self.sceneChangeCounter += 1
if self.restore:
frame = self.restore_process(frame)
if self.interpolate:
if self.isSceneChange:
self.interpolate_process.cacheFrameReset(frame)
else:
self.interpolate_process(frame, self.interpQueue)
if self.upscale:
if self.interpolate:
if self.isSceneChange:
frame = self.upscale_process(frame)
for _ in range(self.interpolate_factor):
self.writeBuffer.write(frame)
else:
while not self.interpQueue.empty():
self.writeBuffer.write(
self.upscale_process(self.interpQueue.get())
)
self.writeBuffer.write(self.upscale_process(frame))
else:
self.writeBuffer.write(self.upscale_process(frame))
else:
if self.interpolate:
if self.isSceneChange or not self.interpQueue.empty():
for _ in range(self.interpolate_factor - 1):
frameToWrite = (
frame if self.isSceneChange else self.interpQueue.get()
)
self.writeBuffer.write(frameToWrite)
self.writeBuffer.write(frame)
if self.preview:
self.preview.add(
frame.squeeze(0).permute(1, 2, 0).mul(255).byte().cpu().numpy()
)
def process(self):
frameCount = 0
self.dedupCount = 0
self.isSceneChange = False
self.sceneChangeCounter = 0
increment = 1 if not self.interpolate else self.interpolate_factor
if self.interpolate:
self.interpQueue = Queue(maxsize=self.interpolate_factor)
try:
with ProgressBarLogic(self.totalFrames * increment) as bar:
for _ in range(self.totalFrames):
self.processFrame(self.readBuffer.read())
frameCount += 1
bar(increment)
if self.readBuffer.isReadFinished():
if self.readBuffer.isQueueEmpty():
break
if self.preview:
self.preview.close()
self.writeBuffer.close()
except Exception as e:
logging.exception(f"Something went wrong while processing the frames, {e}")
logging.info(f"Processed {frameCount} frames")
if self.dedupCount > 0:
logging.info(f"Deduplicated {self.dedupCount} frames")
if self.scenechange:
logging.info(f"Detected {self.sceneChangeCounter} scene changes")
def start(self):
try:
(
self.new_width,
self.new_height,
self.upscale_process,
self.interpolate_process,
self.restore_process,
self.dedup_process,
self.scenechange_process,
) = initializeModels(self)
starTime: float = time()
self.readBuffer = BuildBuffer(
videoInput=self.input,
inpoint=self.inpoint,
outpoint=self.outpoint,
totalFrames=self.totalFrames,
fps=self.fps,
half=self.half,
decodeThreads=self.decode_threads,
resize=self.resize,
resizeMethod=self.resize_method,
width=self.width,
height=self.height,
)
self.writeBuffer = WriteBuffer(
mainPath=mainPath,
input=self.input,
output=self.output,
ffmpegPath=self.ffmpeg_path,
encode_method=self.encode_method,
custom_encoder=self.custom_encoder,
width=self.new_width,
height=self.new_height,
fps=self.outputFPS,
sharpen=self.sharpen,
sharpen_sens=self.sharpen_sens,
grayscale=False,
transparent=False,
audio=self.audio,
benchmark=self.benchmark,
bitDepth=self.bit_depth,
inpoint=self.inpoint,
outpoint=self.outpoint,
preview=self.preview,
)
if self.preview:
from src.utils.previewSettings import Preview
self.preview = Preview()
with ThreadPoolExecutor(max_workers=4 if self.preview else 3) as executor:
executor.submit(self.readBuffer)
executor.submit(self.writeBuffer.start)
executor.submit(self.process)
if self.preview:
executor.submit(self.preview.start)
elapsedTime: float = time() - starTime
fps = (
self.totalFrames
/ elapsedTime
* (1 if not self.interpolate else self.interpolate_factor)
)
logging.info(
f"Total Execution Time: {elapsedTime:.2f} seconds - FPS: {fps:.2f}"
)
print(
green(
f"Total Execution Time: {elapsedTime:.2f} seconds - FPS: {fps:.2f}"
)
)
except Exception as e:
logging.exception(f"Something went wrong while starting the processes, {e}")
if __name__ == "__main__":
sysUsed = system()
if sysUsed == "Windows":
mainPath = os.path.join(os.getenv("APPDATA"), "TheAnimeScripter")
else:
mainPath = os.path.join(
os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),
"TheAnimeScripter",
)
if not os.path.exists(mainPath):
os.makedirs(mainPath)
isFrozen = hasattr(sys, "_MEIPASS")
outputPath = (
os.path.dirname(sys.executable)
if isFrozen
else os.path.dirname(os.path.abspath(__file__))
)
signal(SIGINT, SIG_DFL)
logging.basicConfig(
filename=os.path.join(mainPath, "TAS.log"),
filemode="w",
format="%(message)s",
level=logging.INFO,
)
logging.info("============== Command Line Arguments ==============")
logging.info(f"{' '.join(sys.argv)}\n")
args = createParser(isFrozen, mainPath, outputPath, sysUsed)
outputPath = os.path.join(
(
os.path.dirname(sys.executable)
if isFrozen
else os.path.dirname(os.path.abspath(__file__))
),
"output",
)
results = handleInputOutputs(args, isFrozen, outputPath)
for i in results:
print(green(f"Processing Video: {results[i]['videoPath']}"))
print(green(f"Output Path: {results[i]['outputPath']}"))
width, height, fps, totalFrames, audio = getVideoMetadata(
results[i]["videoPath"], args.inpoint, args.outpoint
)
outputFPS = fps * args.interpolate_factor if args.interpolate else fps
VideoProcessor(
args,
results=results[i],
width=width,
height=height,
fps=fps,
totalFrames=totalFrames,
audio=audio,
outputFPS=outputFPS,
)