-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathvsmlrt.py
3074 lines (2540 loc) · 101 KB
/
vsmlrt.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
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
__version__ = "3.22.13"
__all__ = [
"Backend", "BackendV2",
"Waifu2x", "Waifu2xModel",
"DPIR", "DPIRModel",
"RealESRGAN", "RealESRGANModel",
"RealESRGANv2", "RealESRGANv2Model",
"CUGAN",
"RIFE", "RIFEModel", "RIFEMerge",
"SAFA", "SAFAModel", "SAFAAdaptiveMode",
"SCUNet", "SCUNetModel",
"SwinIR", "SwinIRModel",
"ArtCNN", "ArtCNNModel",
"inference",
"flexible_inference"
]
import copy
from dataclasses import dataclass, field
import enum
from fractions import Fraction
import math
import os
import os.path
import platform
import subprocess
import sys
import tempfile
import time
import typing
import zlib
import vapoursynth as vs
from vapoursynth import core
def get_plugins_path() -> str:
path = b""
try:
path = core.ov.Version()["path"]
except AttributeError:
pass
if path == b"":
try:
path = core.ort.Version()["path"]
except AttributeError:
pass
if path == b"":
try:
path = core.ncnn.Version()["path"]
except AttributeError:
pass
if path == b"":
try:
path = core.trt.Version()["path"]
except AttributeError:
pass
if path == b"":
try:
path = core.migx.Version()["path"]
except AttributeError:
pass
if path == b"":
raise RuntimeError("vsmlrt: cannot load any filters")
return os.path.dirname(path).decode()
plugins_path: str = get_plugins_path()
trtexec_path: str = os.path.join(plugins_path, "vsmlrt-cuda", "trtexec")
migraphx_driver_path: str = os.path.join(plugins_path, "vsmlrt-hip", "migraphx-driver")
models_path: str = os.path.join(plugins_path, "models")
class Backend:
@dataclass(frozen=False)
class ORT_CPU:
""" backend for cpus """
num_streams: int = 1
verbosity: int = 2
fp16: bool = False
fp16_blacklist_ops: typing.Optional[typing.Sequence[str]] = None
# internal backend attributes
supports_onnx_serialization: bool = True
@dataclass(frozen=False)
class ORT_CUDA:
""" backend for nvidia gpus
basic performance tuning:
set fp16 = True (on RTX GPUs)
Semantics of `fp16`:
Enabling `fp16` will use a built-in quantization that converts a fp32 onnx to a fp16 onnx.
If the input video is of half-precision floating-point format,
the generated fp16 onnx will use fp16 input.
The output format can be controlled by the `output_format` option (0 = fp32, 1 = fp16).
Disabling `fp16` will not use the built-in quantization.
However, if the onnx file itself uses fp16 for computation,
the actual computation will be done in fp16.
In this case, the input video format should match the input format of the onnx,
and the output format is inferred from the onnx.
"""
device_id: int = 0
cudnn_benchmark: bool = True
num_streams: int = 1
verbosity: int = 2
fp16: bool = False
use_cuda_graph: bool = False # preview, not supported by all models
fp16_blacklist_ops: typing.Optional[typing.Sequence[str]] = None
prefer_nhwc: bool = False
output_format: int = 0 # 0: fp32, 1: fp16
tf32: bool = False
# internal backend attributes
supports_onnx_serialization: bool = True
@dataclass(frozen=False)
class OV_CPU:
""" backend for x86 cpus
basic performance tuning:
set bf16 = True (on Zen4)
increase num_streams
"""
fp16: bool = False
num_streams: typing.Union[int, str] = 1
bind_thread: bool = True
fp16_blacklist_ops: typing.Optional[typing.Sequence[str]] = None
bf16: bool = False
num_threads: int = 0
# internal backend attributes
supports_onnx_serialization: bool = True
@dataclass(frozen=False)
class TRT:
""" backend for nvidia gpus
basic performance tuning:
set fp16 = True (on RTX GPUs)
increase num_streams
increase workspace
set use_cuda_graph = True
"""
max_shapes: typing.Optional[typing.Tuple[int, int]] = None
opt_shapes: typing.Optional[typing.Tuple[int, int]] = None
fp16: bool = False
device_id: int = 0
workspace: typing.Optional[int] = None
verbose: bool = False
use_cuda_graph: bool = False
num_streams: int = 1
use_cublas: bool = False # cuBLAS + cuBLASLt
static_shape: bool = True
tf32: bool = False
log: bool = True
# as of TensorRT 8.4, it can be turned off without performance penalty in most cases
use_cudnn: bool = False # changed to False since vsmlrt.vpy 3.16
use_edge_mask_convolutions: bool = True
use_jit_convolutions: bool = True
heuristic: bool = False # only supported on Ampere+ with TensorRT 8.5+
output_format: int = 0 # 0: fp32, 1: fp16
min_shapes: typing.Tuple[int, int] = (0, 0)
faster_dynamic_shapes: bool = True
force_fp16: bool = False
builder_optimization_level: int = 3
max_aux_streams: typing.Optional[int] = None
short_path: typing.Optional[bool] = None # True on Windows by default, False otherwise
bf16: bool = False
custom_env: typing.Dict[str, str] = field(default_factory=lambda: {})
custom_args: typing.List[str] = field(default_factory=lambda: [])
engine_folder: typing.Optional[str] = None
max_tactics: typing.Optional[int] = None
tiling_optimization_level: int = 0
l2_limit_for_tiling: int = -1
# internal backend attributes
supports_onnx_serialization: bool = False
@dataclass(frozen=False)
class OV_GPU:
""" backend for nvidia gpus
basic performance tuning:
set fp16 = True
increase num_streams
"""
fp16: bool = False
num_streams: typing.Union[int, str] = 1
device_id: int = 0
fp16_blacklist_ops: typing.Optional[typing.Sequence[str]] = None
# internal backend attributes
supports_onnx_serialization: bool = True
@dataclass(frozen=False)
class NCNN_VK:
""" backend for vulkan devices
basic performance tuning:
set fp16 = True (on modern GPUs)
increase num_streams
"""
fp16: bool = False
device_id: int = 0
num_streams: int = 1
# internal backend attributes
supports_onnx_serialization: bool = True
@dataclass(frozen=False)
class ORT_DML:
""" backend for directml (d3d12) devices """
device_id: int = 0
num_streams: int = 1
verbosity: int = 2
fp16: bool = False
fp16_blacklist_ops: typing.Optional[typing.Sequence[str]] = None
# internal backend attributes
supports_onnx_serialization: bool = True
@dataclass(frozen=False)
class MIGX:
""" backend for amd gpus
basic performance tuning:
set fp16 = True
"""
device_id: int = 0
fp16: bool = False
opt_shapes: typing.Optional[typing.Tuple[int, int]] = None
fast_math: bool = True
exhaustive_tune: bool = False
num_streams: int = 1
short_path: typing.Optional[bool] = None # True on Windows by default, False otherwise
custom_env: typing.Dict[str, str] = field(default_factory=lambda: {})
custom_args: typing.List[str] = field(default_factory=lambda: [])
# internal backend attributes
supports_onnx_serialization: bool = False
@dataclass(frozen=False)
class OV_NPU:
""" backend for intel npus
"""
# internal backend attributes
supports_onnx_serialization: bool = True
@dataclass(frozen=False)
class ORT_COREML:
""" backend for coreml """
num_streams: int = 1
verbosity: int = 0
fp16: bool = False
fp16_blacklist_ops: typing.Optional[typing.Sequence[str]] = None
ml_program: int = 0
# internal backend attributes
supports_onnx_serialization: bool = True
backendT = typing.Union[
Backend.OV_CPU,
Backend.ORT_CPU,
Backend.ORT_CUDA,
Backend.TRT,
Backend.OV_GPU,
Backend.NCNN_VK,
Backend.ORT_DML,
Backend.MIGX,
Backend.OV_NPU,
Backend.ORT_COREML,
]
fallback_backend: typing.Optional[backendT] = None
@enum.unique
class Waifu2xModel(enum.IntEnum):
anime_style_art = 0
anime_style_art_rgb = 1
photo = 2
upconv_7_anime_style_art_rgb = 3
upconv_7_photo = 4
upresnet10 = 5
cunet = 6
swin_unet_art = 7
swin_unet_photo = 8 # 20230329
swin_unet_photo_v2 = 9 # 20230407
swin_unet_art_scan = 10 # 20230504
def Waifu2x(
clip: vs.VideoNode,
noise: typing.Literal[-1, 0, 1, 2, 3] = -1,
scale: typing.Literal[1, 2, 4] = 2,
tiles: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
tilesize: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
overlap: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
model: Waifu2xModel = Waifu2xModel.cunet,
backend: backendT = Backend.OV_CPU(),
preprocess: bool = True
) -> vs.VideoNode:
func_name = "vsmlrt.Waifu2x"
if not isinstance(clip, vs.VideoNode):
raise TypeError(f'{func_name}: "clip" must be a clip!')
if clip.format.sample_type != vs.FLOAT or clip.format.bits_per_sample not in [16, 32]:
raise ValueError(f"{func_name}: only constant format 16/32 bit float input supported")
if not isinstance(noise, int) or noise not in range(-1, 4):
raise ValueError(f'{func_name}: "noise" must be -1, 0, 1, 2, or 3')
if not isinstance(scale, int) or scale not in (1, 2, 4):
raise ValueError(f'{func_name}: "scale" must be 1, 2 or 4')
if not isinstance(model, int) or model not in Waifu2xModel.__members__.values():
raise ValueError(f'{func_name}: invalid "model"')
if model == 0 and noise == 0:
raise ValueError(
f'{func_name}: "anime_style_art" model'
' does not support noise reduction level 0'
)
if model in range(7) and scale not in (1, 2):
raise ValueError(f'{func_name}: "scale" must be 1 or 2')
if model == 0:
if clip.format.color_family != vs.GRAY:
raise ValueError(f'{func_name}: "clip" must be of GRAY color family')
elif clip.format.color_family != vs.RGB:
raise ValueError(f'{func_name}: "clip" must be of RGB color family')
if overlap is None:
overlap_w = overlap_h = [8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4][model]
elif isinstance(overlap, int):
overlap_w = overlap_h = overlap
else:
overlap_w, overlap_h = overlap
if model == 6:
multiple = 4
else:
multiple = 1
width, height = clip.width, clip.height
if preprocess and model in (0, 1, 2):
# emulating cv2.resize(interpolation=cv2.INTER_CUBIC)
clip = core.resize.Bicubic(
clip,
width * 2, height * 2,
filter_param_a=0, filter_param_b=0.75
)
(tile_w, tile_h), (overlap_w, overlap_h) = calc_tilesize(
tiles=tiles, tilesize=tilesize,
width=clip.width, height=clip.height,
multiple=multiple,
overlap_w=overlap_w, overlap_h=overlap_h
)
if tile_w % multiple != 0 or tile_h % multiple != 0:
raise ValueError(
f'{func_name}: tile size must be divisible by {multiple} ({tile_w}, {tile_h})'
)
backend = init_backend(
backend=backend,
trt_opt_shapes=(tile_w, tile_h)
)
folder_path = os.path.join(
models_path,
"waifu2x",
tuple(Waifu2xModel.__members__)[model]
)
if model in (0, 1, 2):
if noise == -1:
model_name = "scale2.0x_model.onnx"
else:
model_name = f"noise{noise}_model.onnx"
elif model in (3, 4, 5):
if noise == -1:
model_name = "scale2.0x_model.onnx"
else:
model_name = f"noise{noise}_scale2.0x_model.onnx"
elif model == 6:
if scale == 1:
scale_name = ""
else:
scale_name = "scale2.0x_"
if noise == -1:
model_name = "scale2.0x_model.onnx"
else:
model_name = f"noise{noise}_{scale_name}model.onnx"
elif model == 7:
if scale == 1:
scale_name = ""
elif scale == 2:
scale_name = "scale2x"
elif scale == 4:
scale_name = "scale4x"
if noise == -1:
if scale == 1:
raise ValueError("swin_unet model for \"noise == -1\" and \"scale == 1\" does not exist")
model_name = f"{scale_name}.onnx"
else:
if scale == 1:
model_name = f"noise{noise}.onnx"
else:
model_name = f"noise{noise}_{scale_name}.onnx"
elif model in (8, 9, 10):
scale_name = "scale4x"
if noise == -1:
model_name = f"{scale_name}.onnx"
else:
model_name = f"noise{noise}_{scale_name}.onnx"
else:
raise ValueError(f"{func_name}: inavlid model {model}")
network_path = os.path.join(folder_path, model_name)
clip = inference_with_fallback(
clips=[clip], network_path=network_path,
overlap=(overlap_w, overlap_h), tilesize=(tile_w, tile_h),
backend=backend
)
if model in range(8) and scale == 1 and clip.width // width == 2:
# emulating cv2.resize(interpolation=cv2.INTER_CUBIC)
# cr: @AkarinVS
clip = fmtc_resample(
clip, scale=0.5,
kernel="impulse", impulse=[-0.1875, 1.375, -0.1875],
kovrspl=2
)
elif model in (8, 9, 10) and scale != 4:
clip = core.resize.Bicubic(
clip, clip.width * scale // 4, clip.height * scale // 4,
filter_param_a=0, filter_param_b=0.5
)
return clip
@enum.unique
class DPIRModel(enum.IntEnum):
drunet_gray = 0
drunet_color = 1
drunet_deblocking_grayscale = 2
drunet_deblocking_color = 3
def DPIR(
clip: vs.VideoNode,
strength: typing.Optional[typing.Union[typing.SupportsFloat, vs.VideoNode]],
tiles: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
tilesize: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
overlap: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
model: DPIRModel = DPIRModel.drunet_gray,
backend: backendT = Backend.OV_CPU()
) -> vs.VideoNode:
func_name = "vsmlrt.DPIR"
if not isinstance(clip, vs.VideoNode):
raise TypeError(f'{func_name}: "clip" must be a clip!')
if clip.format.sample_type != vs.FLOAT or clip.format.bits_per_sample not in [16, 32]:
raise ValueError(f"{func_name}: only constant format 16/32 bit float input supported")
if not isinstance(model, int) or model not in DPIRModel.__members__.values():
raise ValueError(f'{func_name}: invalid "model"')
if model in [0, 2] and clip.format.color_family != vs.GRAY:
raise ValueError(f'{func_name}: "clip" must be of GRAY color family')
elif model in [1, 3] and clip.format.color_family != vs.RGB:
raise ValueError(f'{func_name}: "clip" must be of RGB color family')
if strength is None:
strength = 5.0
gray_format = vs.GRAYS if clip.format.bits_per_sample == 32 else vs.GRAYH
if isinstance(strength, vs.VideoNode):
strength = typing.cast(vs.VideoNode, strength)
if strength.format.color_family != vs.GRAY:
raise ValueError(f'{func_name}: "strength" must be of GRAY color family')
if strength.width != clip.width or strength.height != clip.height:
raise ValueError(f'{func_name}: "strength" must be of the same size as "clip"')
if strength.num_frames != clip.num_frames:
raise ValueError(f'{func_name}: "strength" must be of the same length as "clip"')
strength = core.std.Expr(strength, "x 255 /", format=gray_format)
else:
try:
strength = float(strength)
except TypeError as e:
raise TypeError(f'{func_name}: "strength" must be a float or a clip') from e
strength = core.std.BlankClip(clip, format=gray_format, color=strength / 255, keep=True)
if overlap is None:
overlap_w = overlap_h = 16
elif isinstance(overlap, int):
overlap_w = overlap_h = overlap
else:
overlap_w, overlap_h = overlap
multiple = 8
(tile_w, tile_h), (overlap_w, overlap_h) = calc_tilesize(
tiles=tiles, tilesize=tilesize,
width=clip.width, height=clip.height,
multiple=multiple,
overlap_w=overlap_w, overlap_h=overlap_h
)
if tile_w % multiple != 0 or tile_h % multiple != 0:
raise ValueError(
f'{func_name}: tile size must be divisible by {multiple} ({tile_w}, {tile_h})'
)
backend = init_backend(
backend=backend,
trt_opt_shapes=(tile_w, tile_h)
)
if isinstance(backend, Backend.TRT) and not backend.force_fp16:
backend.custom_args.extend([
"--precisionConstraints=obey",
"--layerPrecisions=Conv_123:fp32"
])
network_path = os.path.join(
models_path,
"dpir",
f"{tuple(DPIRModel.__members__)[model]}.onnx"
)
clip = inference_with_fallback(
clips=[clip, strength], network_path=network_path,
overlap=(overlap_w, overlap_h), tilesize=(tile_w, tile_h),
backend=backend
)
return clip
@enum.unique
class RealESRGANModel(enum.IntEnum):
# v2
animevideo_xsx2 = 0
animevideo_xsx4 = 1
# v3
animevideov3 = 2 # 4x
# contributed: janaiV2(2x) https://github.com/the-database/mpv-upscale-2x_animejanai/releases/tag/2.0.0 maintainer: hooke007
animejanaiV2L1 = 5005
animejanaiV2L2 = 5006
animejanaiV2L3 = 5007
# contributed: janaiV3-hd(2x) https://github.com/the-database/mpv-upscale-2x_animejanai/releases/tag/3.0.0 maintainer: hooke007
animejanaiV3_HD_L1 = 5008
animejanaiV3_HD_L2 = 5009
animejanaiV3_HD_L3 = 5010
# contributed=Ani4K-v2 https://github.com/Sirosky/Upscale-Hub/releases/tag/Ani4K-v2
Ani4Kv2_G6i2_Compact = 7000
Ani4Kv2_G6i2_UltraCompact = 7001
RealESRGANv2Model = RealESRGANModel
def RealESRGAN(
clip: vs.VideoNode,
tiles: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
tilesize: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
overlap: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
model: RealESRGANv2Model = RealESRGANv2Model.animevideo_xsx2,
backend: backendT = Backend.OV_CPU(),
scale: typing.Optional[float] = None
) -> vs.VideoNode:
func_name = "vsmlrt.RealESRGAN"
if not isinstance(clip, vs.VideoNode):
raise TypeError(f'{func_name}: "clip" must be a clip!')
if clip.format.sample_type != vs.FLOAT or clip.format.bits_per_sample not in [16, 32]:
raise ValueError(f"{func_name}: only constant format 16/32 bit float input supported")
if clip.format.color_family != vs.RGB:
raise ValueError(f'{func_name}: "clip" must be of RGB color family')
if not isinstance(model, int) or model not in RealESRGANv2Model.__members__.values():
raise ValueError(f'{func_name}: invalid "model"')
if overlap is None:
overlap_w = overlap_h = 8
elif isinstance(overlap, int):
overlap_w = overlap_h = overlap
else:
overlap_w, overlap_h = overlap
multiple = 1
(tile_w, tile_h), (overlap_w, overlap_h) = calc_tilesize(
tiles=tiles, tilesize=tilesize,
width=clip.width, height=clip.height,
multiple=multiple,
overlap_w=overlap_w, overlap_h=overlap_h
)
backend = init_backend(
backend=backend,
trt_opt_shapes=(tile_w, tile_h)
)
if model in [0, 1]:
network_path = os.path.join(
models_path,
"RealESRGANv2",
f"RealESRGANv2-{tuple(RealESRGANv2Model.__members__)[model]}.onnx".replace('_', '-')
)
elif model == 2:
network_path = os.path.join(
models_path,
"RealESRGANv2",
"realesr-animevideov3.onnx"
)
elif model in [5005, 5006, 5007, 5008, 5009, 5010, 7000, 7001]:
network_path = os.path.join(
models_path,
"RealESRGANv2",
f"{RealESRGANv2Model(model).name}.onnx".replace('_', '-')
)
clip_org = clip
clip = inference_with_fallback(
clips=[clip], network_path=network_path,
overlap=(overlap_w, overlap_h), tilesize=(tile_w, tile_h),
backend=backend
)
if scale is not None:
scale_h = clip.width // clip_org.width
scale_v = clip.height // clip_org.height
assert scale_h == scale_v
if scale != scale_h:
rescale = scale / scale_h
if rescale > 1:
clip = core.resize.Lanczos(clip, int(clip_org.width * scale), int(clip_org.height * scale), filter_param_a=4)
else:
clip = fmtc_resample(clip, scale=rescale, kernel="lanczos", taps=4, fh=1/rescale, fv=1/rescale)
return clip
RealESRGANv2 = RealESRGAN
def CUGAN(
clip: vs.VideoNode,
noise: typing.Literal[-1, 0, 1, 2, 3] = -1,
scale: typing.Literal[2, 3, 4] = 2,
tiles: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
tilesize: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
overlap: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
backend: backendT = Backend.OV_CPU(),
alpha: float = 1.0,
version: typing.Literal[1, 2] = 1, # 1: legacy, 2: pro
conformance: bool = True # currently specifies dynamic range compression for cugan-pro
) -> vs.VideoNode:
"""
denoising strength: 0 < -1 < 1 < 2 < 3
version: (1 or 2)
1 -> legacy,
2 -> pro (only models for "noise" in [-1, 0, 3] and "scale" in [2, 3] are published currently)
"""
func_name = "vsmlrt.CUGAN"
if not isinstance(clip, vs.VideoNode):
raise TypeError(f'{func_name}: "clip" must be a clip!')
if clip.format.sample_type != vs.FLOAT or clip.format.bits_per_sample not in [16, 32]:
raise ValueError(f"{func_name}: only constant format 16/32 bit float input supported")
if not isinstance(noise, int) or noise not in range(-1, 4):
raise ValueError(f'{func_name}: "noise" must be -1, 0, 1, 2, or 3')
if not isinstance(scale, int) or scale not in (2, 3, 4):
raise ValueError(f'{func_name}: "scale" must be 2, 3 or 4')
if scale != 2 and noise in [1, 2]:
raise ValueError(
f'{func_name}: "scale={scale}" model'
f' does not support noise reduction level {noise}'
)
if clip.format.color_family != vs.RGB:
raise ValueError(f'{func_name}: "clip" must be of RGB color family')
if overlap is None:
overlap_w = overlap_h = 4
elif isinstance(overlap, int):
overlap_w = overlap_h = overlap
else:
overlap_w, overlap_h = overlap
multiple = 2
(tile_w, tile_h), (overlap_w, overlap_h) = calc_tilesize(
tiles=tiles, tilesize=tilesize,
width=clip.width, height=clip.height,
multiple=multiple,
overlap_w=overlap_w, overlap_h=overlap_h
)
if tile_w % multiple != 0 or tile_h % multiple != 0:
raise ValueError(
f'{func_name}: tile size must be divisible by {multiple} ({tile_w}, {tile_h})'
)
backend = init_backend(
backend=backend,
trt_opt_shapes=(tile_w, tile_h)
)
folder_path = os.path.join(models_path, "cugan")
if version == 1:
if noise == -1:
model_name = f"up{scale}x-latest-no-denoise.onnx"
elif noise == 0:
model_name = f"up{scale}x-latest-conservative.onnx"
else:
model_name = f"up{scale}x-latest-denoise{noise}x.onnx"
elif version == 2:
if noise == -1:
model_name = f"pro-no-denoise3x-up{scale}x.onnx"
elif noise == 0:
model_name = f"pro-conservative-up{scale}x.onnx"
else:
model_name = f"pro-denoise{noise}x-up{scale}x.onnx"
else:
raise ValueError(f'{func_name}: unknown version ({version}), must be 1 (legacy) or 2 (pro)')
network_path = os.path.join(folder_path, model_name)
# https://github.com/bilibili/ailab/blob/978f3be762183d7fa79525f29a43e65afb995f6b/Real-CUGAN/upcunet_v3.py#L207
# mutates network_path
if alpha != 1.0:
alpha = float(alpha)
import numpy as np
import onnx
from onnx import numpy_helper
model = onnx.load(network_path)
for idx, node in reversed(list(enumerate(model.graph.node))):
if node.op_type == "ConvTranspose":
break
upstream_name = node.input[0]
downstream_name = node.input[0] + "_mul"
node.input[0] = downstream_name
alpha_array = np.array(alpha, dtype=np.float32)
alpha_tensor = numpy_helper.from_array(alpha_array)
alpha_constant = onnx.helper.make_node(
"Constant",
inputs=[],
outputs=["alpha"],
value=alpha_tensor
)
model.graph.node.insert(idx, alpha_constant)
mul_node = onnx.helper.make_node(
"Mul",
inputs=[upstream_name, "alpha"],
outputs=[downstream_name]
)
model.graph.node.insert(idx+1, mul_node)
if backend.supports_onnx_serialization:
if conformance and version == 2:
clip = core.std.Expr(clip, "x 0.7 * 0.15 +")
clip = inference_with_fallback(
clips=[clip], network_path=model.SerializeToString(),
overlap=(overlap_w, overlap_h), tilesize=(tile_w, tile_h),
backend=backend, path_is_serialization=True
)
if conformance and version == 2:
clip = core.std.Expr(clip, "x 0.15 - 0.7 /")
return clip
network_path = f"{network_path}_alpha{alpha!r}.onnx"
onnx.save(model, network_path)
# https://github.com/bilibili/ailab/blob/e102bef22384c629f82552dbec3d6b5bab125639/Real-CUGAN/upcunet_v3.py#L1275-L1276
if conformance and version == 2:
clip = core.std.Expr(clip, "x 0.7 * 0.15 +")
clip = inference_with_fallback(
clips=[clip], network_path=network_path,
overlap=(overlap_w, overlap_h), tilesize=(tile_w, tile_h),
backend=backend
)
# https://github.com/bilibili/ailab/blob/e102bef22384c629f82552dbec3d6b5bab125639/Real-CUGAN/upcunet_v3.py#L269
if conformance and version == 2:
clip = core.std.Expr(clip, "x 0.15 - 0.7 /")
return clip
def get_rife_input(clip: vs.VideoNode) -> typing.List[vs.VideoNode]:
assert clip.format.sample_type == vs.FLOAT
gray_format = vs.GRAYS if clip.format.bits_per_sample == 32 else vs.GRAYH
if (hasattr(core, 'akarin') and
b"width" in core.akarin.Version()["expr_features"] and
b"height" in core.akarin.Version()["expr_features"]
):
if b"fp16" in core.akarin.Version()["expr_features"]:
empty = clip.std.BlankClip(format=gray_format, length=1)
else:
empty = clip.std.BlankClip(format=vs.GRAYS, length=1)
horizontal = bits_as(core.akarin.Expr(empty, 'X 2 * width 1 - / 1 -'), clip)
vertical = bits_as(core.akarin.Expr(empty, 'Y 2 * height 1 - / 1 -'), clip)
else:
empty = clip.std.BlankClip(format=vs.GRAYS, length=1)
from functools import partial
def meshgrid_core(n: int, f: vs.VideoFrame, horizontal: bool) -> vs.VideoFrame:
fout = f.copy()
is_api4 = hasattr(vs, "__api_version__") and vs.__api_version__.api_major == 4
if is_api4:
mem_view = fout[0]
else:
mem_view = fout.get_write_array(0)
height, width = mem_view.shape
if horizontal:
for i in range(height):
for j in range(width):
mem_view[i, j] = 2 * j / (width - 1) - 1
else:
for i in range(height):
for j in range(width):
mem_view[i, j] = 2 * i / (height - 1) - 1
return fout
horizontal = bits_as(core.std.ModifyFrame(empty, empty, partial(meshgrid_core, horizontal=True)), clip)
vertical = bits_as(core.std.ModifyFrame(empty, empty, partial(meshgrid_core, horizontal=False)), clip)
horizontal = horizontal.std.Loop(clip.num_frames)
vertical = vertical.std.Loop(clip.num_frames)
multiplier_h = clip.std.BlankClip(format=gray_format, color=2/(clip.width-1), keep=True)
multiplier_w = clip.std.BlankClip(format=gray_format, color=2/(clip.height-1), keep=True)
return [horizontal, vertical, multiplier_h, multiplier_w]
@enum.unique
class RIFEModel(enum.IntEnum):
"""
Starting from RIFE v4.12 lite, this interface does not provide forward compatiblity in enum values.
"""
v4_0 = 40
v4_2 = 42
v4_3 = 43
v4_4 = 44
v4_5 = 45
v4_6 = 46
v4_7 = 47
v4_8 = 48
v4_9 = 49
v4_10 = 410
v4_11 = 411
v4_12 = 412
v4_12_lite = 4121
v4_13 = 413
v4_13_lite = 4131
v4_14 = 414
v4_14_lite = 4141
v4_15 = 415
v4_15_lite = 4151
v4_16_lite = 4161
v4_17 = 417
v4_17_lite = 4171
v4_18 = 418
v4_19 = 419
v4_20 = 420
v4_21 = 421
v4_22 = 422
v4_22_lite = 4221
v4_23 = 423
v4_24 = 424
v4_25 = 425
v4_25_lite = 4251
v4_25_heavy = 4252
v4_26 = 426
v4_26_heavy = 4262
def RIFEMerge(
clipa: vs.VideoNode,
clipb: vs.VideoNode,
mask: vs.VideoNode,
scale: float = 1.0,
tiles: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
tilesize: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
overlap: typing.Optional[typing.Union[int, typing.Tuple[int, int]]] = None,
model: RIFEModel = RIFEModel.v4_4,
backend: backendT = Backend.OV_CPU(),
ensemble: bool = False,
_implementation: typing.Optional[typing.Literal[1, 2]] = None
) -> vs.VideoNode:
""" temporal MaskedMerge-like interface for the RIFE model
Its semantics is similar to core.std.MaskedMerge(clipa, clipb, mask, first_plane=True),
except that it merges the two clips in the time domain and you specify the "mask" based
on the time point of the resulting clip (range (0,1)) between the two clips.
"""
func_name = "vsmlrt.RIFEMerge"
for clip in (clipa, clipb, mask):
if not isinstance(clip, vs.VideoNode):
raise TypeError(f'{func_name}: clip must be a clip!')
if clip.format.sample_type != vs.FLOAT or clip.format.bits_per_sample not in [16, 32]:
raise ValueError(f"{func_name}: only constant format 16/32 bit float input supported")
for clip in (clipa, clipb):
if clip.format.color_family != vs.RGB:
raise ValueError(f'{func_name}: "clipa" / "clipb" must be of RGB color family')
if clip.width != mask.width or clip.height != mask.height:
raise ValueError(f'{func_name}: video dimensions mismatch')
if clip.num_frames != mask.num_frames:
raise ValueError(f'{func_name}: number of frames mismatch')
if mask.format.color_family != vs.GRAY:
raise ValueError(f'{func_name}: "mask" must be of GRAY color family')
if tiles is not None or tilesize is not None or overlap is not None:
raise ValueError(f'{func_name}: tiling is not supported')
if overlap is None:
overlap_w = overlap_h = 0