formatted setup script with black

This commit is contained in:
K4YT3X 2020-12-13 16:39:49 -05:00
parent 9e8e95803f
commit cc89b0aac5

View File

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