Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
:param first_time: prevents posting warnings multiple times
:return: best resolutions list and plot matplotlib.pyplot
"""
if type(args) == list:
args = parser.parse_args(args)
output_dir = Path(args.dir).resolve()
if not os.access(output_dir, os.W_OK):
raise PermissionError(f"Missing write permissions: {output_dir}")
output_dir = output_dir.joinpath("results")
if (args.img or args.mask_out) and imwri is None:
raise GetnativeException("imwri not found.")
if scaler is None:
scaler = _DefineScaler(args.kernel, b=args.b, c=args.c, taps=args.taps)
else:
scaler = scaler
if scaler.plugin is None:
if "toggaf.asi.xe" in core.get_plugins():
print("Error: descale_getnative support ended, pls use https://github.com/Irrational-Encoding-Wizardry/vapoursynth-descale")
raise GetnativeException('No descale found!')
if args.steps != 1 and first_time:
print(
"Warning for -steps/--stepping: "
"If you are not completely sure what this parameter does, use the default step size.\n"
)
if args.frame is None:
args.frame = src.num_frames // 3
)
if args.frame is None:
args.frame = src.num_frames // 3
elif args.frame < 0:
args.frame = src.num_frames // -args.frame
elif args.frame > src.num_frames - 1:
raise GetnativeException(f"Last frame is {src.num_frames - 1}, but you want {args.frame}")
if args.ar == 0:
args.ar = src.width / src.height
if args.min_h >= src.height:
raise GetnativeException(f"Input image {src.height} is smaller min_h {args.min_h}")
elif args.min_h >= args.max_h:
raise GetnativeException(f"min_h {args.min_h} > max_h {args.max_h}? Not processable")
elif args.max_h > src.height:
print(f"The image height is {src.height}, going higher is stupid! New max_h {src.height}")
args.max_h = src.height
getn = GetNative(src, scaler, args.ar, args.min_h, args.max_h, args.frame, args.mask_out, args.plot_scaling,
args.plot_format, args.show_plot, args.no_save, args.steps, output_dir)
try:
loop = asyncio.get_event_loop()
best_value, plot, resolutions = loop.run_until_complete(getn.run())
except ValueError as err:
raise GetnativeException(f"Error in getnative: {err}")
gc.collect()
print(
f"\n{scaler} AR: {args.ar:.2f} Steps: {args.steps}\n"
f"{best_value}\n"
if not os.access(output_dir, os.W_OK):
raise PermissionError(f"Missing write permissions: {output_dir}")
output_dir = output_dir.joinpath("results")
if (args.img or args.mask_out) and imwri is None:
raise GetnativeException("imwri not found.")
if scaler is None:
scaler = _DefineScaler(args.kernel, b=args.b, c=args.c, taps=args.taps)
else:
scaler = scaler
if scaler.plugin is None:
if "toggaf.asi.xe" in core.get_plugins():
print("Error: descale_getnative support ended, pls use https://github.com/Irrational-Encoding-Wizardry/vapoursynth-descale")
raise GetnativeException('No descale found!')
if args.steps != 1 and first_time:
print(
"Warning for -steps/--stepping: "
"If you are not completely sure what this parameter does, use the default step size.\n"
)
if args.frame is None:
args.frame = src.num_frames // 3
elif args.frame < 0:
args.frame = src.num_frames // -args.frame
elif args.frame > src.num_frames - 1:
raise GetnativeException(f"Last frame is {src.num_frames - 1}, but you want {args.frame}")
if args.ar == 0:
args.ar = src.width / src.height
args.frame = src.num_frames // -args.frame
elif args.frame > src.num_frames - 1:
raise GetnativeException(f"Last frame is {src.num_frames - 1}, but you want {args.frame}")
if args.ar == 0:
args.ar = src.width / src.height
if args.min_h >= src.height:
raise GetnativeException(f"Input image {src.height} is smaller min_h {args.min_h}")
elif args.min_h >= args.max_h:
raise GetnativeException(f"min_h {args.min_h} > max_h {args.max_h}? Not processable")
elif args.max_h > src.height:
print(f"The image height is {src.height}, going higher is stupid! New max_h {src.height}")
args.max_h = src.height
getn = GetNative(src, scaler, args.ar, args.min_h, args.max_h, args.frame, args.mask_out, args.plot_scaling,
args.plot_format, args.show_plot, args.no_save, args.steps, output_dir)
try:
loop = asyncio.get_event_loop()
best_value, plot, resolutions = loop.run_until_complete(getn.run())
except ValueError as err:
raise GetnativeException(f"Error in getnative: {err}")
gc.collect()
print(
f"\n{scaler} AR: {args.ar:.2f} Steps: {args.steps}\n"
f"{best_value}\n"
)
return resolutions, plot
mode = [scaler for scaler in common_scaler["bicubic"]]
mode.append(common_scaler["bilinear"][0])
elif args.mode == "all":
mode = [s for scaler in common_scaler.values() for s in scaler]
for i, scaler in enumerate(mode):
if scaler is not None and scaler.plugin is None:
print(f"Warning: No correct descale version found for {scaler}, continuing with next scaler when available.")
continue
getnative(args, src, scaler, first_time=True if i == 0 else False)
parser = argparse.ArgumentParser(description='Find the native resolution(s) of upscaled material (mostly anime)')
parser.add_argument('--frame', '-f', dest='frame', type=int, default=None, help='Specify a frame for the analysis. Random if unspecified. Negative frame numbers for a frame like this: src.num_frames // -args.frame')
parser.add_argument('--kernel', '-k', dest='kernel', type=str.lower, default="bicubic", help='Resize kernel to be used')
parser.add_argument('--bicubic-b', '-b', dest='b', type=to_float, default="1/3", help='B parameter of bicubic resize')
parser.add_argument('--bicubic-c', '-c', dest='c', type=to_float, default="1/3", help='C parameter of bicubic resize')
parser.add_argument('--lanczos-taps', '-t', dest='taps', type=int, default=3, help='Taps parameter of lanczos resize')
parser.add_argument('--aspect-ratio', '-ar', dest='ar', type=to_float, default=0, help='Force aspect ratio. Only useful for anamorphic input')
parser.add_argument('--min-height', '-min', dest="min_h", type=int, default=500, help='Minimum height to consider')
parser.add_argument('--max-height', '-max', dest="max_h", type=int, default=1000, help='Maximum height to consider')
parser.add_argument('--output-mask', '-mask', dest='mask_out', action="store_true", default=False, help='Save detail mask as png')
parser.add_argument('--plot-scaling', '-ps', dest='plot_scaling', type=str.lower, default='log', help='Scaling of the y axis. Can be "linear" or "log"')
parser.add_argument('--plot-format', '-pf', dest='plot_format', type=str.lower, default='svg', help='Format of the output image. Specify multiple formats separated by commas. Can be svg, png, pdf, rgba, jp(e)g, tif(f), and probably more')
parser.add_argument('--show-plot-gui', '-pg', dest='show_plot', action="store_true", default=False, help='Show an interactive plot gui window.')
parser.add_argument('--no-save', '-ns', dest='no_save', action="store_true", default=False, help='Do not save files to disk. Disables all output arguments!')
parser.add_argument('--is-image', '-img', dest='img', action="store_true", default=False, help='Force image input')
parser.add_argument('--stepping', '-steps', dest='steps', type=int, default=1, help='This changes the way getnative will handle resolutions. Example steps=3 [500p, 503p, 506p ...]')
parser.add_argument('--output-dir', '-dir', dest='dir', type=str, default="", help='Sets the path of the output dir where you want all results to be saved. (/results will always be added as last folder)')
def main():
parser.add_argument(dest='input_file', type=str, help='Absolute or relative path to the input file')
parser.add_argument('--use', '-u', default=None, help='Use specified source filter e.g. (lsmas.LWLibavSource)')
mode.append(common_scaler["bilinear"][0])
elif args.mode == "all":
mode = [s for scaler in common_scaler.values() for s in scaler]
for i, scaler in enumerate(mode):
if scaler is not None and scaler.plugin is None:
print(f"Warning: No correct descale version found for {scaler}, continuing with next scaler when available.")
continue
getnative(args, src, scaler, first_time=True if i == 0 else False)
parser = argparse.ArgumentParser(description='Find the native resolution(s) of upscaled material (mostly anime)')
parser.add_argument('--frame', '-f', dest='frame', type=int, default=None, help='Specify a frame for the analysis. Random if unspecified. Negative frame numbers for a frame like this: src.num_frames // -args.frame')
parser.add_argument('--kernel', '-k', dest='kernel', type=str.lower, default="bicubic", help='Resize kernel to be used')
parser.add_argument('--bicubic-b', '-b', dest='b', type=to_float, default="1/3", help='B parameter of bicubic resize')
parser.add_argument('--bicubic-c', '-c', dest='c', type=to_float, default="1/3", help='C parameter of bicubic resize')
parser.add_argument('--lanczos-taps', '-t', dest='taps', type=int, default=3, help='Taps parameter of lanczos resize')
parser.add_argument('--aspect-ratio', '-ar', dest='ar', type=to_float, default=0, help='Force aspect ratio. Only useful for anamorphic input')
parser.add_argument('--min-height', '-min', dest="min_h", type=int, default=500, help='Minimum height to consider')
parser.add_argument('--max-height', '-max', dest="max_h", type=int, default=1000, help='Maximum height to consider')
parser.add_argument('--output-mask', '-mask', dest='mask_out', action="store_true", default=False, help='Save detail mask as png')
parser.add_argument('--plot-scaling', '-ps', dest='plot_scaling', type=str.lower, default='log', help='Scaling of the y axis. Can be "linear" or "log"')
parser.add_argument('--plot-format', '-pf', dest='plot_format', type=str.lower, default='svg', help='Format of the output image. Specify multiple formats separated by commas. Can be svg, png, pdf, rgba, jp(e)g, tif(f), and probably more')
parser.add_argument('--show-plot-gui', '-pg', dest='show_plot', action="store_true", default=False, help='Show an interactive plot gui window.')
parser.add_argument('--no-save', '-ns', dest='no_save', action="store_true", default=False, help='Do not save files to disk. Disables all output arguments!')
parser.add_argument('--is-image', '-img', dest='img', action="store_true", default=False, help='Force image input')
parser.add_argument('--stepping', '-steps', dest='steps', type=int, default=1, help='This changes the way getnative will handle resolutions. Example steps=3 [500p, 503p, 506p ...]')
parser.add_argument('--output-dir', '-dir', dest='dir', type=str, default="", help='Sets the path of the output dir where you want all results to be saved. (/results will always be added as last folder)')
def main():
parser.add_argument(dest='input_file', type=str, help='Absolute or relative path to the input file')
parser.add_argument('--use', '-u', default=None, help='Use specified source filter e.g. (lsmas.LWLibavSource)')
parser.add_argument('--mode', '-m', dest='mode', type=str, choices=_modes, default=None, help='Choose a predefined mode ["bilinear", "bicubic", "bl-bc", "all"]')
f"{self.kernel.capitalize()}"
f"{'' if self.kernel != 'bicubic' else f' b {self.b:.2f} c {self.c:.2f}'}"
f"{'' if self.kernel != 'lanczos' else f' taps {self.taps}'}"
)
def __repr__(self):
return (
f"ScalerObject: "
f"{self.kernel.capitalize()}"
f"{'' if self.kernel != 'bicubic' else f' b {self.b:.2f} c {self.c:.2f}'}"
f"{'' if self.kernel != 'lanczos' else f' taps {self.taps}'}"
)
common_scaler = {
"bilinear": [_DefineScaler("bilinear")],
"bicubic": [
_DefineScaler("bicubic", b=1 / 3, c=1 / 3),
_DefineScaler("bicubic", b=.5, c=0),
_DefineScaler("bicubic", b=0, c=.5),
_DefineScaler("bicubic", b=1, c=0),
_DefineScaler("bicubic", b=0, c=1),
_DefineScaler("bicubic", b=.2, c=.5),
_DefineScaler("bicubic", b=.5, c=.5),
],
"lanczos": [
_DefineScaler("lanczos", taps=2),
_DefineScaler("lanczos", taps=3),
_DefineScaler("lanczos", taps=4),
_DefineScaler("lanczos", taps=5),
],
"spline": [
_DefineScaler("bicubic", b=0, c=.5),
_DefineScaler("bicubic", b=1, c=0),
_DefineScaler("bicubic", b=0, c=1),
_DefineScaler("bicubic", b=.2, c=.5),
_DefineScaler("bicubic", b=.5, c=.5),
],
"lanczos": [
_DefineScaler("lanczos", taps=2),
_DefineScaler("lanczos", taps=3),
_DefineScaler("lanczos", taps=4),
_DefineScaler("lanczos", taps=5),
],
"spline": [
_DefineScaler("spline16"),
_DefineScaler("spline36"),
_DefineScaler("spline64"),
]
}
class GetNative:
def __init__(self, src, scaler, ar, min_h, max_h, frame, mask_out, plot_scaling, plot_format, show_plot, no_save,
steps, output_dir):
self.plot_format = plot_format
self.plot_scaling = plot_scaling
self.src = src
self.min_h = min_h
self.max_h = max_h
self.ar = ar
self.scaler = scaler
self.frame = frame
self.mask_out = mask_out
_DefineScaler("bicubic", b=.5, c=0),
_DefineScaler("bicubic", b=0, c=.5),
_DefineScaler("bicubic", b=1, c=0),
_DefineScaler("bicubic", b=0, c=1),
_DefineScaler("bicubic", b=.2, c=.5),
_DefineScaler("bicubic", b=.5, c=.5),
],
"lanczos": [
_DefineScaler("lanczos", taps=2),
_DefineScaler("lanczos", taps=3),
_DefineScaler("lanczos", taps=4),
_DefineScaler("lanczos", taps=5),
],
"spline": [
_DefineScaler("spline16"),
_DefineScaler("spline36"),
_DefineScaler("spline64"),
]
}
class GetNative:
def __init__(self, src, scaler, ar, min_h, max_h, frame, mask_out, plot_scaling, plot_format, show_plot, no_save,
steps, output_dir):
self.plot_format = plot_format
self.plot_scaling = plot_scaling
self.src = src
self.min_h = min_h
self.max_h = max_h
self.ar = ar
self.scaler = scaler
self.frame = frame
def mask_detail(self, clip, final_width, final_height):
temp = self.scaler.descaler(clip, final_width, final_height)
temp = self.scaler.upscaler(temp, clip.width, clip.height)
mask = core.std.Expr([clip, temp], 'x y - abs dup 0.015 > swap 16 * 0 ?').std.Inflate()
mask = _DefineScaler(kernel="spline36").upscaler(mask, final_width, final_height)
return mask