35 Commits
4.7.0 ... 4.8.1

Author SHA1 Message Date
K4YT3X
095d40b688 Merge pull request #434 from k4yt3x/black
Formatted code with Black and updated README
2020-12-21 01:58:19 +00:00
K4YT3X
bd6690fed1 updated Patreon badge 2020-12-20 20:56:49 -05:00
K4YT3X
bfda833bcf formatted code with black 2020-12-19 18:11:11 -05:00
K4YT3X
09345703e6 fixed video2x ubuntu setup script paths 2020-12-15 13:05:16 -05:00
K4YT3X
64e4a41710 Merge pull request #424 from fire0shadow/anime4kcpp-import-fix
Add 'import sys' to anime4kcpp.py wrapper
2020-12-15 17:59:28 +00:00
K4YT3X
f7b8b2520a sorted imports and updated file metadata 2020-12-15 17:58:45 +00:00
K4YT3X
fad793b18e formatted build script 2020-12-15 12:56:28 -05:00
K4YT3X
d09d05ae9b fixed video2x_gui name 2020-12-15 12:55:58 -05:00
Fireshadow
89ca3b09d9 Add 'import sys' to anime4kcpp.py wrapper 2020-12-14 23:26:16 +07:00
K4YT3X
4694c557ec added a none option for -tune to address #401 2020-12-13 17:13:03 -05:00
K4YT3X
33d96bcd4e added Discord server description 2020-12-13 16:55:37 -05:00
K4YT3X
eee43def3b redirected subprocess.Popen streams to system stdout and stderr 2020-12-13 16:53:55 -05:00
K4YT3X
f4be9cc596 BiLogger now inherits io.TextIOWrapper and has a fileno attribute 2020-12-13 16:52:58 -05:00
K4YT3X
cc89b0aac5 formatted setup script with black 2020-12-13 16:39:49 -05:00
K4YT3X
9e8e95803f setup script 2.4.1: fixed Gifski setup issues and enhanced garbage cleaning 2020-12-13 16:39:13 -05:00
K4YT3X
df0861ff5c Merge pull request #411 from konqiDAM/master
fix: windows installer fixed, now uses "zipball_url" for gifski
2020-11-18 20:24:54 +00:00
K4YT3X
706aeab03f updated setup script metadata 2020-11-18 20:24:17 +00:00
konqi
f850ca80f1 fix: windows installer fixed, now uses "zipball_url" for gifski 2020-11-18 20:56:56 +01:00
K4YT3X
608bf1a2ec added a link for @Felixkruemel 's name 2020-10-26 18:24:43 -04:00
K4YT3X
b1f7290c20 update Google Colab descriptions 2020-10-26 18:22:52 -04:00
K4YT3X
65d445c293 upscaler 4.4.1: use mimetypes to re-check python-magic's results 2020-10-26 18:14:49 -04:00
K4YT3X
43dbb134b6 Merge pull request #389 from jitsuCM/arr_fix
Quick fix for special case no-upscale 1.0 upscale
2020-10-26 22:09:04 +00:00
K4YT3X
84b0684d64 apply the smallest scaling ratio available instead of 1 2020-10-26 21:53:03 +00:00
K4YT3X
29b4153b63 Merge pull request #384 from Felixkruemel/master
Added Google Colab to readme
2020-10-26 21:47:43 +00:00
K4YT3X
3f1821f1ac Merge pull request #373 from donicrosby/master
Fixed issue where if hwaccel value in config is overwritten with auto
2020-10-26 21:47:16 +00:00
K4YT3X
4f8bb1be1c setup script 2.4.0: updated FFmpeg download URL and unpacking method 2020-10-26 13:13:54 -04:00
jitsuCM
c2f1e43656 Quick fix for special case no-upscale 1.0 upscale 2020-10-22 09:21:53 +02:00
Felixkruemel
914d5cdf87 fixed blank line 2020-10-13 19:27:36 +02:00
Felixkruemel
de77c90dd1 Updated Readme.md with Google Colab integration 2020-10-13 19:26:53 +02:00
donicrosby
458ce82644 Merge branch 'master' of https://github.com/k4yt3x/video2x into master 2020-09-29 17:18:37 -04:00
donicrosby
1d145a8690 Fixed issue where if hwaccel value is set to anything other auto it would be overwritten 2020-09-29 00:51:32 -04:00
K4YT3X
b37acfa31d setup script 2.3.0: changed FFmpeg build provider from zeranoe to gyan.dev 2020-09-28 20:31:22 -04:00
K4YT3X
a0522311e2 made custom intermediate frame format available for waifu2x/srmd/realsr 2020-09-21 15:14:00 -04:00
K4YT3X
7de9cc699a Merge pull request #363 from medram/waifu2x_ncnn_vulkan_args_update
Fixed supporting jpg format for waifu2x_ncnn_vulkan by updating its arguments.
2020-09-21 19:06:42 +00:00
medram
685648957f Update waifu2x_ncnn_vulkan arguments to the latest version! 2020-09-20 21:34:20 +01:00
20 changed files with 2428 additions and 1338 deletions

View File

