-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
REAL-Video-Enhancer.py
537 lines (479 loc) · 20.3 KB
/
REAL-Video-Enhancer.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import sys
import os
# patch for macos
if sys.platform == "darwin":
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# this goes one step up, and goes into the actual directory. This is where backend will be copied to.
os.chdir("..")
import math
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QFileDialog,
QMessageBox,
)
from PySide6.QtGui import QIcon
from src.Util import log
from mainwindow import Ui_MainWindow
from PySide6 import QtSvg # Import the QtSvg module so svg icons can be used on windows
from src.version import version
from src.InputHandler import VideoLoader
from src.ModelHandler import getCustomModelScale
# other imports
from src.Util import (
getOSInfo,
get_gpu_info,
getRAMAmount,
getCPUInfo,
checkForWritePermissions,
getAvailableDiskSpace,
copyFile,
createDirectory,
)
from src.constants import CUSTOM_MODELS_PATH
from src.ui.ProcessTab import ProcessTab
from src.ui.DownloadTab import DownloadTab
from src.ui.SettingsTab import SettingsTab, Settings
from src.ui.HomeTab import HomeTab
from src.Backendhandler import BackendHandler
from src.ModelHandler import totalModels
from src.ui.AnimationHandler import AnimationHandler
from src.ui.QTstyle import Palette
from src.ui.QTcustom import RegularQTPopup
class MainWindow(QMainWindow, Ui_MainWindow):
"""Main window class for the REAL Video Enhancer application.
This class extends the QMainWindow and Ui_MainWindow classes to create the main window of the application.
It sets up the user interface, connects buttons to switch menus, and handles various functionalities such as rendering, file selection, and backend setup.
Attributes:
homeDir (str): The home directory path.
interpolateTimes (int): The number of times to interpolate frames.
upscaleTimes (int): The number of times to upscale frames.
pipeInFrames (None): Placeholder for input frames.
latestPreviewImage (None): Placeholder for the latest preview image.
aspect_ratio (float): The aspect ratio of the window.
Methods:
__init__(): Initializes the MainWindow class.
QButtonConnect(): Connects buttons to switch menus.
setupBackendDeps(): Sets up the backend dependencies.
switchToHomePage(): Switches to the home page.
switchToProcessingPage(): Switches to the processing page.
switchToSettingsPage(): Switches to the settings page.
switchToDownloadPage(): Switches to the download page.
recursivlyCheckIfDepsOnFirstInstallToMakeSureUserHasInstalledAtLeastOneBackend(): Recursively checks if at least one backend is installed.
startRender(): Starts the rendering process.
disableProcessPage(): Disables the process page.
enableProcessPage(): Enables the process page.
getAvailableBackends(): Retrieves the available backends.
openInputFile(): Opens an input video file.
openOutputFolder(): Opens an output folder.
killRenderProcess(): Terminates the render process.
closeEvent(event): Handles the close event of the main window."""
def __init__(self):
super().__init__()
# set up base variables
self.homeDir = os.path.expanduser("~")
self.pipeInFrames = None
self.latestPreviewImage = None
self.videoWidth = None
self.videoHeight = None
self.isVideoLoaded = False
# setup application
# Set up the user interface from Designer.
self.setupUi(self)
backendHandler = BackendHandler(self)
backendHandler.enableCorrectBackends()
backendHandler.setupBackendDeps()
self.backends, self.fullOutput = (
backendHandler.recursivlyCheckIfDepsOnFirstInstallToMakeSureUserHasInstalledAtLeastOneBackend(
firstIter=True
)
)
backendHandler.hideUninstallButtons()
backendHandler.showUninstallButton(self.backends)
icon_path = ":/icons/icons/logo-v2.svg"
self.setWindowIcon(QIcon(icon_path))
QApplication.setWindowIcon(QIcon(icon_path))
self.setWindowTitle("REAL Video Enhancer")
self.setPalette(QApplication.style().standardPalette())
self.setMinimumSize(1100, 700)
self.aspect_ratio = self.width() / self.height()
# set default home page
self.stackedWidget.setCurrentIndex(0)
self.QConnect()
# set up tabs
self.backendComboBox.addItems(self.backends)
printOut = (
"------REAL Video Enhancer------\n"
+ "System Information: \n"
+ "OS: "
+ getOSInfo()
+ "\n"
+ "CPU: "
+ getCPUInfo()
+ "\n"
+ "GPU: "
+ get_gpu_info()
+ "\n"
+ "RAM: "
+ getRAMAmount()
+ "\n"
+ "Available Disk Space: "
+ str(round(getAvailableDiskSpace(), 2))
+ "GB"
+ "\n"
+ "-------------------------------------------\n"
+ "Software Information: \n"
+ f"REAL Video Enhancer Version: {version}\n"
+ self.fullOutput
)
self.systemInfoText.setText(printOut)
log(printOut)
# process the output
for line in self.fullOutput.lower().split("\n"):
if "half precision support:" in line:
halfPrecisionSupport = "true" in line
settings = Settings()
settings.readSettings()
self.settings = settings
self.processTab = ProcessTab(
parent=self,
)
self.homeTab = HomeTab(parent=self)
self.downloadTab = DownloadTab(parent=self, backends=self.backends)
self.settingsTab = SettingsTab(
parent=self, halfPrecisionSupport=halfPrecisionSupport
)
# Startup Animation
self.animationHandler = AnimationHandler()
self.animationHandler.fadeInAnimation(self)
def QConnect(self):
# connect buttons to switch menus
self.homeBtn.clicked.connect(self.switchToHomePage)
self.processBtn.clicked.connect(self.switchToProcessingPage)
self.settingsBtn.clicked.connect(self.switchToSettingsPage)
self.downloadBtn.clicked.connect(self.switchToDownloadPage)
# connect getting default output file
def setButtonsUnchecked(self, buttonToIgnore):
buttons = [
self.homeBtn,
self.processBtn,
self.settingsBtn,
self.downloadBtn,
]
for button in buttons:
if button != buttonToIgnore:
button.setChecked(False)
else:
button.setChecked(True)
# switch menus
def switchToHomePage(self):
self.animationHandler.fadeOutAnimation(self.stackedWidget)
self.stackedWidget.setCurrentWidget(self.homePage)
self.setButtonsUnchecked(self.homeBtn)
self.animationHandler.fadeInAnimation(self.stackedWidget)
def switchToProcessingPage(self):
self.animationHandler.fadeOutAnimation(self.stackedWidget)
self.stackedWidget.setCurrentWidget(self.procPage)
self.setButtonsUnchecked(self.processBtn)
self.animationHandler.fadeInAnimation(self.stackedWidget)
def switchToSettingsPage(self):
self.animationHandler.fadeOutAnimation(self.stackedWidget)
self.stackedWidget.setCurrentWidget(self.settingsPage)
self.setButtonsUnchecked(self.settingsBtn)
self.animationHandler.fadeInAnimation(self.stackedWidget)
def switchToDownloadPage(self):
self.animationHandler.fadeOutAnimation(self.stackedWidget)
self.stackedWidget.setCurrentWidget(self.downloadPage)
self.setButtonsUnchecked(self.downloadBtn)
self.animationHandler.fadeInAnimation(self.stackedWidget)
def updateVideoGUIText(self):
if self.isVideoLoaded:
upscaleModelName = self.upscaleModelComboBox.currentText()
interpolateModelName = self.interpolateModelComboBox.currentText()
interpolateTimes = self.getInterpolationMultiplier(interpolateModelName)
scale = self.getUpscaleModelScale(upscaleModelName)
text = (
f"FPS: {round(self.videoFps,0)} -> {round(self.videoFps*interpolateTimes,0)}\n"
+ f"Resolution: {self.videoWidth}x{self.videoHeight} -> {self.videoWidth*scale}x{self.videoHeight*scale}\n"
+ f"Frame Count: {self.videoFrameCount} -> {int(round(self.videoFrameCount * interpolateTimes,0))}\n"
+ f"Bitrate: {self.videoBitrate}\n"
+ f"Encoder: {self.videoEncoder}\n"
+ f"Container: {self.videoContainer}\n"
)
self.videoInfoTextEdit.setFontPointSize(10)
self.videoInfoTextEdit.setText(text)
def getInterpolationMultiplier(self, interpolateModelName):
if interpolateModelName == "None":
interpolateTimes = 1
else:
interpolateTimes = self.interpolationMultiplierSpinBox.value()
return interpolateTimes
def getUpscaleModelScale(self, upscaleModelName):
if upscaleModelName == "None" or upscaleModelName == "":
scale = 1
else:
scale = totalModels[upscaleModelName][2]
return scale
def setDefaultOutputFile(self, outputDirectory):
"""
Sets the default output file for the video enhancer.
Parameters:
- useDefaultVideoPath (bool): Flag indicating whether to use the default video path for the output file.
Returns:
None
"""
# check if there is a video loaded
if self.isVideoLoaded:
inputFile = self.inputFileText.text()
upscaleModelName = self.upscaleModelComboBox.currentText()
interpolateModelName = self.interpolateModelComboBox.currentText()
interpolateTimes = self.getInterpolationMultiplier(interpolateModelName)
scale = self.getUpscaleModelScale(upscaleModelName)
file_name = os.path.splitext(os.path.basename(inputFile))[0]
base_file_name = f"{file_name}_{round(interpolateTimes*self.videoFps,0)}fps_{scale*self.videoWidth}x{scale*self.videoHeight}"
output_file = os.path.join(
outputDirectory,
f"{base_file_name}.mkv",
)
iteration = 0
while os.path.isfile(output_file):
output_file = os.path.join(
outputDirectory,
f"{base_file_name}_({iteration}).mkv",
)
iteration += 1
self.outputFileText.setText(output_file)
return output_file
def updateVideoGUIDetails(self):
isInterpolate = self.interpolateModelComboBox.currentText() != "None"
isUpscale = self.upscaleModelComboBox.currentText() != "None"
self.interpolationContainer.setVisible(
isInterpolate
)
self.interpolateContainer_2.setVisible(
isInterpolate
)
# set interpolation container visible if interpolate model is not none
self.upscaleContainer.setVisible(
isUpscale
)
self.settings.readSettings()
self.setDefaultOutputFile(self.settings.settings["output_folder_location"])
self.updateVideoGUIText()
def startRender(self):
if not self.isVideoLoaded:
RegularQTPopup("Please select a video file!")
return
if not checkForWritePermissions(os.path.dirname(self.outputFileText.text())):
RegularQTPopup("No write permissions to the output directory!")
return
if (
self.interpolateModelComboBox.currentText() == "None"
and self.upscaleModelComboBox.currentText() == "None"
):
RegularQTPopup("Please select at least one model!")
return
self.startRenderButton.setEnabled(False)
self.progressBar.setRange(
0,
# only set the range to multiply the frame count if the method is interpolate
int(
self.videoFrameCount
* math.ceil(self.interpolationMultiplierSpinBox.value())
)
if self.interpolateModelComboBox.currentText() != "None"
else self.videoFrameCount,
)
self.disableProcessPage()
self.processTab.run(
inputFile=self.inputFileText.text(),
outputPath=self.outputFileText.text(),
videoWidth=self.videoWidth,
videoHeight=self.videoHeight,
videoFps=self.videoFps,
tilingEnabled=self.tilingCheckBox.isChecked(),
tilesize=self.tileSizeComboBox.currentText(),
videoFrameCount=self.videoFrameCount,
backend=self.backendComboBox.currentText(),
interpolateModel=self.interpolateModelComboBox.currentText(),
upscaleModel=self.upscaleModelComboBox.currentText(),
interpolateTimes=self.getInterpolationMultiplier(
self.interpolateModelComboBox.currentText()
),
benchmarkMode=self.benchmarkModeCheckBox.isChecked(),
sloMoMode=self.sloMoModeCheckBox.isChecked(),
dyanmicScaleOpticalFlow=self.dynamicScaledOpticalFlowCheckBox.isChecked(),
ensemble=self.ensembleCheckBox.isChecked(),
)
def disableProcessPage(self):
for child in self.generalSettings.children():
child.setEnabled(False)
for child in self.advancedSettings.children():
child.setEnabled(False)
def enableProcessPage(self):
for child in self.generalSettings.children():
child.setEnabled(True)
for child in self.advancedSettings.children():
child.setEnabled(True)
def loadVideo(self, inputFile):
videoHandler = VideoLoader(inputFile)
videoHandler.loadVideo()
if (
not videoHandler.isValidVideo()
): # this handles case for invalid youtube link and invalid video file
RegularQTPopup("Not a valid input!")
return
videoHandler.getData()
self.videoWidth = videoHandler.width
self.videoHeight = videoHandler.height
self.videoFps = videoHandler.fps
self.videoLength = videoHandler.duration
self.videoFrameCount = videoHandler.total_frames
self.videoEncoder = videoHandler.codec_str
self.videoBitrate = videoHandler.bitrate
self.videoContainer = videoHandler.videoContainer
self.inputFileText.setText(inputFile)
self.outputFileText.setEnabled(True)
self.outputFileSelectButton.setEnabled(True)
self.isVideoLoaded = True
self.updateVideoGUIDetails()
# input file button
def openInputFile(self):
"""
Opens a video file and checks if it is valid,
if it is valid, it will set self.inputFile to the input file, and set the text input field to the input file path.
if it is not valid, it will give a warning to the user.
> IMPLEMENT AFTER SELECT AI > Last, It will enable the output select button, and auto create a default output file
*NOTE
This function will set self.videoWidth, self.videoHeight, and self.videoFps
"""
fileFilter = "Video files (*.mp4 *.mov *.webm *.mkv)"
inputFile, _ = QFileDialog.getOpenFileName(
parent=self,
caption="Select File",
dir=self.homeDir,
filter=fileFilter,
)
self.loadVideo(inputFile)
def importCustomModel(self, format: str):
"""
*args
format: str
The format of the model to import (pytorch, ncnn)
"""
if format == "pytorch":
fileFilter = "PyTorch Model (*.pth)"
modelFile, _ = QFileDialog.getOpenFileName(
parent=self,
caption="Select PyTorch Model",
dir=self.homeDir,
filter=fileFilter,
)
if getCustomModelScale(os.path.basename(modelFile)):
outputModelPath = os.path.join(
CUSTOM_MODELS_PATH, os.path.basename(modelFile)
)
copyFile(modelFile, CUSTOM_MODELS_PATH)
if os.path.isfile(outputModelPath):
RegularQTPopup(
"Model imported successfully!\nPlease restart the app for the changes to take effect."
)
else:
RegularQTPopup("Failed to import model!\nPlease try again.")
else:
RegularQTPopup(
"Custom model does not have a valid\nupscale factor in the name.\nExample: 2x or x2. Skipping import..."
)
elif format == "ncnn":
binFileFilter = "NCNN Bin (*.bin)"
modelBinFile, _ = QFileDialog.getOpenFileName(
parent=self,
caption="Select NCNN Bin",
dir=self.homeDir,
filter=binFileFilter,
)
if getCustomModelScale(os.path.basename(modelFile)):
if modelBinFile == "":
RegularQTPopup("Please select a bin file!")
return
modelParamFile, _ = QFileDialog.getOpenFileName(
parent=self,
caption="Select NCNN Param",
dir=os.path.dirname(modelBinFile),
filter=os.path.basename(modelBinFile).replace(".bin", ".param"),
)
if modelParamFile == "":
RegularQTPopup("Please select a param file!")
return
outputModelFolder = os.path.join(
CUSTOM_MODELS_PATH,
os.path.basename(modelBinFile).replace(".bin", ""),
)
createDirectory(outputModelFolder)
outputBinPath = os.path.join(
outputModelFolder, os.path.basename(modelBinFile)
)
copyFile(modelBinFile, outputModelFolder)
outputParamPath = os.path.join(
outputModelFolder, os.path.basename(modelParamFile)
)
copyFile(modelParamFile, outputModelFolder)
if os.path.isfile(outputBinPath) and os.path.isfile(outputParamPath):
RegularQTPopup(
"Model imported successfully!\nPlease restart the app for the changes to take effect."
)
else:
RegularQTPopup("Failed to import model!\nPlease try again.")
else:
RegularQTPopup(
"Custom model does not have a valid\nupscale factor in the name.\nExample: 2x or x2. Skipping import..."
)
# output file button
def openOutputFolder(self):
"""
Opens a folder,
sets the directory that is selected to the self.outputFolder variable
sets the outputFileText to the output directory
It will also read the input file name, and generate an output file based on it.
"""
outputFolder = QFileDialog.getExistingDirectory(
self,
caption="Select Output Directory",
dir=self.homeDir,
)
self.outputFileText.setText(
os.path.join(outputFolder, self.setDefaultOutputFile(outputFolder))
)
def closeEvent(self, event):
reply = QMessageBox.question(
self,
"",
"Are you sure you want to exit?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No, # type: ignore
)
if reply == QMessageBox.Yes: # type: ignore
self.processTab.killRenderProcess()
event.accept()
else:
event.ignore()
def main():
app = QApplication(sys.argv)
app.setStyle("Fusion")
# setting the pallette
app.setPalette(Palette())
window = MainWindow()
if len(sys.argv) > 1:
if sys.argv[1] == "--fullscreen":
window.showFullScreen()
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "--debug":
import trace
tracer = trace.Trace(
ignoredirs=[sys.prefix, sys.exec_prefix], trace=True, count=False
)
tracer.run("main()")
else:
main()