-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvsr_gui.py
More file actions
404 lines (337 loc) · 15.3 KB
/
Copy pathvsr_gui.py
File metadata and controls
404 lines (337 loc) · 15.3 KB
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
import sys
import os
import signal
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QLabel, QLineEdit, QPushButton,
QFileDialog, QCheckBox, QGroupBox, QMessageBox,
QProgressBar, QComboBox, QTextEdit)
from PyQt6.QtCore import Qt, QProcess, QRegularExpression
class FileDropWidget(QWidget):
def __init__(self, placeholder_text="Drop file here or click to browse", parent=None):
super().__init__(parent)
self.placeholder_text = placeholder_text
self.setAcceptDrops(True)
self.file_path = ""
self.layout = QVBoxLayout(self)
self.label = QLabel(self.placeholder_text)
self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.layout.addWidget(self.label)
self.setStyleSheet("""
FileDropWidget {
border: 2px dashed #aaa;
border-radius: 5px;
padding: 10px;
min-height: 60px;
}
FileDropWidget:hover {
border-color: #555;
}
""")
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
files = [u.toLocalFile() for u in event.mimeData().urls()]
if files:
self.file_path = files[0]
self.update_label()
def mousePressEvent(self, event):
file_path, _ = QFileDialog.getOpenFileName(self, "Select File")
if file_path:
self.file_path = file_path
self.update_label()
def update_label(self):
if self.file_path:
self.label.setText(os.path.basename(self.file_path))
else:
self.label.setText(self.placeholder_text)
def get_file_path(self):
return self.file_path
def set_file_path(self, path):
self.file_path = path
self.update_label()
class VSRGUIApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("VSR GUI")
self.setMinimumWidth(600)
# Main widget and layout
main_widget = QWidget()
main_layout = QVBoxLayout(main_widget)
# Model type selection
model_type_layout = QHBoxLayout()
model_type_layout.addWidget(QLabel("Model Type:"))
self.model_type_combo = QComboBox()
self.model_type_combo.addItems(["PyTorch (.pth)", "ONNX (.onnx)"])
self.model_type_combo.currentIndexChanged.connect(self.on_model_type_changed)
model_type_layout.addWidget(self.model_type_combo)
model_type_layout.addStretch(1)
main_layout.addLayout(model_type_layout)
# Input video section
input_group = QGroupBox("Input Video")
input_layout = QVBoxLayout()
self.input_widget = FileDropWidget("Drop video file here or click to browse")
input_layout.addWidget(self.input_widget)
input_group.setLayout(input_layout)
# Model selection section
model_group = QGroupBox("Model")
model_layout = QHBoxLayout()
self.model_path_edit = QLineEdit()
self.model_path_edit.setReadOnly(True)
self.model_path_edit.setPlaceholderText("Select a model file (.pth or .onnx)")
model_browse_btn = QPushButton("Browse")
model_browse_btn.clicked.connect(self.browse_model)
model_layout.addWidget(self.model_path_edit, 3)
model_layout.addWidget(model_browse_btn, 1)
model_group.setLayout(model_layout)
# Output video section
output_group = QGroupBox("Output")
output_layout = QHBoxLayout()
self.output_path_edit = QLineEdit()
self.output_path_edit.setPlaceholderText("Specify output video path")
output_browse_btn = QPushButton("Browse")
output_browse_btn.clicked.connect(self.browse_output)
output_layout.addWidget(self.output_path_edit, 3)
output_layout.addWidget(output_browse_btn, 1)
output_group.setLayout(output_layout)
# Options section
options_group = QGroupBox("Options")
options_layout = QVBoxLayout()
codec_layout = QHBoxLayout()
codec_layout.addWidget(QLabel("Video Codec:"))
self.codec_combo = QComboBox()
# Add common codec options
codec_options = [
"libx264", # CPU H.264
"libx265", # CPU H.265
"dnxhd", # DNxHD (high quality)
"prores", # ProRes (high quality)
"Custom..." # Allow custom codec input
]
self.codec_combo.addItems(codec_options)
self.codec_combo.setCurrentText("h264_nvenc")
self.codec_combo.currentTextChanged.connect(self.on_codec_changed)
codec_layout.addWidget(self.codec_combo)
# Custom codec input that appears when "Custom..." is selected
self.custom_codec_input = QLineEdit()
self.custom_codec_input.setPlaceholderText("Enter custom codec")
self.custom_codec_input.setVisible(False)
codec_layout.addWidget(self.custom_codec_input)
options_layout.addLayout(codec_layout)
options_group.setLayout(options_layout)
# Process button and Stop button in horizontal layout
button_layout = QHBoxLayout()
self.process_btn = QPushButton("Process Video")
self.process_btn.clicked.connect(self.process_video)
self.process_btn.setStyleSheet("font-weight: bold; height: 30px;")
self.stop_btn = QPushButton("Stop Processing")
self.stop_btn.clicked.connect(self.stop_processing)
self.stop_btn.setStyleSheet("height: 30px;")
self.stop_btn.setToolTip("Forcibly stop the processing. This will result in an incomplete output file.")
self.stop_btn.setEnabled(False)
button_layout.addWidget(self.process_btn)
button_layout.addWidget(self.stop_btn)
# Progress bar and FPS in horizontal layout
progress_layout = QHBoxLayout()
# Progress bar (left side)
self.progress_bar = QProgressBar()
self.progress_bar.setVisible(False)
self.progress_bar.setMinimum(0)
self.progress_bar.setMaximum(100)
self.progress_bar.setStyleSheet("""
QProgressBar {
border: 1px solid #ccc;
border-radius: 5px;
text-align: center;
height: 25px;
min-height: 25px;
margin: 0px;
padding: 0px;
}
QProgressBar::chunk {
background-color: #4CAF50; /* Green color */
width: 10px;
margin: 0px;
}
""")
progress_layout.addWidget(self.progress_bar)
# FPS label (right side)
self.fps_label = QLabel("FPS: --")
self.fps_label.setMinimumWidth(100) # Give it some minimum width
progress_layout.addWidget(self.fps_label)
# Log box
log_group = QGroupBox("Processing Log")
log_layout = QVBoxLayout()
self.log_box = QTextEdit()
self.log_box.setReadOnly(True)
self.log_box.setMinimumHeight(150)
log_layout.addWidget(self.log_box)
log_group.setLayout(log_layout)
# Add everything to main layout
main_layout.addWidget(input_group)
main_layout.addWidget(model_group)
main_layout.addWidget(output_group)
main_layout.addWidget(options_group)
main_layout.addLayout(button_layout)
main_layout.addLayout(progress_layout) # Add the combined progress/FPS layout
main_layout.addWidget(log_group)
# Initialize QProcess
self.process = None
self.total_frames = 0
self.current_frame = 0
self.setCentralWidget(main_widget)
def on_model_type_changed(self, index):
# Update placeholder text and file filter based on selection
if index == 0: # PyTorch
self.model_path_edit.setPlaceholderText("Select a PyTorch model file (.pth)")
else: # ONNX
self.model_path_edit.setPlaceholderText("Select an ONNX model file (.onnx)")
# Clear current selection
self.model_path_edit.clear()
def browse_model(self):
if self.model_type_combo.currentIndex() == 0: # PyTorch
file_path, _ = QFileDialog.getOpenFileName(
self, "Select PyTorch Model File", "", "PyTorch Models (*.pth)"
)
else: # ONNX
file_path, _ = QFileDialog.getOpenFileName(
self, "Select ONNX Model File", "", "ONNX Models (*.onnx)"
)
if file_path:
self.model_path_edit.setText(file_path)
def browse_output(self):
file_path, _ = QFileDialog.getSaveFileName(
self, "Save Output Video", "", "Video Files (*.mkv)"
)
if file_path:
if not file_path.endswith('.mkv'):
file_path += '.mkv'
self.output_path_edit.setText(file_path)
def process_video(self):
# Validate inputs
input_path = self.input_widget.get_file_path()
model_path = self.model_path_edit.text()
output_path = self.output_path_edit.text()
if not input_path:
QMessageBox.warning(self, "Missing Input", "Please select an input video file.")
return
if not model_path:
QMessageBox.warning(self, "Missing Model", "Please select a model file.")
return
if not output_path:
QMessageBox.warning(self, "Missing Output", "Please specify an output path.")
return
# Determine which codec to use
if self.codec_combo.currentText() == "Custom...":
codec = self.custom_codec_input.text()
if not codec:
QMessageBox.warning(self, "Missing Codec", "Please enter a custom codec.")
return
else:
codec = self.codec_combo.currentText()
# Determine which script to run based on model type
if self.model_type_combo.currentIndex() == 0: # PyTorch
script_name = "test_vsr.py"
else: # ONNX
script_name = "test_onnx.py"
# Build command
cmd = [
"python", script_name,
"--model_path", model_path,
"--input", input_path,
"--output", output_path,
"--video", codec,
"--gui-mode"
]
# Clear previous log
self.log_box.clear()
# Reset frame counters
self.total_frames = 0
self.current_frame = 0
# Show progress bar with determinate mode initially
self.progress_bar.setVisible(True)
self.progress_bar.setValue(0)
# Disable process button, enable stop button
self.process_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
# Create and start QProcess
self.process = QProcess()
self.process.readyReadStandardOutput.connect(self.handle_stdout)
self.process.readyReadStandardError.connect(self.handle_stderr)
self.process.finished.connect(self.process_finished)
try:
self.log_box.append("Starting video processing...")
self.log_box.append(f"Command: {' '.join(cmd)}\n")
self.process.start(cmd[0], cmd[1:])
except Exception as e:
self.log_box.append(f"Error: {str(e)}")
self.process_finished()
def stop_processing(self):
if self.process and self.process.state() != QProcess.ProcessState.NotRunning:
self.log_box.append("\nStopping process...")
try:
# Terminate the process gracefully
self.process.terminate()
# Give it a few seconds to terminate gracefully
if not self.process.waitForFinished(3000):
# If it didn't terminate, kill it forcefully
self.log_box.append("Process did not terminate gracefully, forcing kill...")
self.process.kill()
except Exception as e:
self.log_box.append(f"Error while stopping process: {str(e)}")
# If we can't terminate, try to kill it
try:
self.process.kill()
except:
pass
def handle_stdout(self):
data = self.process.readAllStandardOutput()
stdout = bytes(data).decode()
# Check for our special GUI progress format
if 'PROGRESS:' in stdout:
# Split the line into progress and FPS parts
parts = stdout.split('PROGRESS:')[1].strip().split('|')
# Handle progress
if len(parts) >= 1:
progress_parts = parts[0].split('/')
if len(progress_parts) == 2:
self.current_frame = int(progress_parts[0])
# If this is the first time we're getting the total
if self.total_frames == 0:
self.total_frames = int(progress_parts[1])
# Now that we know the total, set the progress bar maximum
self.progress_bar.setMaximum(self.total_frames)
# Update progress bar
self.progress_bar.setValue(self.current_frame)
# Handle FPS
if len(parts) >= 2 and 'FPS:' in parts[1]:
try:
fps = float(parts[1].split(':')[1])
self.fps_label.setText(f"FPS: {fps:.2f}")
except (IndexError, ValueError):
pass
# Always append to log
self.log_box.append(stdout)
def handle_stderr(self):
data = self.process.readAllStandardError()
stderr = bytes(data).decode()
self.log_box.append(stderr)
def process_finished(self, exit_code=None, exit_status=None):
self.progress_bar.setVisible(False)
self.process_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
self.fps_label.setText("FPS: --") # Reset FPS display
self.log_box.append("\nProcessing completed!")
self.process = None
def on_codec_changed(self, text):
if text == "Custom...":
self.custom_codec_input.setVisible(True)
else:
self.custom_codec_input.setVisible(False)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = VSRGUIApp()
window.show()
sys.exit(app.exec())