@@ -8,12 +8,14 @@
![GitHub All Releases](https://img.shields.io/github/downloads/k4yt3x/video2x/total?style=flat-square)
![GitHub](https://img.shields.io/github/license/k4yt3x/video2x?style=flat-square)
![Platforms](https://img.shields.io/badge/Platforms-Windows%20%7C%20Linux%20%7C%20macOS-blue?style=flat-square)
![Become A Patron!](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Fshieldsio-patreon.herokuapp.com%2Fk4yt3x&style=flat-square)
![Become A Patron!](https://img.shields.io/badge/dynamic/json?color=%23e85b46&label=Patreon&query=data.attributes.patron_count&suffix=%20patrons&url=https%3A%2F%2Fwww.patreon.com%2Fapi%2Fcampaigns%2F4507807&style=flat-square)
<!--# Video2X Lossless Video Enlarger-->
### Official Discussion Group (Telegram): https://t.me/video2x
A [Discord server](https://discord.gg/Pwf6Ht) is also available. Please note that most developers are only on Telegram. If you join the Discord server, the developers might not be able to see your questions and help you. It is mostly for user-user interactions and those who do not want to use Telegram.
## [Download Stable/Beta Builds](https://github.com/k4yt3x/video2x/releases/latest) (Windows)
- **`Full`**: full package comes pre-configured with **all** dependencies like `FFmpeg` and `waifu2x-caffe`.
@@ -37,6 +39,12 @@ To download the latest nightly build, go to the [GitHub Actions](https://github.
Video2X Docker images are available on Docker Hub for easy and rapid Video2X deployment on Linux and macOS. If you already have Docker installed, then only one command is needed to start upscaling a video. For more information on how to use Video2X's Docker image, please refer to the [documentations](https://github.com/K4YT3X/video2x/wiki/Docker).
## [Google Colab](https://colab.research.google.com/drive/1xqeZvoJXaBBPP6UyVwErnhwrnth0br0u)
You can use Video2X on [Google Colab](https://colab.research.google.com/) for free. Colab allows you too use a GPU on Google's Servers (Tesla K80, T4, P4, P100). Please bare in mind that Colab can only be provided for free if all users know that they shouldn't abuse it. A single free-tier tier session can last up to 12 hours. Please do not abuse the platform by creating sessions back-to-back and running upscaling 24/7. This might result in you getting banned.
Here is an exmaple Notebook written by [@Felixkruemel](https://github.com/Felixkruemel): [Video2X_on_Colab.ipynb](https://colab.research.google.com/drive/1xqeZvoJXaBBPP6UyVwErnhwrnth0br0u). This file can be used in combination of the following modified configuration file: [@Felixkruemel's Video2X configuration for Google Colab](https://gist.githubusercontent.com/Felixkruemel/71e62de4bb38965ead2e0f4bae7ef4ee/raw/video2x.yaml).
## Introduction
Video2X is a video/GIF/image upscaling software based on Waifu2X, Anime4K, SRMD and RealSR written in Python 3. It upscales videos, GIFs and images, restoring details from low-resolution inputs. Video2X also accepts GIF input to video output and video input to GIF output.
@@ -224,56 +232,6 @@ Are you interested in how the idea of Video2X was born? Do you want to know the
---
# Full Usage
## Video2X Options
### -h, --help
show this help message and exit
### -i INPUT, --input INPUT
source video file/directory
### -o OUTPUT, --output OUTPUT
output video file/directory
### -c CONFIG, --config CONFIG
video2x config file path
### --log LOG
log file path (default: program_directory\video2x_%Y-%m-%d_%H-%M-%S.log)
### --disable_logging
disable logging (default: False)
### -v, --version
display version, lawful information and exit
## Upscaling Options
### -d DRIVER, --driver DRIVER
upscaling driver (default: waifu2x_caffe)
Available options are:
- waifu2x_caffe
- waifu2x_converter_cpp
- waifu2x_ncnn_vulkan
- srmd_ncnn_vulkan
- realsr_ncnn_vulkan
- anime4kcpp
### -r RATIO, --ratio RATIO
scaling ratio
### -p PROCESSES, --processes PROCESSES
number of processes to use for upscaling (default: 1)
### --preserve_frames
preserve extracted and upscaled frames (default: False)
---
## License
Licensed under the GNU General Public License Version 3 (GNU GPL v3)

View File

@@ -4,22 +4,22 @@
Creator: Video2X Bidirectional Logger
Author: K4YT3X
Date Created: June 4, 2020
Last Modified: September 13, 2020
Last Modified: December 13, 2020
"""
# built-in imports
import _io
import io
class BiLogger(object):
""" A bidirectional logger that both prints the output
class BiLogger(io.TextIOWrapper):
"""A bidirectional logger that both prints the output
and log all output to file.
Original code from: https://stackoverflow.com/a/14906787
"""
def __init__(self, terminal: _io.TextIOWrapper, log_file: _io.BufferedRandom):
""" initialize BiLogger
def __init__(self, terminal: io.TextIOWrapper, log_file: io.BufferedRandom):
"""initialize BiLogger
Args:
terminal (_io.TextIOWrapper): original terminal IO wrapper
@@ -27,9 +27,10 @@ class BiLogger(object):
"""
self.terminal = terminal
self.log_file = log_file
self.fileno = self.log_file.fileno
def write(self, message: str):
""" write message to original terminal output and log file
"""write message to original terminal output and log file
Args:
message (str): message to write
@@ -40,6 +41,5 @@ class BiLogger(object):
self.log_file.flush()
def flush(self):
""" flush logger (for compability only)
"""
"""flush logger (for compability only)"""
pass

View File

@@ -12,7 +12,7 @@ To start a PowerShell session with execution policy bypass
powershell -ExecutionPolicy Bypass
#>
if ($args.count -ne 1){
if ($args.count -ne 1) {
Write-Host -ForegroundColor White "Usage:`n .\build.ps1 VIDEO2X_VERSION"
Exit
}
@@ -88,7 +88,7 @@ Copy-Item "requirements.txt" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2
Write-Host -ForegroundColor White "`nDeleting temporary files"
$pathsToRemove = "__pycache__", "build", "dist", "*.spec"
foreach ($path in $pathsToRemove){
foreach ($path in $pathsToRemove) {
Write-Host "Removing path: $($path)"
Remove-Item -path $path -recurse
}

View File

@@ -22,7 +22,7 @@ import time
class ImageCleaner(threading.Thread):
""" Video2X Image Cleaner
"""Video2X Image Cleaner
This class creates an object that keeps track of extracted
frames that has already been upscaled and are not needed
@@ -40,8 +40,7 @@ class ImageCleaner(threading.Thread):
self.running = False
def run(self):
""" Run image cleaner
"""
"""Run image cleaner"""
self.running = True
while self.running:
@@ -49,13 +48,12 @@ class ImageCleaner(threading.Thread):
time.sleep(1)
def stop(self):
""" Stop the image cleaner
"""
"""Stop the image cleaner"""
self.running = False
self.join()
def remove_upscaled_frames(self):
""" remove frames that have already been upscaled
"""remove frames that have already been upscaled
This method compares the files in the extracted frames
directory with the upscaled frames directory, and removes

View File

@@ -17,7 +17,7 @@ from tqdm import tqdm
class ProgressMonitor(threading.Thread):
""" progress monitor
"""progress monitor
This class provides progress monitoring functionalities
by keeping track of the amount of frames in the input
@@ -34,7 +34,15 @@ class ProgressMonitor(threading.Thread):
def run(self):
self.running = True
with tqdm(total=self.upscaler.total_frames, ascii=True, desc=_('Processing: {} (pass {}/{})').format(self.upscaler.current_input_file.name, self.upscaler.current_pass, len(self.upscaler.scaling_jobs))) as progress_bar:
with tqdm(
total=self.upscaler.total_frames,
ascii=True,
desc=_("Processing: {} (pass {}/{})").format(
self.upscaler.current_input_file.name,
self.upscaler.current_pass,
len(self.upscaler.scaling_jobs),
),
) as progress_bar:
# tqdm update method adds the value to the progress
# bar instead of setting the value. Therefore, a delta
# needs to be calculated.
@@ -42,7 +50,13 @@ class ProgressMonitor(threading.Thread):
while self.running:
with contextlib.suppress(FileNotFoundError):
upscaled_frames = [f for f in self.upscaler.upscaled_frames.iterdir() if str(f).lower().endswith(self.upscaler.extracted_frame_format.lower())]
upscaled_frames = [
f
for f in self.upscaler.upscaled_frames.iterdir()
if str(f)
.lower()
.endswith(self.upscaler.extracted_frame_format.lower())
]
if len(upscaled_frames) >= 1:
self.upscaler.last_frame_upscaled = sorted(upscaled_frames)[-1]
self.upscaler.total_frames_upscaled = len(upscaled_frames)

File diff suppressed because it is too large Load Diff

View File

@@ -71,75 +71,143 @@ import yaml
from avalon_framework import Avalon
# internationalization constants
DOMAIN = 'video2x'
LOCALE_DIRECTORY = pathlib.Path(__file__).parent.absolute() / 'locale'
DOMAIN = "video2x"
LOCALE_DIRECTORY = pathlib.Path(__file__).parent.absolute() / "locale"
# getting default locale settings
default_locale, encoding = locale.getdefaultlocale()
language = gettext.translation(DOMAIN, LOCALE_DIRECTORY, [default_locale], fallback=True)
language = gettext.translation(
DOMAIN, LOCALE_DIRECTORY, [default_locale], fallback=True
)
language.install()
_ = language.gettext
CLI_VERSION = '4.3.1'
CLI_VERSION = "4.3.1"
LEGAL_INFO = _('''Video2X CLI Version: {}
LEGAL_INFO = _(
"""Video2X CLI Version: {}
Upscaler Version: {}
Author: K4YT3X
License: GNU GPL v3
Github Page: https://github.com/k4yt3x/video2x
Contact: k4yt3x@k4yt3x.com''').format(CLI_VERSION, UPSCALER_VERSION)
Contact: k4yt3x@k4yt3x.com"""
).format(CLI_VERSION, UPSCALER_VERSION)
LOGO = r'''
LOGO = r"""
__ __ _ _ ___ __ __
\ \ / / (_) | | |__ \ \ \ / /
\ \ / / _ __| | ___ ___ ) | \ V /
\ \/ / | | / _` | / _ \ / _ \ / / > <
\ / | | | (_| | | __/ | (_) | / /_ / . \
\/ |_| \__,_| \___| \___/ |____| /_/ \_\
'''
"""
def parse_arguments():
""" parse CLI arguments
"""
parser = argparse.ArgumentParser(prog='video2x', formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
"""parse CLI arguments"""
parser = argparse.ArgumentParser(
prog="video2x",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
add_help=False,
)
# video options
video2x_options = parser.add_argument_group(_('Video2X Options'))
video2x_options.add_argument('--help', action='help', help=_('show this help message and exit'))
video2x_options = parser.add_argument_group(_("Video2X Options"))
video2x_options.add_argument(
"--help", action="help", help=_("show this help message and exit")
)
# if help is in arguments list
# do not require input and output path to be specified
require_input_output = True
if '-h' in sys.argv or '--help' in sys.argv:
if "-h" in sys.argv or "--help" in sys.argv:
require_input_output = False
video2x_options.add_argument('-i', '--input', type=pathlib.Path, help=_('source video file/directory'), required=require_input_output)
video2x_options.add_argument('-o', '--output', type=pathlib.Path, help=_('output video file/directory'), required=require_input_output)
video2x_options.add_argument('-c', '--config', type=pathlib.Path, help=_('Video2X config file path'), action='store',
default=pathlib.Path(__file__).parent.absolute() / 'video2x.yaml')
video2x_options.add_argument('--log', type=pathlib.Path, help=_('log file path'))
video2x_options.add_argument('-v', '--version', help=_('display version, lawful information and exit'), action='store_true')
video2x_options.add_argument(
"-i",
"--input",
type=pathlib.Path,
help=_("source video file/directory"),
required=require_input_output,
)
video2x_options.add_argument(
"-o",
"--output",
type=pathlib.Path,
help=_("output video file/directory"),
required=require_input_output,
)
video2x_options.add_argument(
"-c",
"--config",
type=pathlib.Path,
help=_("Video2X config file path"),
action="store",
default=pathlib.Path(__file__).parent.absolute() / "video2x.yaml",
)
video2x_options.add_argument("--log", type=pathlib.Path, help=_("log file path"))
video2x_options.add_argument(
"-v",
"--version",
help=_("display version, lawful information and exit"),
action="store_true",
)
# scaling options
upscaling_options = parser.add_argument_group(_('Upscaling Options'))
upscaling_options.add_argument('-r', '--ratio', help=_('scaling ratio'), action='store', type=float)
upscaling_options.add_argument('-w', '--width', help=_('output width'), action='store', type=float)
upscaling_options.add_argument('-h', '--height', help=_('output height'), action='store', type=float)
upscaling_options.add_argument('-d', '--driver', help=_('upscaling driver'), choices=AVAILABLE_DRIVERS, default='waifu2x_ncnn_vulkan')
upscaling_options.add_argument('-p', '--processes', help=_('number of processes to use for upscaling'), action='store', type=int, default=1)
upscaling_options.add_argument('--preserve_frames', help=_('preserve extracted and upscaled frames'), action='store_true')
upscaling_options = parser.add_argument_group(_("Upscaling Options"))
upscaling_options.add_argument(
"-r", "--ratio", help=_("scaling ratio"), action="store", type=float
)
upscaling_options.add_argument(
"-w", "--width", help=_("output width"), action="store", type=float
)
upscaling_options.add_argument(
"-h", "--height", help=_("output height"), action="store", type=float
)
upscaling_options.add_argument(
"-d",
"--driver",
help=_("upscaling driver"),
choices=AVAILABLE_DRIVERS,
default="waifu2x_ncnn_vulkan",
)
upscaling_options.add_argument(
"-p",
"--processes",
help=_("number of processes to use for upscaling"),
action="store",
type=int,
default=1,
)
upscaling_options.add_argument(
"--preserve_frames",
help=_("preserve extracted and upscaled frames"),
action="store_true",
)
# if no driver arguments are specified
if '--' not in sys.argv:
if "--" not in sys.argv:
video2x_args = parser.parse_args()
return video2x_args, None
# if driver arguments are specified
else:
video2x_args = parser.parse_args(sys.argv[1:sys.argv.index('--')])
wrapper = getattr(importlib.import_module(f'wrappers.{video2x_args.driver}'), 'WrapperMain')
driver_args = wrapper.parse_arguments(sys.argv[sys.argv.index('--') + 1:])
video2x_args = parser.parse_args(sys.argv[1 : sys.argv.index("--")])
wrapper = getattr(
importlib.import_module(f"wrappers.{video2x_args.driver}"), "WrapperMain"
)
driver_args = wrapper.parse_arguments(sys.argv[sys.argv.index("--") + 1 :])
return video2x_args, driver_args
@@ -151,7 +219,7 @@ def print_logo():
def read_config(config_file: pathlib.Path) -> dict:
""" read video2x configurations from config file
"""read video2x configurations from config file
Arguments:
config_file {pathlib.Path} -- video2x configuration file pathlib.Path
@@ -160,16 +228,16 @@ def read_config(config_file: pathlib.Path) -> dict:
dict -- dictionary of video2x configuration
"""
with open(config_file, 'r') as config:
with open(config_file, "r") as config:
return yaml.load(config, Loader=yaml.FullLoader)
# /////////////////// Execution /////////////////// #
# this is not a library
if __name__ != '__main__':
Avalon.error(_('This file cannot be imported'))
raise ImportError(f'{__file__} cannot be imported')
if __name__ != "__main__":
Avalon.error(_("This file cannot be imported"))
raise ImportError(f"{__file__} cannot be imported")
# print video2x logo
print_logo()
@@ -183,15 +251,19 @@ if video2x_args.version:
sys.exit(0)
# additional checks on upscaling arguments
if video2x_args.ratio is not None and (video2x_args.width is not None or video2x_args.height is not None):
Avalon.error(_('Specify either scaling ratio or scaling resolution, not both'))
if video2x_args.ratio is not None and (
video2x_args.width is not None or video2x_args.height is not None
):
Avalon.error(_("Specify either scaling ratio or scaling resolution, not both"))
sys.exit(1)
# redirect output to both terminal and log file
if video2x_args.log is not None:
log_file = video2x_args.log.open(mode='a+', encoding='utf-8')
log_file = video2x_args.log.open(mode="a+", encoding="utf-8")
else:
log_file = tempfile.TemporaryFile(mode='a+', suffix='.log', prefix='video2x_', encoding='utf-8')
log_file = tempfile.TemporaryFile(
mode="a+", suffix=".log", prefix="video2x_", encoding="utf-8"
)
original_stdout = sys.stdout
original_stderr = sys.stderr
@@ -203,22 +275,22 @@ config = read_config(video2x_args.config)
# load waifu2x configuration
driver_settings = config[video2x_args.driver]
driver_settings['path'] = os.path.expandvars(driver_settings['path'])
driver_settings["path"] = os.path.expandvars(driver_settings["path"])
# read FFmpeg configuration
ffmpeg_settings = config['ffmpeg']
ffmpeg_settings['ffmpeg_path'] = os.path.expandvars(ffmpeg_settings['ffmpeg_path'])
ffmpeg_settings = config["ffmpeg"]
ffmpeg_settings["ffmpeg_path"] = os.path.expandvars(ffmpeg_settings["ffmpeg_path"])
# read Gifski configuration
gifski_settings = config['gifski']
gifski_settings['gifski_path'] = os.path.expandvars(gifski_settings['gifski_path'])
gifski_settings = config["gifski"]
gifski_settings["gifski_path"] = os.path.expandvars(gifski_settings["gifski_path"])
# load video2x settings
extracted_frame_format = config['video2x']['extracted_frame_format'].lower()
output_file_name_format_string = config['video2x']['output_file_name_format_string']
image_output_extension = config['video2x']['image_output_extension']
video_output_extension = config['video2x']['video_output_extension']
preserve_frames = config['video2x']['preserve_frames']
extracted_frame_format = config["video2x"]["extracted_frame_format"].lower()
output_file_name_format_string = config["video2x"]["output_file_name_format_string"]
image_output_extension = config["video2x"]["image_output_extension"]
video_output_extension = config["video2x"]["video_output_extension"]
preserve_frames = config["video2x"]["preserve_frames"]
# if preserve frames specified in command line
# overwrite config file options
@@ -227,10 +299,10 @@ if video2x_args.preserve_frames is True:
# if cache directory not specified
# use default path: %TEMP%\video2x
if config['video2x']['video2x_cache_directory'] is None:
video2x_cache_directory = (pathlib.Path(tempfile.gettempdir()) / 'video2x')
if config["video2x"]["video2x_cache_directory"] is None:
video2x_cache_directory = pathlib.Path(tempfile.gettempdir()) / "video2x"
else:
video2x_cache_directory = pathlib.Path(config['video2x']['video2x_cache_directory'])
video2x_cache_directory = pathlib.Path(config["video2x"]["video2x_cache_directory"])
# overwrite driver_settings with driver_args
if driver_args is not None:
@@ -252,7 +324,6 @@ try:
driver_settings=driver_settings,
ffmpeg_settings=ffmpeg_settings,
gifski_settings=gifski_settings,
# optional parameters
driver=video2x_args.driver,
scale_ratio=video2x_args.ratio,
@@ -264,17 +335,21 @@ try:
output_file_name_format_string=output_file_name_format_string,
image_output_extension=image_output_extension,
video_output_extension=video_output_extension,
preserve_frames=preserve_frames
preserve_frames=preserve_frames,
)
# run upscaler
upscaler.run()
Avalon.info(_('Program completed, taking {} seconds').format(round((time.time() - begin_time), 5)))
Avalon.info(
_("Program completed, taking {} seconds").format(
round((time.time() - begin_time), 5)
)
)
except Exception:
Avalon.error(_('An exception has occurred'))
Avalon.error(_("An exception has occurred"))
traceback.print_exc()
if video2x_args.log is not None:
@@ -284,12 +359,12 @@ except Exception:
# tempfile.TempFile does not have a name attribute and is not guaranteed to have
# a visible name on the file system
else:
log_file_path = tempfile.mkstemp(suffix='.log', prefix='video2x_')[1]
with open(log_file_path, 'w', encoding='utf-8') as permanent_log_file:
log_file_path = tempfile.mkstemp(suffix=".log", prefix="video2x_")[1]
with open(log_file_path, "w", encoding="utf-8") as permanent_log_file:
log_file.seek(0)
permanent_log_file.write(log_file.read())
Avalon.error(_('The error log file can be found at: {}').format(log_file_path))
Avalon.error(_("The error log file can be found at: {}").format(log_file_path))
finally:
sys.stdout = original_stdout

View File

@@ -1,7 +1,7 @@
# Name: Video2X Configuration File
# Creator: K4YT3X
# Date Created: October 23, 2018
# Last Modified: September 13, 2020
# Last Modified: September 28, 2020
# Values here are the default values. Change the value here to
# save the default value permanently.
# Items commented out are parameters irrelevant to this context
@@ -32,7 +32,7 @@ waifu2x_converter_cpp:
#list-supported-formats: null # dump currently supported format list
#list-opencv-formats: null # (deprecated. Use --list-supported-formats) dump opencv supported format list
#list-processor # dump processor list
output-format: null # The format used when running in recursive/folder mode
#output-format: null # The format used when running in recursive/folder mode
png-compression: 5 # Set PNG compression level (0-9), 9 = Max compression (slowest & smallest)
image-quality: -1 # JPEG & WebP Compression quality (-1-101, 0 being smallest size and lowest quality, -1 being default), use 101 for lossless WebP
block-size: 0 # block size
@@ -55,15 +55,16 @@ waifu2x_converter_cpp:
waifu2x_ncnn_vulkan:
path: '%LOCALAPPDATA%\video2x\waifu2x-ncnn-vulkan\waifu2x-ncnn-vulkan'
v: null # verbose output
#i: null # input-path: input image path (jpg/png) or directory
#o: null # output-path: output image path (png) or directory
#i: null # input-path: input image path (jpg/png/webp) or directory
#o: null # output-path: output image path (jpg/png/webp) or directory
'n': 2 # noise-level: denoise level (-1/0/1/2/3, default=0)
s: 2 # scale: upscale ratio (1/2, default=2)
t: 400 # tile-size: tile size (>=32, default=400)
m: null # model-path: waifu2x model path (default=models-cunet)
g: 0 # gpu-id: gpu device to use (default=0)
j: '1:2:2' # thread count for load/proc/save (default=1:2:2)
j: '1:2:2' # thread count for load/proc/save (default=1:2:2) can be 1:2,2,2:2 for multi-gpu
x: false # enable tta mode
#f: png # output image format (jpg/png/webp, default=ext/png)
srmd_ncnn_vulkan:
path: '%LOCALAPPDATA%\video2x\srmd-ncnn-vulkan\srmd-ncnn-vulkan'
v: null # verbose output
@@ -76,6 +77,7 @@ srmd_ncnn_vulkan:
g: 0 # gpu device to use (default=0)
j: '1:2:2' # thread count for load/proc/save (default=1:2:2)
x: false # enable tta mode
#f: png # output image format (jpg/png/webp, default=ext/png)
realsr_ncnn_vulkan:
path: '%LOCALAPPDATA%\video2x\realsr-ncnn-vulkan\realsr-ncnn-vulkan'
v: null # verbose output
@@ -87,6 +89,7 @@ realsr_ncnn_vulkan:
g: 0 # gpu device to use (default=0)
j: '1:2:2' # thread count for load/proc/save (default=1:2:2)
x: false # enable tta mode
#f: png # output image format (jpg/png/webp, default=ext/png)
anime4kcpp:
path: '%LOCALAPPDATA%\video2x\anime4kcpp\CLI\Anime4KCPP_CLI\Anime4KCPP_CLI'
#input: null # File for loading (string [=./pic/p1.png])
@@ -117,7 +120,7 @@ anime4kcpp:
webVideo: null # process the video from URL
alpha: false # preserve the Alpha channel for transparent image
ffmpeg:
ffmpeg_path: '%LOCALAPPDATA%\video2x\ffmpeg-latest-win64-static\bin'
ffmpeg_path: '%LOCALAPPDATA%\video2x\ffmpeg\bin'
intermediate_file_name: 'intermediate.mkv'
# Step 1: Frame Extraction
# extract all frames from original input into temporary directory

File diff suppressed because it is too large Load Diff

View File

@@ -2289,6 +2289,11 @@
<string>ssim</string>
</property>
</item>
<item>
<property name="text">
<string>none</string>
</property>
</item>
</widget>
</item>
</layout>

View File

@@ -4,10 +4,11 @@
Name: Video2X Setup Script
Creator: K4YT3X
Date Created: November 28, 2018
Last Modified: May 30, 2020
Last Modified: December 13, 2020
Editor: BrianPetkovsek
Editor: SAT3LL
Editor: konqiDAM
Description: This script helps installing all dependencies of video2x
and generates a configuration for it.
@@ -44,33 +45,47 @@ import zipfile
# Therefore, they will be installed during the Python dependency
# installation step and imported later in the script.
SETUP_VERSION = '2.2.1'
SETUP_VERSION = "2.4.1"
# global static variables
LOCALAPPDATA = pathlib.Path(os.getenv('localappdata'))
DRIVER_OPTIONS = ['all',
'ffmpeg',
'gifski',
'waifu2x_caffe',
'waifu2x_converter_cpp',
'waifu2x_ncnn_vulkan',
'srmd_ncnn_vulkan',
'realsr_ncnn_vulkan',
'anime4kcpp']
LOCALAPPDATA = pathlib.Path(os.getenv("localappdata"))
DRIVER_OPTIONS = [
"all",
"ffmpeg",
"gifski",
"waifu2x_caffe",
"waifu2x_converter_cpp",
"waifu2x_ncnn_vulkan",
"srmd_ncnn_vulkan",
"realsr_ncnn_vulkan",
"anime4kcpp",
]
def parse_arguments():
""" parse command line arguments
"""
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-d', '--driver', help='driver to download and configure', choices=DRIVER_OPTIONS, default='all')
parser.add_argument('-u', '--uninstall', help='uninstall Video2X dependencies from default location', action='store_true')
"""parse command line arguments"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"-d",
"--driver",
help="driver to download and configure",
choices=DRIVER_OPTIONS,
default="all",
)
parser.add_argument(
"-u",
"--uninstall",
help="uninstall Video2X dependencies from default location",
action="store_true",
)
# parse arguments
return parser.parse_args()
class Video2xSetup:
""" install dependencies for video2x video enlarger
"""install dependencies for video2x video enlarger
This library is meant to be executed as a stand-alone
script. All files will be installed under %LOCALAPPDATA%\\video2x.
@@ -85,187 +100,232 @@ class Video2xSetup:
# regardless of which driver to install
# always ensure Python modules are installed and up-to-date
if self.download_python_modules:
print('\nInstalling Python libraries')
print("\nInstalling Python libraries")
self._install_python_requirements()
# if all drivers are to be installed
if self.driver == 'all':
DRIVER_OPTIONS.remove('all')
if self.driver == "all":
DRIVER_OPTIONS.remove("all")
for driver in DRIVER_OPTIONS:
getattr(self, f'_install_{driver}')()
getattr(self, f"_install_{driver}")()
# install only the selected driver
else:
getattr(self, f'_install_{self.driver}')()
getattr(self, f"_install_{self.driver}")()
print('\nCleaning up temporary files')
self._cleanup()
# self._cleanup()
def _install_python_requirements(self):
""" Read requirements.txt and return its content
"""
pip_install('requirements.txt')
"""Read requirements.txt and return its content"""
pip_install("requirements.txt")
def _cleanup(self):
""" Cleanup all the temp files downloaded
"""
"""Cleanup all the temp files downloaded"""
print("\nCleaning up temporary files")
for file in self.trash:
try:
if file.is_dir():
print(f'Deleting directory: {file}')
print(f"Deleting directory: {file}")
shutil.rmtree(file)
else:
print(f'Deleting file: {file}')
print(f"Deleting file: {file}")
file.unlink()
except Exception:
print(f'Error deleting: {file}')
print(f"Error deleting: {file}")
traceback.print_exc()
def _install_ffmpeg(self):
""" Install FFMPEG
"""
print('\nInstalling FFmpeg')
"""Install FFMPEG"""
print("\nInstalling FFmpeg")
latest_release = 'https://ffmpeg.zeranoe.com/builds/win64/static/ffmpeg-latest-win64-static.zip'
import patoolib
ffmpeg_zip = download(latest_release, tempfile.gettempdir())
self.trash.append(ffmpeg_zip)
latest_release = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full.7z"
with zipfile.ZipFile(ffmpeg_zip) as zipf:
zipf.extractall(LOCALAPPDATA / 'video2x')
ffmpeg_7z = download(latest_release, tempfile.gettempdir())
self.trash.append(ffmpeg_7z)
# if running in PyInstaller, add sys._MEIPASS\7z to path
# this directory contains 7za.exe and its DLL files
with contextlib.suppress(AttributeError):
os.environ["PATH"] += f";{sys._MEIPASS}\\7z"
ffmpeg_directory = LOCALAPPDATA / "video2x" / "ffmpeg"
# (ffmpeg_directory).mkdir(parents=True, exist_ok=True)
# pyunpack.Archive(ffmpeg_7z).extractall(ffmpeg_directory)
if (ffmpeg_directory).exists():
shutil.rmtree(ffmpeg_directory)
patoolib.extract_archive(str(ffmpeg_7z), outdir=str(LOCALAPPDATA / "video2x"))
(LOCALAPPDATA / "video2x" / ffmpeg_7z.stem).rename(ffmpeg_directory)
def _install_gifski(self):
print('\nInstalling Gifski')
print("\nInstalling Gifski")
import requests
# Get latest release of Gifski via Github API
latest_release = requests.get('https://api.github.com/repos/ImageOptim/gifski/releases/latest').json()
releases = requests.get(
"https://api.github.com/repos/ImageOptim/gifski/releases"
).json()
for release in releases:
for asset in release["assets"]:
if re.search(r"gifski-.*\.tar\.xz", asset["browser_download_url"]):
gifski_tar_xz = download(
asset["browser_download_url"], tempfile.gettempdir()
)
self.trash.append(gifski_tar_xz)
for a in latest_release['assets']:
if re.search(r'gifski-.*\.tar\.xz', a['browser_download_url']):
gifski_tar_gz = download(a['browser_download_url'], tempfile.gettempdir())
self.trash.append(gifski_tar_gz)
# extract and rename
with tarfile.open(gifski_tar_xz) as archive:
archive.extractall(LOCALAPPDATA / "video2x" / "gifski")
# extract and rename
with tarfile.open(gifski_tar_gz) as archive:
archive.extractall(LOCALAPPDATA / 'video2x' / 'gifski')
return
def _install_waifu2x_caffe(self):
""" Install waifu2x_caffe
"""
print('\nInstalling waifu2x-caffe')
"""Install waifu2x_caffe"""
print("\nInstalling waifu2x-caffe")
import requests
# Get latest release of waifu2x-caffe via GitHub API
latest_release = requests.get('https://api.github.com/repos/lltcggie/waifu2x-caffe/releases/latest').json()
latest_release = requests.get(
"https://api.github.com/repos/lltcggie/waifu2x-caffe/releases/latest"
).json()
for a in latest_release['assets']:
if 'waifu2x-caffe.zip' in a['browser_download_url']:
waifu2x_caffe_zip = download(a['browser_download_url'], tempfile.gettempdir())
for a in latest_release["assets"]:
if "waifu2x-caffe.zip" in a["browser_download_url"]:
waifu2x_caffe_zip = download(
a["browser_download_url"], tempfile.gettempdir()
)
self.trash.append(waifu2x_caffe_zip)
with zipfile.ZipFile(waifu2x_caffe_zip) as zipf:
zipf.extractall(LOCALAPPDATA / 'video2x')
zipf.extractall(LOCALAPPDATA / "video2x")
def _install_waifu2x_converter_cpp(self):
""" Install waifu2x_caffe
"""
print('\nInstalling waifu2x-converter-cpp')
"""Install waifu2x_caffe"""
print("\nInstalling waifu2x-converter-cpp")
import requests
# Get latest release of waifu2x-caffe via GitHub API
latest_release = requests.get('https://api.github.com/repos/DeadSix27/waifu2x-converter-cpp/releases/latest').json()
latest_release = requests.get(
"https://api.github.com/repos/DeadSix27/waifu2x-converter-cpp/releases/latest"
).json()
for a in latest_release['assets']:
if re.search(r'waifu2x-DeadSix27-win64_v[0-9]*\.zip', a['browser_download_url']):
waifu2x_converter_cpp_zip = download(a['browser_download_url'], tempfile.gettempdir())
for a in latest_release["assets"]:
if re.search(
r"waifu2x-DeadSix27-win64_v[0-9]*\.zip", a["browser_download_url"]
):
waifu2x_converter_cpp_zip = download(
a["browser_download_url"], tempfile.gettempdir()
)
self.trash.append(waifu2x_converter_cpp_zip)
with zipfile.ZipFile(waifu2x_converter_cpp_zip) as zipf:
zipf.extractall(LOCALAPPDATA / 'video2x' / 'waifu2x-converter-cpp')
zipf.extractall(LOCALAPPDATA / "video2x" / "waifu2x-converter-cpp")
def _install_waifu2x_ncnn_vulkan(self):
""" Install waifu2x-ncnn-vulkan
"""
print('\nInstalling waifu2x-ncnn-vulkan')
"""Install waifu2x-ncnn-vulkan"""
print("\nInstalling waifu2x-ncnn-vulkan")
import requests
# Get latest release of waifu2x-ncnn-vulkan via Github API
latest_release = requests.get('https://api.github.com/repos/nihui/waifu2x-ncnn-vulkan/releases/latest').json()
latest_release = requests.get(
"https://api.github.com/repos/nihui/waifu2x-ncnn-vulkan/releases/latest"
).json()
for a in latest_release['assets']:
if re.search(r'waifu2x-ncnn-vulkan-\d*-windows\.zip', a['browser_download_url']):
waifu2x_ncnn_vulkan_zip = download(a['browser_download_url'], tempfile.gettempdir())
for a in latest_release["assets"]:
if re.search(
r"waifu2x-ncnn-vulkan-\d*-windows\.zip", a["browser_download_url"]
):
waifu2x_ncnn_vulkan_zip = download(
a["browser_download_url"], tempfile.gettempdir()
)
self.trash.append(waifu2x_ncnn_vulkan_zip)
# extract and rename
waifu2x_ncnn_vulkan_directory = LOCALAPPDATA / 'video2x' / 'waifu2x-ncnn-vulkan'
waifu2x_ncnn_vulkan_directory = LOCALAPPDATA / "video2x" / "waifu2x-ncnn-vulkan"
with zipfile.ZipFile(waifu2x_ncnn_vulkan_zip) as zipf:
zipf.extractall(LOCALAPPDATA / 'video2x')
zipf.extractall(LOCALAPPDATA / "video2x")
# if directory already exists, remove it
if waifu2x_ncnn_vulkan_directory.exists():
shutil.rmtree(waifu2x_ncnn_vulkan_directory)
# rename the newly extracted directory
(LOCALAPPDATA / 'video2x' / zipf.namelist()[0]).rename(waifu2x_ncnn_vulkan_directory)
(LOCALAPPDATA / "video2x" / zipf.namelist()[0]).rename(
waifu2x_ncnn_vulkan_directory
)
def _install_srmd_ncnn_vulkan(self):
""" Install srmd-ncnn-vulkan
"""
print('\nInstalling srmd-ncnn-vulkan')
"""Install srmd-ncnn-vulkan"""
print("\nInstalling srmd-ncnn-vulkan")
import requests
# Get latest release of srmd-ncnn-vulkan via Github API
latest_release = requests.get('https://api.github.com/repos/nihui/srmd-ncnn-vulkan/releases/latest').json()
latest_release = requests.get(
"https://api.github.com/repos/nihui/srmd-ncnn-vulkan/releases/latest"
).json()
for a in latest_release['assets']:
if re.search(r'srmd-ncnn-vulkan-\d*-windows\.zip', a['browser_download_url']):
srmd_ncnn_vulkan_zip = download(a['browser_download_url'], tempfile.gettempdir())
for a in latest_release["assets"]:
if re.search(
r"srmd-ncnn-vulkan-\d*-windows\.zip", a["browser_download_url"]
):
srmd_ncnn_vulkan_zip = download(
a["browser_download_url"], tempfile.gettempdir()
)
self.trash.append(srmd_ncnn_vulkan_zip)
# extract and rename
srmd_ncnn_vulkan_directory = LOCALAPPDATA / 'video2x' / 'srmd-ncnn-vulkan'
srmd_ncnn_vulkan_directory = LOCALAPPDATA / "video2x" / "srmd-ncnn-vulkan"
with zipfile.ZipFile(srmd_ncnn_vulkan_zip) as zipf:
zipf.extractall(LOCALAPPDATA / 'video2x')
zipf.extractall(LOCALAPPDATA / "video2x")
# if directory already exists, remove it
if srmd_ncnn_vulkan_directory.exists():
shutil.rmtree(srmd_ncnn_vulkan_directory)
# rename the newly extracted directory
(LOCALAPPDATA / 'video2x' / zipf.namelist()[0]).rename(srmd_ncnn_vulkan_directory)
(LOCALAPPDATA / "video2x" / zipf.namelist()[0]).rename(
srmd_ncnn_vulkan_directory
)
def _install_realsr_ncnn_vulkan(self):
""" Install realsr-ncnn-vulkan
"""
print('\nInstalling realsr-ncnn-vulkan')
"""Install realsr-ncnn-vulkan"""
print("\nInstalling realsr-ncnn-vulkan")
import requests
# Get latest release of realsr-ncnn-vulkan via Github API
latest_release = requests.get('https://api.github.com/repos/nihui/realsr-ncnn-vulkan/releases/latest').json()
latest_release = requests.get(
"https://api.github.com/repos/nihui/realsr-ncnn-vulkan/releases/latest"
).json()
for a in latest_release['assets']:
if re.search(r'realsr-ncnn-vulkan-\d*-windows\.zip', a['browser_download_url']):
realsr_ncnn_vulkan_zip = download(a['browser_download_url'], tempfile.gettempdir())
for a in latest_release["assets"]:
if re.search(
r"realsr-ncnn-vulkan-\d*-windows\.zip", a["browser_download_url"]
):
realsr_ncnn_vulkan_zip = download(
a["browser_download_url"], tempfile.gettempdir()
)
self.trash.append(realsr_ncnn_vulkan_zip)
# extract and rename
realsr_ncnn_vulkan_directory = LOCALAPPDATA / 'video2x' / 'realsr-ncnn-vulkan'
realsr_ncnn_vulkan_directory = LOCALAPPDATA / "video2x" / "realsr-ncnn-vulkan"
with zipfile.ZipFile(realsr_ncnn_vulkan_zip) as zipf:
zipf.extractall(LOCALAPPDATA / 'video2x')
zipf.extractall(LOCALAPPDATA / "video2x")
# if directory already exists, remove it
if realsr_ncnn_vulkan_directory.exists():
shutil.rmtree(realsr_ncnn_vulkan_directory)
# rename the newly extracted directory
(LOCALAPPDATA / 'video2x' / zipf.namelist()[0]).rename(realsr_ncnn_vulkan_directory)
(LOCALAPPDATA / "video2x" / zipf.namelist()[0]).rename(
realsr_ncnn_vulkan_directory
)
def _install_anime4kcpp(self):
""" Install Anime4KCPP
"""
print('\nInstalling Anime4KCPP')
"""Install Anime4KCPP"""
print("\nInstalling Anime4KCPP")
import patoolib
import requests
@@ -273,28 +333,35 @@ class Video2xSetup:
# get latest release of Anime4KCPP via Github API
# at the time of writing this portion, Anime4KCPP doesn't yet have a stable release
# therefore releases/latest won't work
latest_release = requests.get('https://api.github.com/repos/TianZerL/Anime4KCPP/releases/latest').json()
latest_release = requests.get(
"https://api.github.com/repos/TianZerL/Anime4KCPP/releases/latest"
).json()
for a in latest_release['assets']:
if re.search(r'Anime4KCPP_CLI-.*-Win64-msvc\.7z', a['browser_download_url']):
anime4kcpp_7z = download(a['browser_download_url'], tempfile.gettempdir())
for a in latest_release["assets"]:
if re.search(
r"Anime4KCPP_CLI-.*-Win64-msvc\.7z", a["browser_download_url"]
):
anime4kcpp_7z = download(
a["browser_download_url"], tempfile.gettempdir()
)
self.trash.append(anime4kcpp_7z)
# if running in PyInstaller, add sys._MEIPASS\7z to path
# this directory contains 7za.exe and its DLL files
with contextlib.suppress(AttributeError):
os.environ['PATH'] += f';{sys._MEIPASS}\\7z'
os.environ["PATH"] += f";{sys._MEIPASS}\\7z"
# (LOCALAPPDATA / 'video2x' / 'anime4kcpp').mkdir(parents=True, exist_ok=True)
# pyunpack.Archive(anime4kcpp_7z).extractall(LOCALAPPDATA / 'video2x' / 'anime4kcpp')
if (LOCALAPPDATA / 'video2x' / 'anime4kcpp').exists():
shutil.rmtree(LOCALAPPDATA / 'video2x' / 'anime4kcpp')
patoolib.extract_archive(str(anime4kcpp_7z), outdir=str(LOCALAPPDATA / 'video2x' / 'anime4kcpp'))
if (LOCALAPPDATA / "video2x" / "anime4kcpp").exists():
shutil.rmtree(LOCALAPPDATA / "video2x" / "anime4kcpp")
patoolib.extract_archive(
str(anime4kcpp_7z), outdir=str(LOCALAPPDATA / "video2x" / "anime4kcpp")
)
def download(url, save_path, chunk_size=4096):
""" Download file to local with requests library
"""
"""Download file to local with requests library"""
from tqdm import tqdm
import requests
@@ -308,14 +375,14 @@ def download(url, save_path, chunk_size=4096):
# get file name
file_name = None
if 'content-disposition' in stream.headers:
disposition = stream.headers['content-disposition']
if "content-disposition" in stream.headers:
disposition = stream.headers["content-disposition"]
with contextlib.suppress(IndexError):
file_name = re.findall("filename=(.+)", disposition)[0].strip('"')
if file_name is None:
# output_file = f'{save_path}\\{stream.url.split("/")[-1]}'
output_file = save_path / stream.url.split('/')[-1]
output_file = save_path / stream.url.split("/")[-1]
else:
output_file = save_path / file_name
@@ -324,17 +391,17 @@ def download(url, save_path, chunk_size=4096):
# get total size for progress bar if provided in headers
total_size = 0
if 'content-length' in stream.headers:
total_size = int(stream.headers['content-length'])
if "content-length" in stream.headers:
total_size = int(stream.headers["content-length"])
# print download information summary
print(f'Downloading: {url}')
print(f'Total size: {total_size}')
print(f'Chunk size: {chunk_size}')
print(f'Saving to: {output_file}')
print(f"Downloading: {url}")
print(f"Total size: {total_size}")
print(f"Chunk size: {chunk_size}")
print(f"Saving to: {output_file}")
# Write content into file
with open(output_file, 'wb') as output:
with open(output_file, "wb") as output:
with tqdm(total=total_size, ascii=True) as progress_bar:
for chunk in stream.iter_content(chunk_size=chunk_size):
if chunk:
@@ -346,16 +413,18 @@ def download(url, save_path, chunk_size=4096):
def pip_install(file):
""" Install python package via python pip module
"""Install python package via python pip module
pip.main() is not available after pip 9.0.1, thus
pip module is not used in this case.
"""
return subprocess.run([sys.executable, '-m', 'pip', 'install', '-U', '-r', file]).returncode
return subprocess.run(
[sys.executable, "-m", "pip", "install", "-U", "-r", file]
).returncode
if __name__ != '__main__':
raise ImportError('video2x_setup cannot be imported')
if __name__ != "__main__":
raise ImportError("video2x_setup cannot be imported")
try:
# set default exit code
@@ -365,42 +434,47 @@ try:
start_time = time.time()
# check platform
if platform.system() != 'Windows':
print('This script is currently only compatible with Windows')
if platform.system() != "Windows":
print("This script is currently only compatible with Windows")
EXIT_CODE = 1
sys.exit(1)
# parse command line arguments
args = parse_arguments()
print('Video2X Setup Script')
print(f'Version: {SETUP_VERSION}')
print("Video2X Setup Script")
print(f"Version: {SETUP_VERSION}")
# uninstall video2x dependencies
if args.uninstall:
if input('Are you sure you want to uninstall all Video2X dependencies? [y/N]: ').lower() == 'y':
if (
input(
"Are you sure you want to uninstall all Video2X dependencies? [y/N]: "
).lower()
== "y"
):
try:
print(f'Removing: {LOCALAPPDATA / "video2x"}')
shutil.rmtree(LOCALAPPDATA / 'video2x')
print('Successfully uninstalled all dependencies')
shutil.rmtree(LOCALAPPDATA / "video2x")
print("Successfully uninstalled all dependencies")
except FileNotFoundError:
print(f'Dependency folder does not exist: {LOCALAPPDATA / "video2x"}')
else:
print('Uninstallation aborted')
print("Uninstallation aborted")
# run installation
else:
# do not install pip modules if script
# is packaged in exe format
download_python_modules = True
if sys.argv[0].endswith('.exe'):
print('\nScript is packaged as exe, skipping pip module download')
if sys.argv[0].endswith(".exe"):
print("\nScript is packaged as exe, skipping pip module download")
download_python_modules = False
# create setup install instance and run installer
setup = Video2xSetup(args.driver, download_python_modules)
setup.run()
print('\nScript finished successfully')
print("\nScript finished successfully")
# let SystemExit signals pass through
except SystemExit as e:
@@ -410,35 +484,35 @@ except SystemExit as e:
# user needs to run this with higher privilege
except PermissionError:
traceback.print_exc()
print('You might have insufficient privilege for this script to run')
print('Try running this script with Administrator privileges')
print("You might have insufficient privilege for this script to run")
print("Try running this script with Administrator privileges")
EXIT_CODE = 1
# for any exception in the script
except Exception:
traceback.print_exc()
print('An error has occurred')
print('Video2X Automatic Setup has failed')
# in case of a failure, try cleaning up temp files
try:
setup._cleanup()
except Exception:
traceback.print_exc()
print('An error occurred while trying to cleanup files')
print("An error has occurred")
print("Video2X Automatic Setup has failed")
EXIT_CODE = 1
# regardless if script finishes successfully or not
# print script execution summary
finally:
print('Script finished')
print(f'Time taken: {timedelta(seconds=round(time.time() - start_time))}')
# always try cleaning up trash
try:
setup._cleanup()
except Exception:
traceback.print_exc()
print("An error occurred while trying to cleanup files")
print("Script finished")
print(f"Time taken: {timedelta(seconds=round(time.time() - start_time))}")
# if the program is launched as an Windows PE file
# it might be launched from double clicking
# pause the window before it closes automatically
if sys.argv[0].endswith('.exe'):
input('Press [ENTER] to exit script')
if sys.argv[0].endswith(".exe"):
input("Press [ENTER] to exit script")
sys.exit(EXIT_CODE)

View File

@@ -187,15 +187,15 @@ mv -v $TEMP/realsr-ncnn-vulkan/realsr-ncnn-vulkan-*-linux $INSTALLATION_PATH/vid
# install Anime4KCPP
# install the latest cmake for compiling Anime4KCPP
aria2c https://github.com/Kitware/CMake/releases/download/v3.18.2/cmake-3.18.2-Linux-x86_64.sh --dir / -o "$TEMP/cmake.sh"
mkdir /cmake
bash "$TEMP/cmake.sh" --prefix=/cmake --skip-license
mkdir $TEMP/cmake
bash "$TEMP/cmake.sh" --prefix=$TEMP/cmake --skip-license
# build and install Anime4KCPP
apt-fast install -y --no-install-recommends libopencv-dev opencl-dev
git clone --recurse-submodules --depth=1 --progress https://github.com/TianZerL/Anime4KCPP.git $TEMP/anime4kcpp
mkdir -v $TEMP/anime4kcpp/build
cd $TEMP/anime4kcpp/build
/cmake/bin/cmake -DBuild_GUI=OFF ..
$TEMP/cmake/bin/cmake -DBuild_GUI=OFF ..
make -j$(nproc)
mv -v $TEMP/anime4kcpp/build $INSTALLATION_PATH/video2x/src/dependencies/anime4kcpp
ln -s $INSTALLATION_PATH/video2x/src/dependencies/anime4kcpp/bin/libAnime4KCPPCore.so /usr/lib

View File

@@ -4,7 +4,10 @@
Name: Anime4KCPP Driver
Author: K4YT3X
Date Created: May 3, 2020
Last Modified: September 9, 2020
Last Modified: December 15, 2020
Editor: fire0shadow
Last Modified: December 15, 2020
Description: This class is a high-level wrapper
for Anime4KCPP.
@@ -16,6 +19,7 @@ import os
import pathlib
import platform
import subprocess
import sys
import threading
# third-party imports
@@ -23,8 +27,7 @@ from avalon_framework import Avalon
class WrapperMain:
""" Anime4K CPP wrapper
"""
"""Anime4K CPP wrapper"""
def __init__(self, driver_settings):
self.driver_settings = driver_settings
@@ -34,53 +37,55 @@ class WrapperMain:
def zero_to_one_float(value):
value = float(value)
if value < 0.0 or value > 1.0:
raise argparse.ArgumentTypeError(f'{value} is not between 0.0 and 1.0')
raise argparse.ArgumentTypeError(f"{value} is not between 0.0 and 1.0")
return value
@staticmethod
def parse_arguments(arguments):
# fmt: off
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
parser.error = lambda message: (_ for _ in ()).throw(AttributeError(message))
parser.add_argument('--help', action='help', help='show this help message and exit')
parser.add_argument('-i', '--input', type=str, help=argparse.SUPPRESS) # help='File for loading')
parser.add_argument('-o', '--output', type=str, help=argparse.SUPPRESS) # help='File for outputting')
parser.add_argument('-p', '--passes', type=int, help='Passes for processing')
parser.add_argument('-n', '--pushColorCount', type=int, help='Limit the number of color pushes')
parser.add_argument('-c', '--strengthColor', type=WrapperMain.zero_to_one_float, help='Strength for pushing color,range 0 to 1,higher for thinner')
parser.add_argument('-g', '--strengthGradient', type=WrapperMain.zero_to_one_float, help='Strength for pushing gradient,range 0 to 1,higher for sharper')
parser.add_argument('-z', '--zoomFactor', type=float, help='zoom factor for resizing')
parser.add_argument('-t', '--threads', type=int, help='Threads count for video processing')
parser.add_argument('-f', '--fastMode', action='store_true', help='Faster but maybe low quality')
parser.add_argument('-v', '--videoMode', action='store_true', help='Video process')
parser.add_argument('-s', '--preview', action='store_true', help='Preview image')
parser.add_argument('-b', '--preprocessing', action='store_true', help='Enable pre processing')
parser.add_argument('-a', '--postprocessing', action='store_true', help='Enable post processing')
parser.add_argument('-r', '--preFilters', type=int, help='Enhancement filter, only working when preProcessing is true,there are 5 options by binary:Median blur=0000001, Mean blur=0000010, CAS Sharpening=0000100, Gaussian blur weak=0001000, Gaussian blur=0010000, Bilateral filter=0100000, Bilateral filter faster=1000000, you can freely combine them, eg: Gaussian blur weak + Bilateral filter = 0001000 | 0100000 = 0101000 = 40(D)')
parser.add_argument('-e', '--postFilters', type=int, help='Enhancement filter, only working when postProcessing is true,there are 5 options by binary:Median blur=0000001, Mean blur=0000010, CAS Sharpening=0000100, Gaussian blur weak=0001000, Gaussian blur=0010000, Bilateral filter=0100000, Bilateral filter faster=1000000, you can freely combine them, eg: Gaussian blur weak + Bilateral filter = 0001000 | 0100000 = 0101000 = 40(D), so you can put 40 to enable Gaussian blur weak and Bilateral filter, which also is what I recommend for image that < 1080P, 48 for image that >= 1080P, and for performance I recommend to use 72 for video that < 1080P, 80 for video that >=1080P')
parser.add_argument('-q', '--GPUMode', action='store_true', help='Enable GPU acceleration')
parser.add_argument('-w', '--CNNMode', action='store_true', help='Enable ACNet')
parser.add_argument('-H', '--HDN', action='store_true', help='Enable HDN mode for ACNet')
parser.add_argument('-L', '--HDNLevel', type=int, help='Set HDN level')
parser.add_argument('-l', '--listGPUs', action='store_true', help='list GPUs')
parser.add_argument('-h', '--platformID', type=int, help='Specify the platform ID')
parser.add_argument('-d', '--deviceID', type=int, help='Specify the device ID')
parser.add_argument('-C', '--codec', type=str, help='Specify the codec for encoding from mp4v(recommended in Windows), dxva(for Windows), avc1(H264, recommended in Linux), vp09(very slow), hevc(not support in Windowds), av01(not support in Windowds) (string [=mp4v])')
parser.add_argument('-F', '--forceFps', type=float, help='Set output video fps to the specifying number, 0 to disable')
parser.add_argument('-D', '--disableProgress', action='store_true', help='disable progress display')
parser.add_argument('-W', '--webVideo', type=str, help='process the video from URL')
parser.add_argument('-A', '--alpha', action='store_true', help='preserve the Alpha channel for transparent image')
parser.add_argument("--help", action="help", help="show this help message and exit")
parser.add_argument("-i", "--input", type=str, help=argparse.SUPPRESS) # help="File for loading")
parser.add_argument("-o", "--output", type=str, help=argparse.SUPPRESS) # help="File for outputting")
parser.add_argument("-p", "--passes", type=int, help="Passes for processing")
parser.add_argument("-n", "--pushColorCount", type=int, help="Limit the number of color pushes")
parser.add_argument("-c", "--strengthColor", type=WrapperMain.zero_to_one_float, help="Strength for pushing color,range 0 to 1,higher for thinner")
parser.add_argument("-g", "--strengthGradient", type=WrapperMain.zero_to_one_float, help="Strength for pushing gradient,range 0 to 1,higher for sharper")
parser.add_argument("-z", "--zoomFactor", type=float, help="zoom factor for resizing")
parser.add_argument("-t", "--threads", type=int, help="Threads count for video processing")
parser.add_argument("-f", "--fastMode", action="store_true", help="Faster but maybe low quality")
parser.add_argument("-v", "--videoMode", action="store_true", help="Video process")
parser.add_argument("-s", "--preview", action="store_true", help="Preview image")
parser.add_argument("-b", "--preprocessing", action="store_true", help="Enable pre processing")
parser.add_argument("-a", "--postprocessing", action="store_true", help="Enable post processing")
parser.add_argument("-r", "--preFilters", type=int, help="Enhancement filter, only working when preProcessing is true,there are 5 options by binary:Median blur=0000001, Mean blur=0000010, CAS Sharpening=0000100, Gaussian blur weak=0001000, Gaussian blur=0010000, Bilateral filter=0100000, Bilateral filter faster=1000000, you can freely combine them, eg: Gaussian blur weak + Bilateral filter = 0001000 | 0100000 = 0101000 = 40(D)")
parser.add_argument("-e", "--postFilters", type=int, help="Enhancement filter, only working when postProcessing is true,there are 5 options by binary:Median blur=0000001, Mean blur=0000010, CAS Sharpening=0000100, Gaussian blur weak=0001000, Gaussian blur=0010000, Bilateral filter=0100000, Bilateral filter faster=1000000, you can freely combine them, eg: Gaussian blur weak + Bilateral filter = 0001000 | 0100000 = 0101000 = 40(D), so you can put 40 to enable Gaussian blur weak and Bilateral filter, which also is what I recommend for image that < 1080P, 48 for image that >= 1080P, and for performance I recommend to use 72 for video that < 1080P, 80 for video that >=1080P")
parser.add_argument("-q", "--GPUMode", action="store_true", help="Enable GPU acceleration")
parser.add_argument("-w", "--CNNMode", action="store_true", help="Enable ACNet")
parser.add_argument("-H", "--HDN", action="store_true", help="Enable HDN mode for ACNet")
parser.add_argument("-L", "--HDNLevel", type=int, help="Set HDN level")
parser.add_argument("-l", "--listGPUs", action="store_true", help="list GPUs")
parser.add_argument("-h", "--platformID", type=int, help="Specify the platform ID")
parser.add_argument("-d", "--deviceID", type=int, help="Specify the device ID")
parser.add_argument("-C", "--codec", type=str, help="Specify the codec for encoding from mp4v(recommended in Windows), dxva(for Windows), avc1(H264, recommended in Linux), vp09(very slow), hevc(not support in Windowds), av01(not support in Windowds) (string [=mp4v])")
parser.add_argument("-F", "--forceFps", type=float, help="Set output video fps to the specifying number, 0 to disable")
parser.add_argument("-D", "--disableProgress", action="store_true", help="disable progress display")
parser.add_argument("-W", "--webVideo", type=str, help="process the video from URL")
parser.add_argument("-A", "--alpha", action="store_true", help="preserve the Alpha channel for transparent image")
return parser.parse_args(arguments)
# fmt: on
def load_configurations(self, upscaler):
# self.driver_settings['zoomFactor'] = upscaler.scale_ratio
self.driver_settings['threads'] = upscaler.processes
self.driver_settings["threads"] = upscaler.processes
# append FFmpeg path to the end of PATH
# Anime4KCPP will then use FFmpeg to migrate audio tracks
os.environ['PATH'] += f';{upscaler.ffmpeg_settings["ffmpeg_path"]}'
os.environ["PATH"] += f';{upscaler.ffmpeg_settings["ffmpeg_path"]}'
def set_scale_ratio(self, scale_ratio: float):
self.driver_settings['zoomFactor'] = scale_ratio
self.driver_settings["zoomFactor"] = scale_ratio
def upscale(self, input_file, output_file):
"""This is the core function for WAIFU2X class
@@ -94,33 +99,33 @@ class WrapperMain:
# change the working directory to the binary's parent directory
# so the binary can find shared object files and other files
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# overwrite config file settings
self.driver_settings['input'] = input_file
self.driver_settings['output'] = output_file
self.driver_settings["input"] = input_file
self.driver_settings["output"] = output_file
# Anime4KCPP will look for Anime4KCPPKernel.cl under the current working directory
# change the CWD to its containing directory so it will find it
if platform.system() == 'Windows':
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
if platform.system() == "Windows":
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# list to be executed
# initialize the list with waifu2x binary path as the first element
execute = [self.driver_settings['path']]
execute = [self.driver_settings["path"]]
for key in self.driver_settings.keys():
value = self.driver_settings[key]
# null or None means that leave this option out (keep default)
if key == 'path' or value is None or value is False:
if key == "path" or value is None or value is False:
continue
else:
if len(key) == 1:
execute.append(f'-{key}')
execute.append(f"-{key}")
else:
execute.append(f'--{key}')
execute.append(f"--{key}")
# true means key is an option
if value is not True:
@@ -128,6 +133,8 @@ class WrapperMain:
# return the Popen object of the new process created
self.print_lock.acquire()
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}')
Avalon.debug_info(
f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}'
)
self.print_lock.release()
return subprocess.Popen(execute)
return subprocess.Popen(execute, stdout=sys.stdout, stderr=sys.stderr)

View File

@@ -13,6 +13,7 @@ Description: This class handles all FFmpeg related operations.
import json
import pathlib
import subprocess
import sys
# third-party imports
from avalon_framework import Avalon
@@ -26,20 +27,24 @@ class Ffmpeg:
and inserting audio tracks to videos.
"""
def __init__(self, ffmpeg_settings, extracted_frame_format='png'):
def __init__(self, ffmpeg_settings, extracted_frame_format="png"):
self.ffmpeg_settings = ffmpeg_settings
self.ffmpeg_path = pathlib.Path(self.ffmpeg_settings['ffmpeg_path'])
self.ffmpeg_binary = self.ffmpeg_path / 'ffmpeg'
self.ffmpeg_probe_binary = self.ffmpeg_path / 'ffprobe'
self.ffmpeg_path = pathlib.Path(self.ffmpeg_settings["ffmpeg_path"])
self.ffmpeg_binary = self.ffmpeg_path / "ffmpeg"
self.ffmpeg_probe_binary = self.ffmpeg_path / "ffprobe"
# video metadata
self.extracted_frame_format = extracted_frame_format
self.intermediate_file_name = pathlib.Path(self.ffmpeg_settings['intermediate_file_name'])
self.pixel_format = self.ffmpeg_settings['extract_frames']['output_options']['-pix_fmt']
self.intermediate_file_name = pathlib.Path(
self.ffmpeg_settings["intermediate_file_name"]
)
self.pixel_format = self.ffmpeg_settings["extract_frames"]["output_options"][
"-pix_fmt"
]
def get_pixel_formats(self):
""" Get a dictionary of supported pixel formats
"""Get a dictionary of supported pixel formats
List all supported pixel formats and their
corresponding bit depth.
@@ -47,12 +52,7 @@ class Ffmpeg:
Returns:
dictionary -- JSON dict of all pixel formats to bit depth
"""
execute = [
self.ffmpeg_probe_binary,
'-v',
'quiet',
'-pix_fmts'
]
execute = [self.ffmpeg_probe_binary, "-v", "quiet", "-pix_fmts"]
# turn elements into str
execute = [str(e) for e in execute]
@@ -63,9 +63,15 @@ class Ffmpeg:
pixel_formats = {}
# record all pixel formats into dictionary
for line in subprocess.run(execute, check=True, stdout=subprocess.PIPE).stdout.decode().split('\n'):
for line in (
subprocess.run(execute, check=True, stdout=subprocess.PIPE)
.stdout.decode()
.split("\n")
):
try:
pixel_formats[" ".join(line.split()).split()[1]] = int(" ".join(line.split()).split()[3])
pixel_formats[" ".join(line.split()).split()[1]] = int(
" ".join(line.split()).split()[3]
)
except (IndexError, ValueError):
pass
@@ -75,7 +81,7 @@ class Ffmpeg:
return pixel_formats
def get_number_of_frames(self, input_file: str, video_stream_index: int) -> int:
""" Count the number of frames in a video
"""Count the number of frames in a video
Args:
input_file (str): input file path
@@ -87,26 +93,30 @@ class Ffmpeg:
execute = [
self.ffmpeg_probe_binary,
'-v',
'quiet',
'-count_frames',
'-select_streams',
f'v:{video_stream_index}',
'-show_entries',
'stream=nb_read_frames',
'-of',
'default=nokey=1:noprint_wrappers=1',
input_file
"-v",
"quiet",
"-count_frames",
"-select_streams",
f"v:{video_stream_index}",
"-show_entries",
"stream=nb_read_frames",
"-of",
"default=nokey=1:noprint_wrappers=1",
input_file,
]
# turn elements into str
execute = [str(e) for e in execute]
Avalon.debug_info(f'Executing: {" ".join(execute)}')
return int(subprocess.run(execute, check=True, stdout=subprocess.PIPE).stdout.decode().strip())
return int(
subprocess.run(execute, check=True, stdout=subprocess.PIPE)
.stdout.decode()
.strip()
)
def probe_file_info(self, input_video):
""" Gets input video information
"""Gets input video information
This method reads input video information
using ffprobe in dictionary
@@ -122,14 +132,14 @@ class Ffmpeg:
# since video2x only strictly recignizes this one format
execute = [
self.ffmpeg_probe_binary,
'-v',
'quiet',
'-print_format',
'json',
'-show_format',
'-show_streams',
'-i',
input_video
"-v",
"quiet",
"-print_format",
"json",
"-show_format",
"-show_streams",
"-i",
input_video,
]
# turn elements into str
@@ -137,37 +147,38 @@ class Ffmpeg:
Avalon.debug_info(f'Executing: {" ".join(execute)}')
json_str = subprocess.run(execute, check=True, stdout=subprocess.PIPE).stdout
return json.loads(json_str.decode('utf-8'))
return json.loads(json_str.decode("utf-8"))
def extract_frames(self, input_file, extracted_frames):
""" extract frames from video or GIF file
"""
execute = [
self.ffmpeg_binary
]
"""extract frames from video or GIF file"""
execute = [self.ffmpeg_binary]
# load general options
execute.extend(self._read_configuration(phase='extract_frames'))
execute.extend(self._read_configuration(phase="extract_frames"))
# load input_options
execute.extend(self._read_configuration(phase='extract_frames', section='input_options'))
execute.extend(
self._read_configuration(phase="extract_frames", section="input_options")
)
# specify input file
execute.extend([
'-i',
input_file
])
execute.extend(["-i", input_file])
# load output options
execute.extend(self._read_configuration(phase='extract_frames', section='output_options'))
execute.extend(
self._read_configuration(phase="extract_frames", section="output_options")
)
# specify output file
execute.extend([
extracted_frames / f'extracted_%0d.{self.extracted_frame_format}'
# extracted_frames / f'frame_%06d.{self.extracted_frame_format}'
])
execute.extend(
[
extracted_frames
/ f"extracted_%0d.{self.extracted_frame_format}"
# extracted_frames / f'frame_%06d.{self.extracted_frame_format}'
]
)
return(self._execute(execute))
return self._execute(execute)
def assemble_video(self, framerate, upscaled_frames):
"""Converts images into videos
@@ -181,86 +192,93 @@ class Ffmpeg:
"""
execute = [
self.ffmpeg_binary,
'-r',
"-r",
str(framerate)
# '-s',
# resolution
]
# read other options
execute.extend(self._read_configuration(phase='assemble_video'))
execute.extend(self._read_configuration(phase="assemble_video"))
# read input options
execute.extend(self._read_configuration(phase='assemble_video', section='input_options'))
execute.extend(
self._read_configuration(phase="assemble_video", section="input_options")
)
# WORKAROUND FOR WAIFU2X-NCNN-VULKAN
# Dev: SAT3LL
# rename all .png.png suffixes to .png
import re
regex = re.compile(r'\.png\.png$', re.IGNORECASE)
regex = re.compile(r"\.png\.png$", re.IGNORECASE)
for frame_name in upscaled_frames.iterdir():
(upscaled_frames / frame_name).rename(upscaled_frames / regex.sub('.png', str(frame_name)))
(upscaled_frames / frame_name).rename(
upscaled_frames / regex.sub(".png", str(frame_name))
)
# END WORKAROUND
# append input frames path into command
execute.extend([
'-i',
upscaled_frames / f'extracted_%d.{self.extracted_frame_format}'
# upscaled_frames / f'%06d.{self.extracted_frame_format}'
])
execute.extend(
[
"-i",
upscaled_frames / f"extracted_%d.{self.extracted_frame_format}"
# upscaled_frames / f'%06d.{self.extracted_frame_format}'
]
)
# read FFmpeg output options
execute.extend(self._read_configuration(phase='assemble_video', section='output_options'))
execute.extend(
self._read_configuration(phase="assemble_video", section="output_options")
)
# specify output file location
execute.extend([
upscaled_frames / self.intermediate_file_name
])
execute.extend([upscaled_frames / self.intermediate_file_name])
return(self._execute(execute))
return self._execute(execute)
def migrate_streams(self, input_video, output_video, upscaled_frames):
""" Migrates audio tracks and subtitles from input video to output video
"""Migrates audio tracks and subtitles from input video to output video
Arguments:
input_video {string} -- input video file path
output_video {string} -- output video file path
upscaled_frames {string} -- directory containing upscaled frames
"""
execute = [
self.ffmpeg_binary
]
execute = [self.ffmpeg_binary]
# load general options
execute.extend(self._read_configuration(phase='migrate_streams'))
execute.extend(self._read_configuration(phase="migrate_streams"))
# load input options
execute.extend(self._read_configuration(phase='migrate_streams', section='input_options'))
execute.extend(
self._read_configuration(phase="migrate_streams", section="input_options")
)
# load input file names
execute.extend([
# input 1: upscaled intermediate file without sound
'-i',
upscaled_frames / self.intermediate_file_name,
# input 2: original video with streams to copy over
'-i',
input_video
])
execute.extend(
[
# input 1: upscaled intermediate file without sound
"-i",
upscaled_frames / self.intermediate_file_name,
# input 2: original video with streams to copy over
"-i",
input_video,
]
)
# load output options
execute.extend(self._read_configuration(phase='migrate_streams', section='output_options'))
execute.extend(
self._read_configuration(phase="migrate_streams", section="output_options")
)
# load output video path
execute.extend([
output_video
])
execute.extend([output_video])
return(self._execute(execute))
return self._execute(execute)
def _read_configuration(self, phase, section=None):
""" read configuration from JSON
"""read configuration from JSON
Read the configurations (arguments) from the JSON
configuration file and append them to the end of the
@@ -289,7 +307,12 @@ class Ffmpeg:
value = self.ffmpeg_settings[phase][key]
# null or None means that leave this option out (keep default)
if value is None or value is False or isinstance(value, dict) or value == '':
if (
value is None
or value is False
or isinstance(value, dict)
or value == ""
):
continue
# if the value is a list, append the same argument and all values
@@ -316,4 +339,4 @@ class Ffmpeg:
# turn all list elements into string to avoid errors
execute = [str(e) for e in execute]
Avalon.debug_info(f'Executing: {" ".join(execute)}')
return subprocess.Popen(execute)
return subprocess.Popen(execute, stdout=sys.stdout, stderr=sys.stderr)

View File

@@ -12,36 +12,44 @@ Description: High-level wrapper for Gifski.
# built-in imports
import pathlib
import subprocess
import sys
# third-party imports
from avalon_framework import Avalon
class Gifski:
def __init__(self, gifski_settings):
self.gifski_settings = gifski_settings
def make_gif(self, upscaled_frames: pathlib.Path, output_path: pathlib.Path, framerate: float, extracted_frame_format: str, output_width: int, output_height: int) -> subprocess.Popen:
def make_gif(
self,
upscaled_frames: pathlib.Path,
output_path: pathlib.Path,
framerate: float,
extracted_frame_format: str,
output_width: int,
output_height: int,
) -> subprocess.Popen:
execute = [
self.gifski_settings['gifski_path'],
'-o',
self.gifski_settings["gifski_path"],
"-o",
output_path,
'--fps',
"--fps",
int(round(framerate, 0)),
'--width',
"--width",
output_width,
'--height',
output_height
"--height",
output_height,
]
# load configurations from config file
execute.extend(self._load_configuration())
# append frames location
execute.extend([upscaled_frames / f'extracted_*.{extracted_frame_format}'])
execute.extend([upscaled_frames / f"extracted_*.{extracted_frame_format}"])
return(self._execute(execute))
return self._execute(execute)
def _load_configuration(self):
@@ -52,13 +60,13 @@ class Gifski:
value = self.gifski_settings[key]
# null or None means that leave this option out (keep default)
if key == 'gifski_path' or value is None or value is False:
if key == "gifski_path" or value is None or value is False:
continue
else:
if len(key) == 1:
configuration.append(f'-{key}')
configuration.append(f"-{key}")
else:
configuration.append(f'--{key}')
configuration.append(f"--{key}")
# true means key is an option
if value is not True:
@@ -69,6 +77,6 @@ class Gifski:
# turn all list elements into string to avoid errors
execute = [str(e) for e in execute]
Avalon.debug_info(f'Executing: {execute}')
Avalon.debug_info(f"Executing: {execute}")
return subprocess.Popen(execute)
return subprocess.Popen(execute, stdout=sys.stdout, stderr=sys.stderr)

View File

@@ -4,7 +4,7 @@
Name: RealSR NCNN Vulkan Driver
Creator: K4YT3X
Date Created: May 26, 2020
Last Modified: September 9, 2020
Last Modified: September 21, 2020
Description: This class is a high-level wrapper
for realsr_ncnn_vulkan.
@@ -16,6 +16,7 @@ import os
import pathlib
import platform
import subprocess
import sys
import threading
# third-party imports
@@ -37,26 +38,32 @@ class WrapperMain:
@staticmethod
def parse_arguments(arguments):
# fmt: off
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
parser.error = lambda message: (_ for _ in ()).throw(AttributeError(message))
parser.add_argument('--help', action='help', help='show this help message and exit')
parser.add_argument('-v', action='store_true', help='verbose output')
parser.add_argument('-i', type=str, help=argparse.SUPPRESS) # help='input image path (jpg/png) or directory')
parser.add_argument('-o', type=str, help=argparse.SUPPRESS) # help='output image path (png) or directory')
parser.add_argument('-s', type=int, help='upscale ratio')
parser.add_argument('-t', type=int, help='tile size (>=32/0=auto)')
parser.add_argument('-m', type=str, help='realsr model path')
parser.add_argument('-g', type=int, help='gpu device to use')
parser.add_argument('-j', type=str, help='thread count for load/proc/save')
parser.add_argument('-x', action='store_true', help='enable tta mode')
parser.add_argument("--help", action="help", help="show this help message and exit")
parser.add_argument("-v", action="store_true", help="verbose output")
parser.add_argument("-i", type=str, help=argparse.SUPPRESS) # help="input image path (jpg/png) or directory")
parser.add_argument("-o", type=str, help=argparse.SUPPRESS) # help="output image path (png) or directory")
parser.add_argument("-s", type=int, help="upscale ratio")
parser.add_argument("-t", type=int, help="tile size (>=32/0=auto)")
parser.add_argument("-m", type=str, help="realsr model path")
parser.add_argument("-g", type=int, help="gpu device to use")
parser.add_argument("-j", type=str, help="thread count for load/proc/save")
parser.add_argument("-x", action="store_true", help="enable tta mode")
parser.add_argument("-f", type=str, help=argparse.SUPPRESS) # help="output image format (jpg/png/webp, default=ext/png)")
return parser.parse_args(arguments)
# fmt: on
def load_configurations(self, upscaler):
# self.driver_settings['s'] = int(upscaler.scale_ratio)
self.driver_settings['j'] = '{}:{}:{}'.format(upscaler.processes, upscaler.processes, upscaler.processes)
self.driver_settings["j"] = "{}:{}:{}".format(
upscaler.processes, upscaler.processes, upscaler.processes
)
self.driver_settings["f"] = upscaler.extracted_frame_format.lower()
def set_scale_ratio(self, scale_ratio: int):
self.driver_settings['s'] = int(scale_ratio)
self.driver_settings["s"] = int(scale_ratio)
def upscale(self, input_directory, output_directory):
"""This is the core function for RealSR NCNN Vulkan class
@@ -69,33 +76,33 @@ class WrapperMain:
# change the working directory to the binary's parent directory
# so the binary can find shared object files and other files
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# overwrite config file settings
self.driver_settings['i'] = input_directory
self.driver_settings['o'] = output_directory
self.driver_settings["i"] = input_directory
self.driver_settings["o"] = output_directory
# by default, realsr-ncnn-vulkan will look for the models under the current working directory
# change the working directory to its containing folder if model directory not specified
if self.driver_settings['m'] is None and platform.system() == 'Windows':
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
if self.driver_settings["m"] is None and platform.system() == "Windows":
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# list to be executed
# initialize the list with the binary path as the first element
execute = [self.driver_settings['path']]
execute = [self.driver_settings["path"]]
for key in self.driver_settings.keys():
value = self.driver_settings[key]
# null or None means that leave this option out (keep default)
if key == 'path' or value is None or value is False:
if key == "path" or value is None or value is False:
continue
else:
if len(key) == 1:
execute.append(f'-{key}')
execute.append(f"-{key}")
else:
execute.append(f'--{key}')
execute.append(f"--{key}")
# true means key is an option
if value is not True:
@@ -103,6 +110,8 @@ class WrapperMain:
# return the Popen object of the new process created
self.print_lock.acquire()
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}')
Avalon.debug_info(
f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}'
)
self.print_lock.release()
return subprocess.Popen(execute)
return subprocess.Popen(execute, stdout=sys.stdout, stderr=sys.stderr)

View File

@@ -4,7 +4,7 @@
Name: SRMD NCNN Vulkan Driver
Creator: K4YT3X
Date Created: April 26, 2020
Last Modified: September 9, 2020
Last Modified: September 21, 2020
Description: This class is a high-level wrapper
for srmd_ncnn_vulkan.
@@ -16,6 +16,7 @@ import os
import pathlib
import platform
import subprocess
import sys
import threading
# third-party imports
@@ -37,27 +38,33 @@ class WrapperMain:
@staticmethod
def parse_arguments(arguments):
# fmt: off
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
parser.error = lambda message: (_ for _ in ()).throw(AttributeError(message))
parser.add_argument('--help', action='help', help='show this help message and exit')
parser.add_argument('-v', action='store_true', help='verbose output')
parser.add_argument('-i', type=str, help=argparse.SUPPRESS) # help='input image path (jpg/png) or directory')
parser.add_argument('-o', type=str, help=argparse.SUPPRESS) # help='output image path (png) or directory')
parser.add_argument('-n', type=int, choices=range(-1, 11), help='denoise level')
parser.add_argument('-s', type=int, help='upscale ratio')
parser.add_argument('-t', type=int, help='tile size (>=32)')
parser.add_argument('-m', type=str, help='srmd model path')
parser.add_argument('-g', type=int, help='gpu device to use')
parser.add_argument('-j', type=str, help='thread count for load/proc/save')
parser.add_argument('-x', action='store_true', help='enable tta mode')
parser.add_argument("--help", action="help", help="show this help message and exit")
parser.add_argument("-v", action="store_true", help="verbose output")
parser.add_argument("-i", type=str, help=argparse.SUPPRESS) # help="input image path (jpg/png) or directory")
parser.add_argument("-o", type=str, help=argparse.SUPPRESS) # help="output image path (png) or directory")
parser.add_argument("-n", type=int, choices=range(-1, 11), help="denoise level")
parser.add_argument("-s", type=int, help="upscale ratio")
parser.add_argument("-t", type=int, help="tile size (>=32)")
parser.add_argument("-m", type=str, help="srmd model path")
parser.add_argument("-g", type=int, help="gpu device to use")
parser.add_argument("-j", type=str, help="thread count for load/proc/save")
parser.add_argument("-x", action="store_true", help="enable tta mode")
parser.add_argument("-f", type=str, help=argparse.SUPPRESS) # help="output image format (jpg/png/webp, default=ext/png)")
return parser.parse_args(arguments)
# fmt: on
def load_configurations(self, upscaler):
# self.driver_settings['s'] = int(upscaler.scale_ratio)
self.driver_settings['j'] = '{}:{}:{}'.format(upscaler.processes, upscaler.processes, upscaler.processes)
self.driver_settings["j"] = "{}:{}:{}".format(
upscaler.processes, upscaler.processes, upscaler.processes
)
self.driver_settings["f"] = upscaler.extracted_frame_format.lower()
def set_scale_ratio(self, scale_ratio: int):
self.driver_settings['s'] = int(scale_ratio)
self.driver_settings["s"] = int(scale_ratio)
def upscale(self, input_directory, output_directory):
"""This is the core function for SRMD ncnn Vulkan class
@@ -70,33 +77,33 @@ class WrapperMain:
# change the working directory to the binary's parent directory
# so the binary can find shared object files and other files
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# overwrite config file settings
self.driver_settings['i'] = input_directory
self.driver_settings['o'] = output_directory
self.driver_settings["i"] = input_directory
self.driver_settings["o"] = output_directory
# by default, srmd-ncnn-vulkan will look for the models under the current working directory
# change the working directory to its containing folder if model directory not specified
if self.driver_settings['m'] is None and platform.system() == 'Windows':
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
if self.driver_settings["m"] is None and platform.system() == "Windows":
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# list to be executed
# initialize the list with the binary path as the first element
execute = [self.driver_settings['path']]
execute = [self.driver_settings["path"]]
for key in self.driver_settings.keys():
value = self.driver_settings[key]
# null or None means that leave this option out (keep default)
if key == 'path' or value is None or value is False:
if key == "path" or value is None or value is False:
continue
else:
if len(key) == 1:
execute.append(f'-{key}')
execute.append(f"-{key}")
else:
execute.append(f'--{key}')
execute.append(f"--{key}")
# true means key is an option
if value is not True:
@@ -104,6 +111,8 @@ class WrapperMain:
# return the Popen object of the new process created
self.print_lock.acquire()
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}')
Avalon.debug_info(
f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}'
)
self.print_lock.release()
return subprocess.Popen(execute)
return subprocess.Popen(execute, stdout=sys.stdout, stderr=sys.stderr)

View File

@@ -15,6 +15,7 @@ import argparse
import os
import pathlib
import subprocess
import sys
import threading
# third-party imports
@@ -36,77 +37,78 @@ class WrapperMain:
@staticmethod
def parse_arguments(arguments):
# fmt: off
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
parser.error = lambda message: (_ for _ in ()).throw(AttributeError(message))
parser.add_argument('--help', action='help', help='show this help message and exit')
parser.add_argument('-t', '--tta', type=int, choices=range(2), help='8x slower and slightly high quality')
parser.add_argument('--gpu', type=int, help='gpu device no')
parser.add_argument('-b', '--batch_size', type=int, help='input batch size')
parser.add_argument('--crop_h', type=int, help='input image split size(height)')
parser.add_argument('--crop_w', type=int, help='input image split size(width)')
parser.add_argument('-c', '--crop_size', type=int, help='input image split size')
parser.add_argument('-d', '--output_depth', type=int, help='output image chaneel depth bit')
parser.add_argument('-q', '--output_quality', type=int, help='output image quality')
parser.add_argument('-p', '--process', choices=['cpu', 'gpu', 'cudnn'], help='process mode')
parser.add_argument('--model_dir', type=str, help='path to custom model directory (don\'t append last / )')
parser.add_argument('-h', '--scale_height', type=int, help='custom scale height')
parser.add_argument('-w', '--scale_width', type=int, help='custom scale width')
parser.add_argument('-s', '--scale_ratio', type=float, help='custom scale ratio')
parser.add_argument('-n', '--noise_level', type=int, choices=range(4), help='noise reduction level')
parser.add_argument('-m', '--mode', choices=['noise', 'scale', 'noise_scale', 'auto_scale'], help='image processing mode')
parser.add_argument('-e', '--output_extention', type=str, help='extention to output image file when output_path is (auto) or input_path is folder')
parser.add_argument('-l', '--input_extention_list', type=str, help='extention to input image file when input_path is folder')
parser.add_argument('-o', '--output_path', type=str, help=argparse.SUPPRESS) # help='path to output image file (when input_path is folder, output_path must be folder)')
parser.add_argument('-i', '--input_path', type=str, help=argparse.SUPPRESS) # help='(required) path to input image file')
parser.add_argument("--help", action="help", help="show this help message and exit")
parser.add_argument("-t", "--tta", type=int, choices=range(2), help="8x slower and slightly high quality")
parser.add_argument("--gpu", type=int, help="gpu device no")
parser.add_argument("-b", "--batch_size", type=int, help="input batch size")
parser.add_argument("--crop_h", type=int, help="input image split size(height)")
parser.add_argument("--crop_w", type=int, help="input image split size(width)")
parser.add_argument("-c", "--crop_size", type=int, help="input image split size")
parser.add_argument("-d", "--output_depth", type=int, help="output image chaneel depth bit")
parser.add_argument("-q", "--output_quality", type=int, help="output image quality")
parser.add_argument("-p", "--process", choices=["cpu", "gpu", "cudnn"], help="process mode")
parser.add_argument("--model_dir", type=str, help="path to custom model directory (don\"t append last / )")
parser.add_argument("-h", "--scale_height", type=int, help="custom scale height")
parser.add_argument("-w", "--scale_width", type=int, help="custom scale width")
parser.add_argument("-s", "--scale_ratio", type=float, help="custom scale ratio")
parser.add_argument("-n", "--noise_level", type=int, choices=range(4), help="noise reduction level")
parser.add_argument("-m", "--mode", choices=["noise", "scale", "noise_scale", "auto_scale"], help="image processing mode")
parser.add_argument("-e", "--output_extention", type=str, help="extention to output image file when output_path is (auto) or input_path is folder")
parser.add_argument("-l", "--input_extention_list", type=str, help="extention to input image file when input_path is folder")
parser.add_argument("-o", "--output_path", type=str, help=argparse.SUPPRESS) # help="path to output image file (when input_path is folder, output_path must be folder)")
parser.add_argument("-i", "--input_path", type=str, help=argparse.SUPPRESS) # help="(required) path to input image file")
return parser.parse_args(arguments)
# fmt: on
def load_configurations(self, upscaler):
# use scale width and scale height if specified
# self.driver_settings['scale_ratio'] = upscaler.scale_ratio
self.driver_settings['output_extention'] = upscaler.extracted_frame_format
self.driver_settings["output_extention"] = upscaler.extracted_frame_format
# bit_depth will be 12 at this point
# it will up updated later
self.driver_settings['output_depth'] = 12
self.driver_settings["output_depth"] = 12
def set_scale_resolution(self, width: int, height: int):
self.driver_settings['scale_width'] = width
self.driver_settings['scale_height'] = height
self.driver_settings['scale_ratio'] = None
self.driver_settings["scale_width"] = width
self.driver_settings["scale_height"] = height
self.driver_settings["scale_ratio"] = None
def set_scale_ratio(self, scale_ratio: float):
self.driver_settings['scale_width'] = None
self.driver_settings['scale_height'] = None
self.driver_settings['scale_ratio'] = scale_ratio
self.driver_settings["scale_width"] = None
self.driver_settings["scale_height"] = None
self.driver_settings["scale_ratio"] = scale_ratio
def upscale(self, input_directory, output_directory):
""" start upscaling process
"""
"""start upscaling process"""
# change the working directory to the binary's parent directory
# so the binary can find shared object files and other files
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# overwrite config file settings
self.driver_settings['input_path'] = input_directory
self.driver_settings['output_path'] = output_directory
self.driver_settings["input_path"] = input_directory
self.driver_settings["output_path"] = output_directory
# list to be executed
# initialize the list with waifu2x binary path as the first element
execute = [self.driver_settings['path']]
execute = [self.driver_settings["path"]]
for key in self.driver_settings.keys():
value = self.driver_settings[key]
# null or None means that leave this option out (keep default)
if key == 'path' or value is None or value is False:
if key == "path" or value is None or value is False:
continue
else:
if len(key) == 1:
execute.append(f'-{key}')
execute.append(f"-{key}")
else:
execute.append(f'--{key}')
execute.append(f"--{key}")
# true means key is an option
if value is not True:
@@ -114,6 +116,8 @@ class WrapperMain:
# return the Popen object of the new process created
self.print_lock.acquire()
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}')
Avalon.debug_info(
f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}'
)
self.print_lock.release()
return subprocess.Popen(execute)
return subprocess.Popen(execute, stdout=sys.stdout, stderr=sys.stderr)

View File

@@ -15,6 +15,7 @@ import argparse
import os
import pathlib
import subprocess
import sys
import threading
# third-party imports
@@ -36,45 +37,47 @@ class WrapperMain:
@staticmethod
def parse_arguments(arguments):
# fmt: off
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
parser.error = lambda message: (_ for _ in ()).throw(AttributeError(message))
parser.add_argument('--help', action='help', help='show this help message and exit')
parser.add_argument('--list-supported-formats', action='store_true', help='dump currently supported format list')
parser.add_argument('--list-opencv-formats', action='store_true', help='(deprecated. Use --list-supported-formats) dump opencv supported format list')
parser.add_argument('-l', '--list-processor', action='store_true', help='dump processor list')
parser.add_argument('-f', '--output-format', choices=['png', 'jpg'], help='The format used when running in recursive/folder mode\nSee --list-supported-formats for a list of supported formats/extensions.')
parser.add_argument('-c', '--png-compression', type=int, choices=range(10), help='Set PNG compression level (0-9), 9 = Max compression (slowest & smallest)')
parser.add_argument('-q', '--image-quality', type=int, choices=range(-1, 102), help='JPEG & WebP Compression quality (0-101, 0 being smallest size and lowest quality), use 101 for lossless WebP')
parser.add_argument('--block-size', type=int, help='block size')
parser.add_argument('--disable-gpu', action='store_true', help='disable GPU')
parser.add_argument('--force-OpenCL', action='store_true', help='force to use OpenCL on Intel Platform')
parser.add_argument('-p', '--processor', type=int, help='set target processor')
parser.add_argument('-j', '--jobs', type=int, help='number of threads launching at the same time')
parser.add_argument('--model-dir', type=str, help='path to custom model directory (don\'t append last / )')
parser.add_argument('--scale-ratio', type=float, help='custom scale ratio')
parser.add_argument('--noise-level', type=int, choices=range(4), help='noise reduction level')
parser.add_argument('-m', '--mode', choices=['noise', 'scale', 'noise-scale'], help='image processing mode')
parser.add_argument('-v', '--log-level', type=int, choices=range(5), help='Set log level')
parser.add_argument('-s', '--silent', action='store_true', help='Enable silent mode. (same as --log-level 1)')
parser.add_argument('-t', '--tta', type=int, choices=range(2), help='Enable Test-Time Augmentation mode.')
parser.add_argument('-g', '--generate-subdir', type=int, choices=range(2), help='Generate sub folder when recursive directory is enabled.')
parser.add_argument('-a', '--auto-naming', type=int, choices=range(2), help='Add postfix to output name when output path is not specified.\nSet 0 to disable this.')
parser.add_argument('-r', '--recursive-directory', type=int, choices=range(2), help='Search recursively through directories to find more images to process.')
parser.add_argument('-o', '--output', type=str, help=argparse.SUPPRESS) # help='path to output image file or directory (you should use the full path)')
parser.add_argument('-i', '--input', type=str, help=argparse.SUPPRESS) # help='(required) path to input image file or directory (you should use the full path)')
parser.add_argument('--version', action='store_true', help='Displays version information and exits.')
parser.add_argument("--help", action="help", help="show this help message and exit")
parser.add_argument("--list-supported-formats", action="store_true", help="dump currently supported format list")
parser.add_argument("--list-opencv-formats", action="store_true", help="(deprecated. Use --list-supported-formats) dump opencv supported format list")
parser.add_argument("-l", "--list-processor", action="store_true", help="dump processor list")
parser.add_argument("-f", "--output-format", choices=["png", "jpg"], help="The format used when running in recursive/folder mode\nSee --list-supported-formats for a list of supported formats/extensions.")
parser.add_argument("-c", "--png-compression", type=int, choices=range(10), help="Set PNG compression level (0-9), 9 = Max compression (slowest & smallest)")
parser.add_argument("-q", "--image-quality", type=int, choices=range(-1, 102), help="JPEG & WebP Compression quality (0-101, 0 being smallest size and lowest quality), use 101 for lossless WebP")
parser.add_argument("--block-size", type=int, help="block size")
parser.add_argument("--disable-gpu", action="store_true", help="disable GPU")
parser.add_argument("--force-OpenCL", action="store_true", help="force to use OpenCL on Intel Platform")
parser.add_argument("-p", "--processor", type=int, help="set target processor")
parser.add_argument("-j", "--jobs", type=int, help="number of threads launching at the same time")
parser.add_argument("--model-dir", type=str, help="path to custom model directory (don\"t append last / )")
parser.add_argument("--scale-ratio", type=float, help="custom scale ratio")
parser.add_argument("--noise-level", type=int, choices=range(4), help="noise reduction level")
parser.add_argument("-m", "--mode", choices=["noise", "scale", "noise-scale"], help="image processing mode")
parser.add_argument("-v", "--log-level", type=int, choices=range(5), help="Set log level")
parser.add_argument("-s", "--silent", action="store_true", help="Enable silent mode. (same as --log-level 1)")
parser.add_argument("-t", "--tta", type=int, choices=range(2), help="Enable Test-Time Augmentation mode.")
parser.add_argument("-g", "--generate-subdir", type=int, choices=range(2), help="Generate sub folder when recursive directory is enabled.")
parser.add_argument("-a", "--auto-naming", type=int, choices=range(2), help="Add postfix to output name when output path is not specified.\nSet 0 to disable this.")
parser.add_argument("-r", "--recursive-directory", type=int, choices=range(2), help="Search recursively through directories to find more images to process.")
parser.add_argument("-o", "--output", type=str, help=argparse.SUPPRESS) # help="path to output image file or directory (you should use the full path)")
parser.add_argument("-i", "--input", type=str, help=argparse.SUPPRESS) # help="(required) path to input image file or directory (you should use the full path)")
parser.add_argument("--version", action="store_true", help="Displays version information and exits.")
return parser.parse_args(arguments)
# fmt: on
def load_configurations(self, upscaler):
# self.driver_settings['scale-ratio'] = upscaler.scale_ratio
self.driver_settings['jobs'] = upscaler.processes
self.driver_settings['output-format'] = upscaler.extracted_frame_format.lower()
self.driver_settings["jobs"] = upscaler.processes
self.driver_settings["output-format"] = upscaler.extracted_frame_format.lower()
def set_scale_ratio(self, scale_ratio: float):
self.driver_settings['scale-ratio'] = scale_ratio
self.driver_settings["scale-ratio"] = scale_ratio
def upscale(self, input_directory, output_directory):
""" Waifu2x Converter Driver Upscaler
"""Waifu2x Converter Driver Upscaler
This method executes the upscaling of extracted frames.
Arguments:
@@ -86,33 +89,35 @@ class WrapperMain:
# change the working directory to the binary's parent directory
# so the binary can find shared object files and other files
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# overwrite config file settings
self.driver_settings['input'] = input_directory
self.driver_settings['output'] = output_directory
self.driver_settings["input"] = input_directory
self.driver_settings["output"] = output_directory
# models_rgb must be specified manually for waifu2x-converter-cpp
# if it's not specified in the arguments, create automatically
if self.driver_settings['model-dir'] is None:
self.driver_settings['model-dir'] = pathlib.Path(self.driver_settings['path']).parent / 'models_rgb'
if self.driver_settings["model-dir"] is None:
self.driver_settings["model-dir"] = (
pathlib.Path(self.driver_settings["path"]).parent / "models_rgb"
)
# list to be executed
# initialize the list with waifu2x binary path as the first element
execute = [self.driver_settings['path']]
execute = [self.driver_settings["path"]]
for key in self.driver_settings.keys():
value = self.driver_settings[key]
# null or None means that leave this option out (keep default)
if key == 'path' or value is None or value is False:
if key == "path" or value is None or value is False:
continue
else:
if len(key) == 1:
execute.append(f'-{key}')
execute.append(f"-{key}")
else:
execute.append(f'--{key}')
execute.append(f"--{key}")
# true means key is an option
if value is not True:
@@ -120,6 +125,8 @@ class WrapperMain:
# return the Popen object of the new process created
self.print_lock.acquire()
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}')
Avalon.debug_info(
f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}'
)
self.print_lock.release()
return subprocess.Popen(execute)
return subprocess.Popen(execute, stdout=sys.stdout, stderr=sys.stderr)

View File

@@ -7,7 +7,7 @@ Date Created: June 26, 2019
Last Modified: May 11, 2020
Editor: K4YT3X
Last Modified: September 9, 2020
Last Modified: September 21, 2020
Description: This class is a high-level wrapper
for waifu2x_ncnn_vulkan.
@@ -19,6 +19,7 @@ import os
import pathlib
import platform
import subprocess
import sys
import threading
# third-party imports
@@ -40,30 +41,36 @@ class WrapperMain:
@staticmethod
def parse_arguments(arguments):
# fmt: off
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
parser.error = lambda message: (_ for _ in ()).throw(AttributeError(message))
parser.add_argument('--help', action='help', help='show this help message and exit')
parser.add_argument('-v', action='store_true', help='verbose output')
parser.add_argument('-i', type=str, help=argparse.SUPPRESS) # help='input image path (jpg/png) or directory')
parser.add_argument('-o', type=str, help=argparse.SUPPRESS) # help='output image path (png) or directory')
parser.add_argument('-n', type=int, choices=range(-1, 4), help='denoise level')
parser.add_argument('-s', type=int, help='upscale ratio')
parser.add_argument('-t', type=int, help='tile size (>=32)')
parser.add_argument('-m', type=str, help='waifu2x model path')
parser.add_argument('-g', type=int, help='gpu device to use')
parser.add_argument('-j', type=str, help='thread count for load/proc/save')
parser.add_argument('-x', action='store_true', help='enable tta mode')
parser.add_argument("--help", action="help", help="show this help message and exit")
parser.add_argument("-v", action="store_true", help="verbose output")
parser.add_argument("-i", type=str, help=argparse.SUPPRESS) # help="input image path (jpg/png/webp) or directory")
parser.add_argument("-o", type=str, help=argparse.SUPPRESS) # help="output image path (jpg/png/webp) or directory")
parser.add_argument("-n", type=int, choices=range(-1, 4), help="denoise level")
parser.add_argument("-s", type=int, help="upscale ratio")
parser.add_argument("-t", type=int, help="tile size (>=32)")
parser.add_argument("-m", type=str, help="waifu2x model path")
parser.add_argument("-g", type=int, help="gpu device to use")
parser.add_argument("-j", type=str, help="thread count for load/proc/save")
parser.add_argument("-x", action="store_true", help="enable tta mode")
parser.add_argument("-f", type=str, help=argparse.SUPPRESS) # help="output image format (jpg/png/webp, default=ext/png)")
return parser.parse_args(arguments)
# fmt: on
def load_configurations(self, upscaler):
# self.driver_settings['s'] = int(upscaler.scale_ratio)
self.driver_settings['j'] = '{}:{}:{}'.format(upscaler.processes, upscaler.processes, upscaler.processes)
self.driver_settings["j"] = "{}:{}:{}".format(
upscaler.processes, upscaler.processes, upscaler.processes
)
self.driver_settings["f"] = upscaler.extracted_frame_format.lower()
def set_scale_ratio(self, scale_ratio: int):
self.driver_settings['s'] = int(scale_ratio)
self.driver_settings["s"] = int(scale_ratio)
def upscale(self, input_directory, output_directory):
""" This is the core function for waifu2x class
"""This is the core function for waifu2x class
Arguments:
input_directory {string} -- source directory path
@@ -73,33 +80,33 @@ class WrapperMain:
# change the working directory to the binary's parent directory
# so the binary can find shared object files and other files
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# overwrite config file settings
self.driver_settings['i'] = input_directory
self.driver_settings['o'] = output_directory
self.driver_settings["i"] = input_directory
self.driver_settings["o"] = output_directory
# by default, waifu2x-ncnn-vulkan will look for the models under the current working directory
# change the working directory to its containing folder if model directory not specified
if self.driver_settings['m'] is None and platform.system() == 'Windows':
os.chdir(pathlib.Path(self.driver_settings['path']).parent)
if self.driver_settings["m"] is None and platform.system() == "Windows":
os.chdir(pathlib.Path(self.driver_settings["path"]).parent)
# list to be executed
# initialize the list with waifu2x binary path as the first element
execute = [self.driver_settings['path']]
execute = [self.driver_settings["path"]]
for key in self.driver_settings.keys():
value = self.driver_settings[key]
# null or None means that leave this option out (keep default)
if key == 'path' or value is None or value is False:
if key == "path" or value is None or value is False:
continue
else:
if len(key) == 1:
execute.append(f'-{key}')
execute.append(f"-{key}")
else:
execute.append(f'--{key}')
execute.append(f"--{key}")
# true means key is an option
if value is not True:
@@ -107,6 +114,8 @@ class WrapperMain:
# return the Popen object of the new process created
self.print_lock.acquire()
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}')
Avalon.debug_info(
f'[upscaler] Subprocess {os.getpid()} executing: {" ".join(execute)}'
)
self.print_lock.release()
return subprocess.Popen(execute)
return subprocess.Popen(execute, stdout=sys.stdout, stderr=sys.stderr)