-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathVideoSubtitleRemover.py
More file actions
6866 lines (6035 loc) · 280 KB
/
VideoSubtitleRemover.py
File metadata and controls
6866 lines (6035 loc) · 280 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
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Video Subtitle Remover Pro
A professional Windows application for AI-powered subtitle removal from videos
and images. Based on: https://github.com/YaoFANGUK/video-subtitle-remover
Author: SysAdminDoc
See APP_VERSION for the running version -- the docstring deliberately omits
a hardcoded number so there is a single source of truth.
"""
import os
import sys
import json
import math
import uuid
import threading
import subprocess
import time
import tempfile
import logging
import logging.handlers
import traceback
from pathlib import Path
from typing import Optional, List, Tuple, Callable
from dataclasses import dataclass, field
from enum import Enum
from datetime import datetime
# =============================================================================
# LOGGING SETUP -- file + stream, crash handler
# =============================================================================
APP_NAME = "Video Subtitle Remover Pro"
# Single source of truth for the app's version string. Update here and it
# propagates to the banner, header, logs, About dialog, and CHANGELOG cue.
APP_VERSION = "3.12.0"
APP_AUTHOR = "SysAdminDoc"
LOG_DIR = Path(os.environ.get("APPDATA", Path.home())) / "VideoSubtitleRemoverPro"
LOG_DIR.mkdir(parents=True, exist_ok=True)
LOG_FILE = LOG_DIR / "vsr_pro.log"
SETTINGS_FILE = LOG_DIR / "settings.json"
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.StreamHandler(),
logging.handlers.RotatingFileHandler(
LOG_FILE, maxBytes=5 * 1024 * 1024, backupCount=2, encoding='utf-8'),
]
)
logger = logging.getLogger(__name__)
def crash_handler(exc_type, exc_value, exc_tb):
"""Global crash handler -- log to file and show MessageBox."""
msg = ''.join(traceback.format_exception(exc_type, exc_value, exc_tb))
logger.critical(f"UNHANDLED EXCEPTION:\n{msg}")
try:
import tkinter.messagebox as mb
mb.showerror("Fatal Error",
f"{APP_NAME} crashed.\n\n{exc_value}\n\nLog: {LOG_FILE}")
except Exception:
pass
sys.__excepthook__(exc_type, exc_value, exc_tb)
sys.excepthook = crash_handler
# GUI Imports
try:
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from tkinter import font as tkfont
except ImportError:
logger.error("Tkinter not found. Please install Python with Tkinter support.")
sys.exit(1)
try:
from PIL import Image, ImageTk, ImageDraw, ImageFilter
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
logger.warning("Pillow not installed. Image preview will be limited.")
# =============================================================================
# CONFIGURATION & CONSTANTS
# =============================================================================
# =============================================================================
# DESIGN TOKENS -- cohesive, premium dark theme
# =============================================================================
class Theme:
"""Design system. Dark-first, refined tonal layering, calm accents."""
# Surfaces -- deliberate tonal ladder (BG_DARK < BG_SECONDARY < BG_CARD < BG_TERTIARY < BG_RAISED)
BG_DARK = "#06080f" # App background (deepest)
BG_SECONDARY = "#0c111c" # Main panel surface
BG_CARD = "#121927" # Card / inner panel
BG_CARD_HOVER = "#182132" # Card hovered
BG_CARD_SELECTED = "#1a2944" # Card selected (subtle blue tint)
BG_TERTIARY = "#1b2438" # Elevated field (inputs, chips)
BG_RAISED = "#222d44" # Most-elevated surface (toast, popover)
BG_LOG = "#070b13" # Log panel
BG_OVERLAY = "#0a0e17" # Modal / overlay backdrop
# Accents
GREEN_PRIMARY = "#34d399" # Emerald -- success and primary CTA
GREEN_HOVER = "#10b981" # Deeper emerald (hover)
GREEN_PRESS = "#059669" # Pressed
GREEN_MUTED = "#0f3324" # Success tint background
BLUE_PRIMARY = "#60a5fa" # Sky blue -- secondary CTA / info
BLUE_HOVER = "#3b82f6" # Deeper blue (hover)
BLUE_PRESS = "#2563eb" # Pressed
BLUE_MUTED = "#13294a" # Blue tint background
# Text
TEXT_PRIMARY = "#f4f7fd" # Near-white -- primary text
TEXT_SECONDARY = "#c5cfe2" # High-contrast secondary
TEXT_MUTED = "#8391ad" # Support / helper text
TEXT_DISABLED = "#4c5877" # Disabled
# Status
SUCCESS = "#34d399"
SUCCESS_BG = "#0e2e22"
WARNING = "#fbbf24"
WARNING_BG = "#352412"
ERROR = "#f87171"
ERROR_BG = "#351821"
INFO = "#60a5fa"
INFO_BG = "#0f2744"
# Borders
BORDER = "#27324a" # Standard border
BORDER_STRONG = "#364364" # Emphasized border
BORDER_SUBTLE = "#1a2234" # Soft divider
BORDER_FOCUS = "#60a5fa" # Focus ring
# Progress
PROGRESS_BG = "#182236"
PROGRESS_FILL = BLUE_PRIMARY
# Typography (Segoe UI stack). Use these constants instead of inline fonts.
FONT_FAMILY = "Segoe UI"
FONT_MONO = "Consolas"
# Size tokens
F_DISPLAY = 22 # hero page title
F_HEADING = 16 # section card heading
F_TITLE = 12 # card title / subsection
F_BODY = 10 # body text (default)
F_BODY_SM = 9 # compact body
F_LABEL = 9 # labels, helper
F_META = 8 # meta / captions
F_EYEBROW = 8 # small-caps eyebrow
F_MICRO = 7 # ultra compact
# Spacing rhythm (4pt baseline)
S_XS = 4
S_SM = 8
S_MD = 12
S_LG = 16
S_XL = 20
S_2XL = 24
S_3XL = 32
# Radii
R_SM = 4
R_MD = 6
R_LG = 8
R_XL = 12
def f(size: int, weight: str = "normal") -> tuple:
"""Shortcut to build a Segoe UI font tuple."""
if weight == "bold":
return (Theme.FONT_FAMILY, size, "bold")
return (Theme.FONT_FAMILY, size)
def mono(size: int) -> tuple:
return (Theme.FONT_MONO, size)
class InpaintMode(Enum):
AUTO = "Auto"
STTN = "STTN"
LAMA = "LAMA"
PROPAINTER = "ProPainter"
class ProcessingStatus(Enum):
IDLE = "idle"
LOADING = "loading"
DETECTING = "detecting"
PROCESSING = "processing"
MERGING = "merging"
COMPLETE = "complete"
ERROR = "error"
CANCELLED = "cancelled"
STATUS_UI = {
ProcessingStatus.IDLE: {
"label": "Ready",
"color": Theme.TEXT_SECONDARY,
"bg": Theme.BG_TERTIARY,
},
ProcessingStatus.LOADING: {
"label": "Loading",
"color": Theme.INFO,
"bg": Theme.INFO_BG,
},
ProcessingStatus.DETECTING: {
"label": "Scanning",
"color": Theme.INFO,
"bg": Theme.INFO_BG,
},
ProcessingStatus.PROCESSING: {
"label": "Removing",
"color": Theme.SUCCESS,
"bg": Theme.SUCCESS_BG,
},
ProcessingStatus.MERGING: {
"label": "Finishing",
"color": Theme.WARNING,
"bg": Theme.WARNING_BG,
},
ProcessingStatus.COMPLETE: {
"label": "Complete",
"color": Theme.SUCCESS,
"bg": Theme.SUCCESS_BG,
},
ProcessingStatus.ERROR: {
"label": "Needs Attention",
"color": Theme.ERROR,
"bg": Theme.ERROR_BG,
},
ProcessingStatus.CANCELLED: {
"label": "Stopped",
"color": Theme.TEXT_MUTED,
"bg": Theme.BG_TERTIARY,
},
}
@dataclass
class ProcessingConfig:
"""Configuration for subtitle removal processing."""
mode: InpaintMode = InpaintMode.STTN
use_gpu: bool = True
gpu_id: int = 0
# STTN settings
sttn_skip_detection: bool = False
sttn_neighbor_stride: int = 10
sttn_reference_length: int = 10
sttn_max_load_num: int = 30
# LAMA settings
lama_super_fast: bool = False
# Region settings
subtitle_area: Optional[Tuple[int, int, int, int]] = None # x1, y1, x2, y2
# Detection settings
detection_lang: str = "en"
detection_threshold: float = 0.5
# Time range (video only, seconds)
time_start: float = 0.0
time_end: float = 0.0
# Detection frame skip (0=detect every frame, N=reuse mask for N frames)
detection_frame_skip: int = 0
# Mask dilation in pixels for cleaner removal
mask_dilate_px: int = 8
# Mask edge feathering (soft-blend width in pixels; 0 disables)
mask_feather_px: int = 4
# Temporal Background Exposure (real STTN / ProPainter backing)
tbe_enable: bool = True
tbe_min_coverage: int = 3
tbe_use_median: bool = True
# v3.9 quality controls
tbe_flow_warp: bool = False # Farneback flow-warp before TBE aggregation
tbe_scene_cut_split: bool = True # split TBE batch at scene cuts
tbe_scene_cut_threshold: float = 0.35
edge_ring_px: int = 2 # post-inpaint colour-match ring width
# v3.9 workflow features
subtitle_areas: Optional[List[Tuple[int, int, int, int]]] = None # multi-region
auto_band: bool = False # auto-detect dominant subtitle band on load
export_srt: bool = False # write detected text as SRT sidecar
export_mask_video: bool = False # write B/W mask debug mp4
adaptive_batch: bool = True # VRAM-probe-driven batch sizing
# v3.12 AUTO mode + preprocessing
auto_exposure_threshold: float = 0.55
deinterlace: bool = False
deinterlace_auto: bool = True
keyframe_detection: bool = False
quality_report: bool = False
# v3.10 quality knobs
kalman_tracking: bool = True # smooth per-frame detection jitter
kalman_iou_threshold: float = 0.3
kalman_max_age: int = 2
phash_skip_enable: bool = True # adaptive mask reuse via perceptual hash
phash_skip_distance: int = 4
colour_tune_enable: bool = False # grow mask by dominant-colour match
colour_tune_tolerance: int = 25
# Output settings
output_format: str = "mp4"
preserve_audio: bool = True
output_quality: int = 23 # CRF value (15-35, lower = better quality)
use_hw_encode: bool = True # try hardware encoding (NVENC/QSV/AMF)
# UI state (persisted across sessions; not part of processing config)
window_geometry: str = "" # e.g. "1240x860+100+60"
adv_panel_open: bool = False
log_panel_open: bool = True
onboarding_seen: bool = False
def to_dict(self) -> dict:
return {
"mode": self.mode.value,
"use_gpu": self.use_gpu,
"gpu_id": self.gpu_id,
"sttn_skip_detection": self.sttn_skip_detection,
"sttn_neighbor_stride": self.sttn_neighbor_stride,
"sttn_reference_length": self.sttn_reference_length,
"sttn_max_load_num": self.sttn_max_load_num,
"lama_super_fast": self.lama_super_fast,
"subtitle_area": list(self.subtitle_area) if self.subtitle_area else None,
"detection_lang": self.detection_lang,
"detection_threshold": self.detection_threshold,
"output_format": self.output_format,
"preserve_audio": self.preserve_audio,
"output_quality": self.output_quality,
"time_start": self.time_start,
"time_end": self.time_end,
"detection_frame_skip": self.detection_frame_skip,
"mask_dilate_px": self.mask_dilate_px,
"mask_feather_px": self.mask_feather_px,
"tbe_enable": self.tbe_enable,
"tbe_min_coverage": self.tbe_min_coverage,
"tbe_use_median": self.tbe_use_median,
"tbe_flow_warp": self.tbe_flow_warp,
"tbe_scene_cut_split": self.tbe_scene_cut_split,
"tbe_scene_cut_threshold": self.tbe_scene_cut_threshold,
"edge_ring_px": self.edge_ring_px,
"subtitle_areas": [list(r) for r in self.subtitle_areas] if self.subtitle_areas else None,
"auto_band": self.auto_band,
"export_srt": self.export_srt,
"export_mask_video": self.export_mask_video,
"adaptive_batch": self.adaptive_batch,
"auto_exposure_threshold": self.auto_exposure_threshold,
"deinterlace": self.deinterlace,
"deinterlace_auto": self.deinterlace_auto,
"keyframe_detection": self.keyframe_detection,
"quality_report": self.quality_report,
"kalman_tracking": self.kalman_tracking,
"kalman_iou_threshold": self.kalman_iou_threshold,
"kalman_max_age": self.kalman_max_age,
"phash_skip_enable": self.phash_skip_enable,
"phash_skip_distance": self.phash_skip_distance,
"colour_tune_enable": self.colour_tune_enable,
"colour_tune_tolerance": self.colour_tune_tolerance,
"use_hw_encode": self.use_hw_encode,
"window_geometry": self.window_geometry,
"adv_panel_open": self.adv_panel_open,
"log_panel_open": self.log_panel_open,
"onboarding_seen": self.onboarding_seen,
}
def normalized(self) -> 'ProcessingConfig':
"""Coerce persisted or imported values into a safe, UI-friendly shape."""
self.mode = _coerce_gui_mode(self.mode)
self.use_gpu = _coerce_bool(self.use_gpu, True)
self.gpu_id = max(0, _coerce_int(self.gpu_id, 0))
self.sttn_skip_detection = _coerce_bool(self.sttn_skip_detection, False)
self.sttn_neighbor_stride = _coerce_int(self.sttn_neighbor_stride, 10, 5, 30)
self.sttn_reference_length = _coerce_int(self.sttn_reference_length, 10, 5, 30)
self.sttn_max_load_num = _coerce_int(self.sttn_max_load_num, 30, 10, 100)
self.lama_super_fast = _coerce_bool(self.lama_super_fast, False)
self.subtitle_area = _coerce_rect(self.subtitle_area)
self.subtitle_areas = _coerce_rect_list(self.subtitle_areas)
self.detection_lang = _coerce_text(self.detection_lang, "en", 24).lower()
self.detection_threshold = _coerce_float(self.detection_threshold, 0.5, 0.1, 0.9)
self.time_start = max(0.0, _coerce_float(self.time_start, 0.0))
self.time_end = max(0.0, _coerce_float(self.time_end, 0.0))
if self.time_end and self.time_end < self.time_start:
self.time_end = 0.0
self.detection_frame_skip = _coerce_int(self.detection_frame_skip, 0, 0, 10)
self.mask_dilate_px = _coerce_int(self.mask_dilate_px, 8, 0, 20)
self.mask_feather_px = _coerce_int(self.mask_feather_px, 4, 0, 15)
self.tbe_enable = _coerce_bool(self.tbe_enable, True)
self.tbe_min_coverage = _coerce_int(self.tbe_min_coverage, 3, 1, 10)
self.tbe_use_median = _coerce_bool(self.tbe_use_median, True)
self.tbe_flow_warp = _coerce_bool(self.tbe_flow_warp, False)
self.tbe_scene_cut_split = _coerce_bool(self.tbe_scene_cut_split, True)
self.tbe_scene_cut_threshold = _coerce_float(self.tbe_scene_cut_threshold, 0.35, 0.0, 1.0)
self.edge_ring_px = _coerce_int(self.edge_ring_px, 2, 0, 8)
self.auto_band = _coerce_bool(self.auto_band, False)
self.export_srt = _coerce_bool(self.export_srt, False)
self.export_mask_video = _coerce_bool(self.export_mask_video, False)
self.adaptive_batch = _coerce_bool(self.adaptive_batch, True)
self.auto_exposure_threshold = _coerce_float(self.auto_exposure_threshold, 0.55, 0.0, 1.0)
self.deinterlace = _coerce_bool(self.deinterlace, False)
self.deinterlace_auto = _coerce_bool(self.deinterlace_auto, True)
self.keyframe_detection = _coerce_bool(self.keyframe_detection, False)
self.quality_report = _coerce_bool(self.quality_report, False)
self.kalman_tracking = _coerce_bool(self.kalman_tracking, True)
self.kalman_iou_threshold = _coerce_float(self.kalman_iou_threshold, 0.3, 0.0, 1.0)
self.kalman_max_age = _coerce_int(self.kalman_max_age, 2, 0, 30)
self.phash_skip_enable = _coerce_bool(self.phash_skip_enable, True)
self.phash_skip_distance = _coerce_int(self.phash_skip_distance, 4, 0, 64)
self.colour_tune_enable = _coerce_bool(self.colour_tune_enable, False)
self.colour_tune_tolerance = _coerce_int(self.colour_tune_tolerance, 25, 0, 100)
self.output_format = _coerce_text(self.output_format, "mp4", 16).lower()
self.preserve_audio = _coerce_bool(self.preserve_audio, True)
self.output_quality = _coerce_int(self.output_quality, 23, 15, 35)
self.use_hw_encode = _coerce_bool(self.use_hw_encode, True)
self.window_geometry = _coerce_text(self.window_geometry, "", 64)
self.adv_panel_open = _coerce_bool(self.adv_panel_open, False)
self.log_panel_open = _coerce_bool(self.log_panel_open, True)
self.onboarding_seen = _coerce_bool(self.onboarding_seen, False)
return self
@classmethod
def from_dict(cls, data: dict) -> 'ProcessingConfig':
mode = data.get("mode", InpaintMode.STTN.value)
return cls(
mode=mode,
use_gpu=data.get("use_gpu", True),
gpu_id=data.get("gpu_id", 0),
sttn_skip_detection=data.get("sttn_skip_detection", False),
sttn_neighbor_stride=data.get("sttn_neighbor_stride", 10),
sttn_reference_length=data.get("sttn_reference_length", 10),
sttn_max_load_num=data.get("sttn_max_load_num", 30),
lama_super_fast=data.get("lama_super_fast", False),
subtitle_area=_coerce_rect(data.get("subtitle_area")),
detection_lang=data.get("detection_lang", "en"),
detection_threshold=data.get("detection_threshold", 0.5),
output_format=data.get("output_format", "mp4"),
preserve_audio=data.get("preserve_audio", True),
output_quality=data.get("output_quality", 23),
time_start=data.get("time_start", 0.0),
time_end=data.get("time_end", 0.0),
detection_frame_skip=data.get("detection_frame_skip", 0),
mask_dilate_px=data.get("mask_dilate_px", 8),
mask_feather_px=data.get("mask_feather_px", 4),
tbe_enable=data.get("tbe_enable", True),
tbe_min_coverage=data.get("tbe_min_coverage", 3),
tbe_use_median=data.get("tbe_use_median", True),
tbe_flow_warp=data.get("tbe_flow_warp", False),
tbe_scene_cut_split=data.get("tbe_scene_cut_split", True),
tbe_scene_cut_threshold=data.get("tbe_scene_cut_threshold", 0.35),
edge_ring_px=data.get("edge_ring_px", 2),
subtitle_areas=_coerce_rect_list(data.get("subtitle_areas")),
auto_band=data.get("auto_band", False),
export_srt=data.get("export_srt", False),
export_mask_video=data.get("export_mask_video", False),
adaptive_batch=data.get("adaptive_batch", True),
auto_exposure_threshold=data.get("auto_exposure_threshold", 0.55),
deinterlace=data.get("deinterlace", False),
deinterlace_auto=data.get("deinterlace_auto", True),
keyframe_detection=data.get("keyframe_detection", False),
quality_report=data.get("quality_report", False),
kalman_tracking=data.get("kalman_tracking", True),
kalman_iou_threshold=data.get("kalman_iou_threshold", 0.3),
kalman_max_age=data.get("kalman_max_age", 2),
phash_skip_enable=data.get("phash_skip_enable", True),
phash_skip_distance=data.get("phash_skip_distance", 4),
colour_tune_enable=data.get("colour_tune_enable", False),
colour_tune_tolerance=data.get("colour_tune_tolerance", 25),
use_hw_encode=data.get("use_hw_encode", True),
window_geometry=data.get("window_geometry", ""),
adv_panel_open=data.get("adv_panel_open", False),
log_panel_open=data.get("log_panel_open", True),
onboarding_seen=data.get("onboarding_seen", False),
).normalized()
@dataclass
class QueueItem:
"""Represents an item in the processing queue."""
id: str
file_path: str
output_path: str
config: ProcessingConfig
output_path_locked: bool = False
status: ProcessingStatus = ProcessingStatus.IDLE
progress: float = 0.0
message: str = ""
started_at: Optional[datetime] = None
completed_at: Optional[datetime] = None
error: Optional[str] = None
quality_report: Optional[dict] = None
def _coerce_bool(value, default: bool) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return bool(value)
if isinstance(value, str):
lowered = value.strip().lower()
if lowered in {"1", "true", "yes", "on"}:
return True
if lowered in {"0", "false", "no", "off", ""}:
return False
return default
def _coerce_int(value, default: int, min_value: Optional[int] = None,
max_value: Optional[int] = None) -> int:
try:
f = float(value)
if not math.isfinite(f):
raise ValueError("non-finite float")
coerced = int(f)
except (TypeError, ValueError):
coerced = default
if min_value is not None:
coerced = max(min_value, coerced)
if max_value is not None:
coerced = min(max_value, coerced)
return coerced
def _coerce_float(value, default: float, min_value: Optional[float] = None,
max_value: Optional[float] = None) -> float:
try:
coerced = float(value)
if not math.isfinite(coerced):
raise ValueError("non-finite float")
except (TypeError, ValueError):
coerced = default
if min_value is not None:
coerced = max(min_value, coerced)
if max_value is not None:
coerced = min(max_value, coerced)
return coerced
def _coerce_text(value, default: str, max_length: int = 256) -> str:
if isinstance(value, str):
text = value.strip()
if len(text) > max_length:
text = text[:max_length]
return text
return default
def _coerce_rect(value) -> Optional[Tuple[int, int, int, int]]:
if not isinstance(value, (list, tuple)) or len(value) != 4:
return None
try:
x1, y1, x2, y2 = [int(float(v)) for v in value]
except (TypeError, ValueError):
return None
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = max(0, x2), max(0, y2)
if x2 <= x1 or y2 <= y1:
return None
return (x1, y1, x2, y2)
def _coerce_rect_list(value) -> Optional[List[Tuple[int, int, int, int]]]:
if not isinstance(value, (list, tuple)):
return None
rects = []
for item in value:
rect = _coerce_rect(item)
if rect:
rects.append(rect)
return rects or None
def _coerce_gui_mode(value) -> InpaintMode:
if isinstance(value, InpaintMode):
return value
if isinstance(value, str):
normalized = value.strip().casefold()
mode_map = {
"auto": InpaintMode.AUTO,
"sttn": InpaintMode.STTN,
"lama": InpaintMode.LAMA,
"propainter": InpaintMode.PROPAINTER,
"pro painter": InpaintMode.PROPAINTER,
}
if normalized in mode_map:
return mode_map[normalized]
return InpaintMode.STTN
def _read_json_object(path: Path, label: str) -> Optional[dict]:
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
logger.warning(f"Could not read {label} from {path}: {exc}")
return None
if not isinstance(payload, dict):
logger.warning(f"Ignoring {label} at {path}: expected a JSON object")
return None
return payload
def _write_json_atomic(path: Path, payload: dict):
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = None
try:
fd, temp_name = tempfile.mkstemp(
prefix=f".{path.name}.",
suffix=".tmp",
dir=str(path.parent),
)
temp_path = Path(temp_name)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(payload, handle, indent=2)
os.replace(temp_path, path)
finally:
if temp_path and temp_path.exists():
try:
temp_path.unlink()
except OSError:
pass
# =============================================================================
# SETTINGS PERSISTENCE
# =============================================================================
def load_settings() -> ProcessingConfig:
"""Load saved settings from disk."""
try:
if SETTINGS_FILE.exists():
data = _read_json_object(SETTINGS_FILE, "settings")
if not data:
return ProcessingConfig()
logger.info(f"Settings loaded from {SETTINGS_FILE}")
return ProcessingConfig.from_dict(data)
except Exception as e:
logger.warning(f"Could not load settings: {e}")
return ProcessingConfig()
def save_settings(config: ProcessingConfig):
"""Save settings to disk."""
try:
_write_json_atomic(SETTINGS_FILE, config.normalized().to_dict())
logger.info(f"Settings saved to {SETTINGS_FILE}")
except Exception as e:
logger.warning(f"Could not save settings: {e}")
# =============================================================================
# PRESET LIBRARY
# =============================================================================
PRESETS_FILE = LOG_DIR / "presets.json"
# Built-in presets tuned for common content types. Only the fields that
# matter for each recipe are set; everything else inherits from the current
# config when the preset is applied (so user-tuned quality knobs survive).
BUILTIN_PRESETS = {
"YouTube (default)": {
"description": "Balanced defaults for typical YouTube / streaming footage.",
"fields": {
"mode": "STTN",
"detection_threshold": 0.5,
"mask_dilate_px": 8,
"mask_feather_px": 4,
"edge_ring_px": 2,
"tbe_flow_warp": False,
"tbe_scene_cut_split": True,
"colour_tune_enable": False,
"kalman_tracking": True,
"phash_skip_enable": True,
},
},
"Anime / Animation": {
"description": "Flat backgrounds benefit from LAMA + tight feather.",
"fields": {
"mode": "LAMA",
"detection_threshold": 0.55,
"mask_dilate_px": 10,
"mask_feather_px": 3,
"edge_ring_px": 0,
"colour_tune_enable": True,
"colour_tune_tolerance": 30,
},
},
"Motion-heavy / Action": {
"description": "Enables flow-warped TBE + ProPainter for fast pans.",
"fields": {
"mode": "ProPainter",
"detection_threshold": 0.45,
"mask_dilate_px": 12,
"mask_feather_px": 6,
"edge_ring_px": 3,
"tbe_flow_warp": True,
"tbe_scene_cut_split": True,
"kalman_tracking": True,
},
},
"TikTok / Vertical short": {
"description": "9:16 short-form with bold burned-in captions.",
"fields": {
"mode": "STTN",
"detection_threshold": 0.4,
"mask_dilate_px": 14,
"mask_feather_px": 5,
"colour_tune_enable": True,
"auto_band": True,
},
},
"VHS / Low-res restore": {
"description": "Noisy SD footage; higher feather and tolerant pHash.",
"fields": {
"mode": "STTN",
"detection_threshold": 0.4,
"mask_dilate_px": 10,
"mask_feather_px": 6,
"edge_ring_px": 4,
"phash_skip_enable": True,
"phash_skip_distance": 8,
"kalman_tracking": True,
},
},
"News / Chyron (bottom-third)": {
"description": "Lower-third graphics; auto-band + STTN + tight mask.",
"fields": {
"mode": "STTN",
"detection_threshold": 0.5,
"auto_band": True,
"mask_dilate_px": 6,
"mask_feather_px": 3,
"kalman_tracking": True,
},
},
}
def _load_user_presets() -> dict:
if PRESETS_FILE.exists():
payload = _read_json_object(PRESETS_FILE, "user presets")
if payload is not None:
return payload
return {}
def _save_user_presets(presets: dict):
try:
_write_json_atomic(PRESETS_FILE, presets)
except Exception as exc:
logger.warning(f"Could not save user presets: {exc}")
def list_presets() -> List[Tuple[str, str]]:
"""Return [(name, description)] for every built-in + user preset."""
items = [(n, p.get("description", "")) for n, p in BUILTIN_PRESETS.items()]
for name, payload in _load_user_presets().items():
if isinstance(payload, dict):
items.append((name, _coerce_text(payload.get("description", "User preset"), "User preset", 120)))
return items
def apply_preset(config: ProcessingConfig, name: str) -> bool:
"""Apply a named preset to `config` in-place. Returns True on success."""
preset = BUILTIN_PRESETS.get(name)
if preset is None:
preset = _load_user_presets().get(name)
if not isinstance(preset, dict):
return False
fields = preset.get("fields", {})
if not isinstance(fields, dict):
return False
for k, v in fields.items():
if k == "mode":
config.mode = _coerce_gui_mode(v)
continue
if hasattr(config, k):
setattr(config, k, v)
config.normalized()
return True
def save_user_preset(name: str, description: str, config: ProcessingConfig,
fields: Optional[List[str]] = None) -> bool:
"""Snapshot the selected fields from `config` into a user preset."""
name = _coerce_text(name, "", 80)
description = _coerce_text(description, "User preset", 160) or "User preset"
if not name:
return False
if name in BUILTIN_PRESETS:
return False # don't let users overwrite built-ins
default_fields = [
"mode", "detection_threshold", "mask_dilate_px", "mask_feather_px",
"edge_ring_px", "tbe_flow_warp", "tbe_scene_cut_split",
"colour_tune_enable", "colour_tune_tolerance",
"kalman_tracking", "phash_skip_enable", "phash_skip_distance",
"auto_band",
]
fields = fields or default_fields
config = config.normalized()
snap = {}
for k in fields:
v = getattr(config, k, None)
if k == "mode" and hasattr(v, "value"):
v = v.value
if v is not None:
snap[k] = v
user = _load_user_presets()
user[name] = {"description": description, "fields": snap}
_save_user_presets(user)
return True
def delete_user_preset(name: str) -> bool:
if name in BUILTIN_PRESETS:
return False
user = _load_user_presets()
if name not in user:
return False
del user[name]
_save_user_presets(user)
return True
def export_preset(name: str, path: str) -> bool:
"""Write a named preset (built-in or user) to a standalone JSON file
so it can be shared or version-controlled alongside a project."""
preset = BUILTIN_PRESETS.get(name) or _load_user_presets().get(name)
if not preset:
return False
payload = {
"name": name,
"description": preset.get("description", ""),
"fields": preset.get("fields", {}),
"vsr_preset_format": 1,
}
try:
_write_json_atomic(Path(path), payload)
return True
except Exception as exc:
logger.warning(f"Could not export preset '{name}' to {path}: {exc}")
return False
def import_preset(path: str) -> Optional[str]:
"""Load a shareable preset JSON and install it under the user's preset
library. Returns the installed name on success, None on failure.
Collisions with built-in names are rejected; collisions with existing
user presets overwrite."""
payload = _read_json_object(Path(path), "preset import")
if payload is None:
return None
if payload.get("vsr_preset_format") != 1:
logger.warning(f"Not a v1 VSR preset: {path}")
return None
name = _coerce_text(payload.get("name", ""), "", 80)
fields = payload.get("fields", {})
description = _coerce_text(payload.get("description", "Imported preset"), "Imported preset", 160)
if not name or not isinstance(fields, dict):
return None
if name in BUILTIN_PRESETS:
name = f"{name} (imported)"
user = _load_user_presets()
user[name] = {"description": description, "fields": fields}
_save_user_presets(user)
return name
# =============================================================================
# UTILITY FUNCTIONS
# =============================================================================
def get_app_dir() -> Path:
"""Get the application directory."""
if getattr(sys, 'frozen', False):
return Path(sys.executable).parent
return Path(__file__).parent
def detect_gpu() -> List[dict]:
"""Detect available GPUs."""
gpus = []
# Try NVIDIA GPU detection
try:
result = subprocess.run(
['nvidia-smi', '--query-gpu=index,name,memory.total', '--format=csv,noheader,nounits'],
capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
for line in result.stdout.strip().split('\n'):
if line.strip():
parts = line.split(',')
if len(parts) >= 3:
try:
gpu_idx = int(parts[0].strip())
gpu_mem = f"{int(parts[2].strip())} MB"
except ValueError:
continue
gpus.append({
"index": gpu_idx,
"name": parts[1].strip(),
"memory": gpu_mem,
"type": "NVIDIA"
})
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
# If no NVIDIA GPU, check for DirectML support
if not gpus:
try:
import torch_directml
gpus.append({
"index": 0,
"name": "DirectML Device",
"memory": "Unknown",
"type": "DirectML"
})
except ImportError:
pass
return gpus
def format_time(seconds: float) -> str:
"""Format seconds into human-readable time."""
if seconds < 60:
return f"{seconds:.1f}s"
elif seconds < 3600:
m, s = divmod(seconds, 60)
return f"{int(m)}m {int(s)}s"
else:
h, rem = divmod(seconds, 3600)
m, s = divmod(rem, 60)
return f"{int(h)}h {int(m)}m"
def format_size(bytes_size: int) -> str:
"""Format bytes into human-readable size."""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_size < 1024:
return f"{bytes_size:.1f} {unit}"
bytes_size /= 1024
return f"{bytes_size:.1f} PB"
def is_video_file(path: str) -> bool:
"""Check if file is a supported video format."""
video_extensions = {'.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.mpeg', '.mpg'}
return Path(path).suffix.lower() in video_extensions
def is_image_file(path: str) -> bool:
"""Check if file is a supported image format."""
image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp'}
return Path(path).suffix.lower() in image_extensions
def detect_ai_engines() -> dict:
"""Probe which AI engines are available."""
engines = {"detection": [], "inpainting": []}
# RapidOCR first -- ONNX Runtime, 4-5x faster than PaddleOCR, leak-free
try:
try:
import rapidocr # noqa: F401
except ImportError:
import rapidocr_onnxruntime # noqa: F401
engines["detection"].append("RapidOCR")
except ImportError:
pass
try:
import paddleocr # noqa: F401
engines["detection"].append("PaddleOCR")
except ImportError:
pass
try:
from surya.detection import DetectionPredictor # noqa: F401
engines["detection"].append("Surya")
except Exception:
pass
try:
import easyocr # noqa: F401
engines["detection"].append("EasyOCR")
except ImportError:
pass
if not engines["detection"]: