mirror of
https://github.com/k4yt3x/video2x.git
synced 2026-02-06 20:44:56 +08:00
Compare commits
243 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5cf3271aad | ||
|
|
bcbead4d96 | ||
|
|
a3d0465e44 | ||
|
|
995fdec5c8 | ||
|
|
5c3ea51ccb | ||
|
|
a24b321088 | ||
|
|
a83249c670 | ||
|
|
ab2f982a84 | ||
|
|
91401977da | ||
|
|
99971bceb1 | ||
|
|
0c6de8af16 | ||
|
|
4def30f516 | ||
|
|
8d553ac575 | ||
|
|
e1a1cf578b | ||
|
|
4015617152 | ||
|
|
648bf4fd3d | ||
|
|
e3ed08ff40 | ||
|
|
90f807655a | ||
|
|
ab77d62c71 | ||
|
|
a64fabae87 | ||
|
|
26558c6159 | ||
|
|
4fbbb20258 | ||
|
|
4659a9a9f5 | ||
|
|
4c48af4fa4 | ||
|
|
4a6f90a1f0 | ||
|
|
2d9c5fe751 | ||
|
|
bef3861d3c | ||
|
|
bcb54b6d2c | ||
|
|
e82a26d44f | ||
|
|
14f7f34ee3 | ||
|
|
11ba334f16 | ||
|
|
c451b14bd7 | ||
|
|
80623a6bb7 | ||
|
|
a5dd87a72c | ||
|
|
9b20ef89c9 | ||
|
|
91efe2d684 | ||
|
|
0d9d5c4f43 | ||
|
|
e0e42b11c8 | ||
|
|
790bb54598 | ||
|
|
f2943802cb | ||
|
|
d12f2a3888 | ||
|
|
871d6386a8 | ||
|
|
589a68caf7 | ||
|
|
afacc48e1e | ||
|
|
4a3553607b | ||
|
|
988600a769 | ||
|
|
36aa3bf1d4 | ||
|
|
9dde3c66f1 | ||
|
|
e9c1c22788 | ||
|
|
134e8b7080 | ||
|
|
a295b4a54f | ||
|
|
c198082190 | ||
|
|
8f2dc43af3 | ||
|
|
b0ce8f3ff9 | ||
|
|
0b1f7b8422 | ||
|
|
def20650e2 | ||
|
|
7489376404 | ||
|
|
826279ce09 | ||
|
|
88d2cd9e14 | ||
|
|
31728ff625 | ||
|
|
3168737fd4 | ||
|
|
5fbc195740 | ||
|
|
40d0d79141 | ||
|
|
37a0966bad | ||
|
|
baf4c5815f | ||
|
|
d25a478e64 | ||
|
|
ba723c6216 | ||
|
|
11ea8a7a21 | ||
|
|
3bce37416b | ||
|
|
e3cfe13b5c | ||
|
|
81d8ce78cb | ||
|
|
89fa91c8c5 | ||
|
|
c8dbb90f5b | ||
|
|
685120011b | ||
|
|
82da40327b | ||
|
|
9b4fb3258a | ||
|
|
f00a10aa91 | ||
|
|
93e8f36ffb | ||
|
|
f10e59099c | ||
|
|
82715ade18 | ||
|
|
63de63e594 | ||
|
|
8daeb862a4 | ||
|
|
be0d1f1d08 | ||
|
|
ec1327b5d8 | ||
|
|
5b3e5604cc | ||
|
|
a2fc71d6c5 | ||
|
|
ab684bcd48 | ||
|
|
d26b406813 | ||
|
|
133b837b15 | ||
|
|
9aebc77883 | ||
|
|
b8472f155a | ||
|
|
19e6d241d5 | ||
|
|
89860f22cb | ||
|
|
88299d404a | ||
|
|
0f1639ed62 | ||
|
|
3b6462d1da | ||
|
|
43a2078330 | ||
|
|
b1e844dcad | ||
|
|
becce32d3e | ||
|
|
d2ddf32527 | ||
|
|
7224c53997 | ||
|
|
2ed9bd4da6 | ||
|
|
38c52cdfd2 | ||
|
|
80579d3fa9 | ||
|
|
47f94dfd6c | ||
|
|
c470dde5da | ||
|
|
c532ac3c88 | ||
|
|
f50ceecd62 | ||
|
|
2ba0e951f9 | ||
|
|
5753ea8f52 | ||
|
|
09db8bedd0 | ||
|
|
6a100b1526 | ||
|
|
a2150a8dbc | ||
|
|
78ded08ed5 | ||
|
|
5db2cfd2a3 | ||
|
|
652b9f34bd | ||
|
|
f3c50ea728 | ||
|
|
880087241d | ||
|
|
067e17290a | ||
|
|
fc675e7899 | ||
|
|
2d81270e44 | ||
|
|
3ace2447c2 | ||
|
|
30b0e2c7bf | ||
|
|
d54fea0310 | ||
|
|
332055a4e5 | ||
|
|
19e17b1a8f | ||
|
|
9e745fb747 | ||
|
|
fd5edead7e | ||
|
|
aa7c0b3f12 | ||
|
|
65cc4c6afb | ||
|
|
bd2da021bd | ||
|
|
7e888db7b2 | ||
|
|
7726a86e35 | ||
|
|
a0595136ab | ||
|
|
5c93a5a73b | ||
|
|
7b9b87fa9b | ||
|
|
cb255da65c | ||
|
|
d503325a62 | ||
|
|
954233c238 | ||
|
|
95416f68a8 | ||
|
|
dce778b3bf | ||
|
|
c537dd726c | ||
|
|
b1918a4a8a | ||
|
|
7ae9618785 | ||
|
|
eb3d29103c | ||
|
|
a188f6ebda | ||
|
|
fd67dfca11 | ||
|
|
b1f29f1098 | ||
|
|
fe7c0c840d | ||
|
|
dc2410d4da | ||
|
|
91ac512d57 | ||
|
|
732288f075 | ||
|
|
e812c228c3 | ||
|
|
9841fa9577 | ||
|
|
5391f59847 | ||
|
|
6180ccd9b2 | ||
|
|
e10315f89e | ||
|
|
6521e071ce | ||
|
|
a685e91b14 | ||
|
|
9d72bad314 | ||
|
|
2b63b5f0a6 | ||
|
|
9c84228c17 | ||
|
|
f9bb191336 | ||
|
|
7a3af366f8 | ||
|
|
d4223f93ec | ||
|
|
c5c764a91f | ||
|
|
ba6472c9fc | ||
|
|
dc1244580f | ||
|
|
0347d05127 | ||
|
|
45f5bf91e6 | ||
|
|
5e78beabcf | ||
|
|
6c5b7ea17f | ||
|
|
d9610abae0 | ||
|
|
47471352ba | ||
|
|
969cfe5c0d | ||
|
|
e12db41213 | ||
|
|
7a69d58e28 | ||
|
|
ad6308d385 | ||
|
|
8c3a85ac42 | ||
|
|
db603062e9 | ||
|
|
807276fcc3 | ||
|
|
9be46f7d62 | ||
|
|
f42a8ab71f | ||
|
|
e3b2624977 | ||
|
|
685d894bef | ||
|
|
b0167e9f08 | ||
|
|
74767743bd | ||
|
|
ece345e531 | ||
|
|
47e787c80c | ||
|
|
4639555626 | ||
|
|
d423fa1b6e | ||
|
|
734cf7bb0e | ||
|
|
77ad212b01 | ||
|
|
a27bdb4b63 | ||
|
|
89dfd21f97 | ||
|
|
5151be4122 | ||
|
|
f8d3fa5c25 | ||
|
|
61abcc6a3a | ||
|
|
40a4d3a602 | ||
|
|
9429b04528 | ||
|
|
55c2f7abfb | ||
|
|
c7c83d35ed | ||
|
|
ca90c5be02 | ||
|
|
5a2b387b9d | ||
|
|
eda5d70773 | ||
|
|
8b845e35b3 | ||
|
|
e3b7110ff5 | ||
|
|
cefa2c4f30 | ||
|
|
4d9c0866ce | ||
|
|
25fca78eb4 | ||
|
|
4a0ffae6c8 | ||
|
|
f94f99eb1c | ||
|
|
a9586bf508 | ||
|
|
5f69a44bf7 | ||
|
|
1ee76c0224 | ||
|
|
0b99ac33a6 | ||
|
|
4e3565b3ac | ||
|
|
b40aee0cd7 | ||
|
|
5b27cf26e1 | ||
|
|
8fe6fd4009 | ||
|
|
d4d485e132 | ||
|
|
53f5192896 | ||
|
|
e6d865a80d | ||
|
|
d25857a178 | ||
|
|
81af7b1c1b | ||
|
|
81b8e45b6f | ||
|
|
e003cbc568 | ||
|
|
f96b95563e | ||
|
|
76144b589a | ||
|
|
15d2dbb07a | ||
|
|
9d5ad2f70c | ||
|
|
b5da9ebbf7 | ||
|
|
a1e1d98929 | ||
|
|
fafd5fadd3 | ||
|
|
1280a791ec | ||
|
|
8e85d6a6d3 | ||
|
|
8b0f82e95e | ||
|
|
a6666c3c3b | ||
|
|
585164a508 | ||
|
|
6b3e1b9768 | ||
|
|
0f4daa12d2 | ||
|
|
4cf83dc565 | ||
|
|
b984977227 |
12
.github/FUNDING.yml
vendored
Normal file
12
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: k4yt3x
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
5
.github/ISSUE_TEMPLATE/bug-report.md
vendored
5
.github/ISSUE_TEMPLATE/bug-report.md
vendored
@@ -11,10 +11,11 @@ assignees: K4YT3X
|
||||
|
||||
|Module|Version|
|
||||
|-|-|
|
||||
|`video2x`||
|
||||
|`ffmpeg`||
|
||||
|`Video2X`||
|
||||
|`FFmpeg`||
|
||||
|`waifu2x-caffe`||
|
||||
|`waifu2x-converter-cpp`||
|
||||
|`waifu2x-ncnn-vulkan`||
|
||||
|
||||
## Symptom
|
||||
|
||||
|
||||
10
.gitignore
vendored
10
.gitignore
vendored
@@ -1,9 +1,3 @@
|
||||
# Runtime files
|
||||
upscaled/
|
||||
frames/
|
||||
waifu2x-caffe/
|
||||
testvid.mp4
|
||||
|
||||
# PyCharm
|
||||
.idea/
|
||||
|
||||
@@ -57,8 +51,8 @@ coverage.xml
|
||||
.pytest_cache/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
#*.mo
|
||||
#*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
|
||||
307
README.md
307
README.md
@@ -1,59 +1,72 @@
|
||||
# Video2X Lossless Video Enlarger
|
||||
<p align="center">
|
||||
<img src="https://user-images.githubusercontent.com/21986859/81489504-c7d1f780-9265-11ea-86c8-cc0316e2082d.png"/>
|
||||
</p>
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
<img alt="Become a Patron!"
|
||||
src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png"
|
||||
href="https://www.patreon.com/bePatron?u=34970782"
|
||||
height=20 />
|
||||
|
||||
<!--# Video2X Lossless Video Enlarger-->
|
||||
|
||||
### Official Discussion Group (Telegram): https://t.me/video2x
|
||||
|
||||
## Download Builds (beta)
|
||||
## [Download Builds](https://github.com/k4yt3x/video2x/releases) (Windows)
|
||||
|
||||
You can go to the [releases page](https://github.com/k4yt3x/video2x/releases) to download the latest builds of `Video2X`. The exe files will require no Python or Python module installation.
|
||||
You can go to the [releases page](https://github.com/k4yt3x/video2x/releases) to download the latest builds of Video2X. The exe files will require no Python or Python module installation. There are two editions available.
|
||||
|
||||
The **`full`** package provides all packages that will possibly be needed by `Video2X`, including `FFmpeg`, `waifu2x-caffe` and `waifu2x-converter-cpp`. The config file (`video2x.json`) is also already configured for the environment. All you need to do is just to launch `video2x.exe`.
|
||||
- **`Full`**: full package comes pre-configured with **all** dependencies like `FFmpeg` and `waifu2x-caffe`.
|
||||
- **`Light`**: ligt package comes with only Video2X binaries and a template configuration file. The user will either have to run the setup script or install and configure dependencies themselves.
|
||||
|
||||
The **`light`** package provides only the most basic functions of `Video2X`. Only `video2x.exe`, `video2x_setup.exe` and `video2x.json` are included. To setup `FFmpeg`, `waifu2x-caffe` or `waifu2x-converter-cpp` automatically, simply launch `video2x_setup.exe`.
|
||||
Go to the [Quick Start](#quick-start) section for usages.
|
||||
|
||||
## Prerequisites
|
||||
## Introduction
|
||||
|
||||
Component names that are **bolded** can be automatically downloaded and configured with the `video2x_setup.py` script.
|
||||
Video2X is a video upscaling software based on Waifu2X, Anime4K and SRMD written in Python 3. It upscales videos and restores details from low-resolution videos. Below is a side-by-side preview.
|
||||
|
||||
1. Operating System: Windows
|
||||
2. AMD GPU / Nvidia GPU
|
||||
3. AMD GPU driver / Nvidia GPU driver / Nvidia CUDNN
|
||||
4. [**FFmpeg**](https://ffmpeg.zeranoe.com/builds/)
|
||||
5. [**waifu2x-caffe**](https://github.com/lltcggie/waifu2x-caffe/releases) / [**waifu2x-converter-cpp**](https://github.com/DeadSix27/waifu2x-converter-cpp/releases)
|
||||

|
||||
|
||||
## Recent Changes
|
||||
*Upscale Comparison Demonstration*
|
||||
|
||||
### 2.7.1 (April 18, 2019)
|
||||
|
||||
- Fixed video2x custom temp folder bug found by @cr08 .
|
||||
|
||||
### 2.7.0 (March 30, 2019)
|
||||
|
||||
- Added support for different extracted image formats.
|
||||
- Redesigned FFmpeg wrapper, FFmpeg settings are now customizable in the `video2x.json` config file.
|
||||
- Other minor enhancements and adjustments (e.g. argument -> method variable)
|
||||
|
||||
### Setup Script 1.2.0 (March 26, 2019)
|
||||
|
||||
- `video2x_setup.py` script can now automatically download and configure `waifu2x-converter-cpp`.
|
||||
- replaced old progress indicator with progress bar.
|
||||
|
||||
## Description
|
||||
|
||||
Video2X is an automation software based on waifu2x image enlarging engine. It extracts frames from a video, enlarge it by a number of times without losing any details or quality, keeping lines smooth and edges sharp.
|
||||
|
||||
For short: **Video2X enlarges your video without losing details**
|
||||
|
||||
Watch for the sharper edges in this screenshot around the shadows:
|
||||
|
||||

|
||||
|
||||
**You can also watch the YouTube video Demo: https://www.youtube.com/watch?v=PG94iPoeoZk**
|
||||
**You can watch the whole demo video on YouTube: https://youtu.be/mGEfasQl2Zo**
|
||||
|
||||
Clip is from trailer of animated movie "千と千尋の神隠し". Copyright belongs to "株式会社スタジオジブリ (STUDIO GHIBLI INC.)". Will delete immediately if use of clip is in violation of copyright.
|
||||
|
||||
## Screenshot
|
||||
## Demo Videos
|
||||
|
||||

|
||||
Below is a list of all the demo videos available.
|
||||
The list is sorted from new to old.
|
||||
|
||||
- **Bad Apple!!**
|
||||
- YouTube: https://youtu.be/-RKLdCELgkQ
|
||||
- Bilibili: https://www.bilibili.com/video/BV1s5411s7xV/
|
||||
- **The Pet Girl of Sakurasou 240P to 1080P 60FPS**
|
||||
- Original name: さくら荘のペットな彼女
|
||||
- YouTube: https://youtu.be/M0vDI1HH2_Y
|
||||
- Bilibili: https://www.bilibili.com/video/BV14k4y167KP/
|
||||
- **Spirited Away (360P to 4K)**
|
||||
- Original name: 千と千尋の神隠し
|
||||
- YouTube: https://youtu.be/mGEfasQl2Zo
|
||||
- Bilibili: https://www.bilibili.com/video/BV1V5411471i/
|
||||
|
||||
## Screenshots
|
||||
|
||||
### Video2X GUI
|
||||
|
||||

|
||||
|
||||
*Video2X GUI Screenshot*
|
||||
|
||||
### Video2X CLI
|
||||
|
||||

|
||||
|
||||
*Video2X CLI Screenshot*
|
||||
|
||||
---
|
||||
|
||||
@@ -63,150 +76,167 @@ Clip is from trailer of animated movie "千と千尋の神隠し". Copyright bel
|
||||
|
||||
You can find all detailed user-facing and developer-facing documentations in the [Video2X Wiki](https://github.com/k4yt3x/video2x/wiki). It covers everything from step-by-step instructions for beginners, to the code structure of this program for advanced users and developers. If this README page doesn't answer all your questions, the wiki page is where you should head to.
|
||||
|
||||
### [Run From Source](https://github.com/k4yt3x/video2x/wiki/Run-From-Source)
|
||||
|
||||
Instructions for how to run this program from source code.
|
||||
|
||||
### [Step-By-Step Tutorial](https://github.com/k4yt3x/video2x/wiki/Step-By-Step-Tutorial)
|
||||
|
||||
For those who want a detailed walk-through of how to use `Video2X`, you can head to the [Step-By-Step Tutorial](https://github.com/k4yt3x/video2x/wiki/Step-By-Step-Tutorial) wiki page. It includes almost every step you need to perform in order to enlarge your first video.
|
||||
For those who want a detailed walk-through of how to use Video2X, you can head to the [Step-By-Step Tutorial](https://github.com/k4yt3x/video2x/wiki/Step-By-Step-Tutorial) wiki page. It includes almost every step you need to perform in order to enlarge your first video.
|
||||
|
||||
### [Waifu2X Drivers](https://github.com/k4yt3x/video2x/wiki/Waifu2X-Drivers)
|
||||
### [Drivers](https://github.com/k4yt3x/video2x/wiki/Drivers)
|
||||
|
||||
Go to the [Waifu2X Drivers](https://github.com/k4yt3x/video2x/wiki/Waifu2X-Drivers) wiki page if you want to see a detailed description on the different types of `waifu2x` drivers implemented by `Video2X`. This wiki page contains detailed difference between different drivers, and how to download and set each of them up for `Video2X`.
|
||||
Go to the [Drivers](https://github.com/k4yt3x/video2x/wiki/Drivers) wiki page if you want to see a detailed description on the different types of drivers implemented by Video2X. This wiki page contains detailed difference between different drivers, and how to download and set each of them up for Video2X.
|
||||
|
||||
### [Q&A](https://github.com/k4yt3x/video2x/wiki/Q&A)
|
||||
|
||||
If you have any questions, first try visiting our [Q&A](https://github.com/k4yt3x/video2x/wiki/Q&A) page to see if your question is answered there. If not, open an issue and we will respond to your questions ASAP.
|
||||
If you have any questions, first try visiting our [Q&A](https://github.com/k4yt3x/video2x/wiki/Q&A) page to see if your question is answered there. If not, open an issue and we will respond to your questions ASAP. Alternatively, you can also join our [Telegram discussion group](https://t.me/video2x) and ask your questions there.
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Python 3**
|
||||
Download: https://www.python.org/downloads/windows/
|
||||
- **FFmpeg Windows Build**
|
||||
Download: https://ffmpeg.org/download.html
|
||||
- **waifu2x-caffe** (for Nvidia CUDA/CUDNN)
|
||||
Download: https://github.com/lltcggie/waifu2x-caffe/releases
|
||||
- **waifu2x-converter-cpp** (required for AMD, OpenCL and OpenGL processing)
|
||||
Download: https://github.com/DeadSix27/waifu2x-converter-cpp/releases
|
||||
|
||||
### Installing Dependencies
|
||||
|
||||
First, clone the video2x repository.
|
||||
|
||||
```shell
|
||||
git clone https://github.com/k4yt3x/video2x.git
|
||||
cd video2x/bin
|
||||
```
|
||||
|
||||
Then you may run the `video2x_setup.py` script to install and configure the dependencies automatically. This script is designed and tested on Windows 10.
|
||||
|
||||
This script will install the newest version of `ffmpeg`, either or both of `waifu2x-caffe` and `waifu2x-converter-cpp` to `%LOCALAPPDATA%\\video2x` and all required python libraries.
|
||||
|
||||
```shell
|
||||
python video2x_setup.py
|
||||
```
|
||||
|
||||
Alternatively, you can also install the dependencies manually. Please refer to the prerequisites section to see what's needed.
|
||||
|
||||
Then you'll need to install python dependencies before start using video2x. Install simply by executing the following command.
|
||||
|
||||
```shell
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
**Note that all command line arguments/options overwrite configuration file settings.**
|
||||
|
||||
### Sample Videos
|
||||
|
||||
If you can't find a video clip to begin with, or if you want to see a before-after comparison, we have prepared some sample clips for you. The quick start guide down below will also be based on the name of the sample clips.
|
||||
|
||||

|
||||
|
||||
- [Sample Video Original (240P) 1.7MB](https://files.flexio.org/Resources/Videos/sample_input.mp4)
|
||||
- [Sample Video Upscaled (1080P) 4.8MB](https://files.flexio.org/Resources/Videos/sample_output.mp4)
|
||||
*Sample Upscale Videos*
|
||||
|
||||
- [Sample Video (240P) 4.54MB](https://files.k4yt3x.com/Resources/Videos/sample_input.mp4)
|
||||
- [Sample Video Upscaled (1080P) 4.54MB](https://files.k4yt3x.com/Resources/Videos/sample_output.mp4)
|
||||
- [Sample Video Original (1080P) 22.2MB](https://files.k4yt3x.com/Resources/Videos/sample_original.mp4)
|
||||
|
||||
Clip is from anime "さくら荘のペットな彼女". Copyright belongs to "株式会社アニプレックス (Aniplex Inc.)". Will delete immediately if use of clip is in violation of copyright.
|
||||
|
||||
### Nvidia CUDA (waifu2x-caffe)
|
||||
---
|
||||
|
||||
Enlarge the video to 1920x1080 using CUDA. You may also use the `-r/--ratio` option.
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before running Video2X, you'll need to ensure you have installed the drivers' external dependencies such as GPU drivers.
|
||||
|
||||
- waifu2x-caffe
|
||||
- GPU mode: Nvidia graphics card driver
|
||||
- cuDNN mode: Nvidia CUDA and [cuDNN](https://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html#install-windows)
|
||||
- Other Drivers
|
||||
- GPU driver if you want to use GPU for processing
|
||||
|
||||
### Running Video2X (GUI)
|
||||
|
||||
The easiest way to run Video2X is to use the full build. Extract the full release zip file and you'll get these files.
|
||||
|
||||

|
||||
|
||||
Simply double click on video2x_gui.exe to launch the GUI.
|
||||
|
||||

|
||||
|
||||
Then, drag the videos you wish to upscale into the window and select the appropriate output path.
|
||||
|
||||

|
||||
|
||||
Tweak the settings if you want to, then hit the start button at the bottom and the upscale will start. Now you'll just have to wait for it to complete.
|
||||
|
||||

|
||||
|
||||
### Running Video2X (CLI)
|
||||
|
||||
#### Basic Upscale Example
|
||||
|
||||
This example command below uses `waifu2x-caffe` to enlarge the video `sample-input.mp4` two double its original size.
|
||||
|
||||
```shell
|
||||
python video2x.py -i sample_input.mp4 -o sample_output.mp4 -m gpu --width=1920 --height=1080
|
||||
python video2x.py -i sample-input.mp4 -o sample-output.mp4 -r 2 -d waifu2x_caffe
|
||||
```
|
||||
|
||||
### Nvidia CNDNN
|
||||
#### Advanced Upscale Example
|
||||
|
||||
Enlarge the video to 1920x1080 using CUDNN. You may also use the `-r/--ratio` option.
|
||||
If you would like to tweak engine-specific settings, either specify the corresponding argument after `--`, or edit the corresponding field in the configuration file `video2x.yaml`. **Command line arguments will overwrite default values in the config file.**
|
||||
|
||||
This example below adds enables TTA for `waifu2x-caffe`.
|
||||
|
||||
```shell
|
||||
python video2x.py -i sample_input.mp4 -o sample_output.mp4 -m cudnn --width=1920 --height=1080
|
||||
python video2x.py -i sample-input.mp4 -o sample-output.mp4 -r 2 -d waifu2x_caffe -- --tta 1
|
||||
```
|
||||
|
||||
### AMD or Nvidia (waifu2x-converter-cpp OpenCL)
|
||||
|
||||
Enlarge the video by 2 times using OpenCL. Note that `waifu2x-converter-cpp` doesn't support width and height. You'll also have to explicitly specify that the driver to be used is `waifu2x_converter`.
|
||||
To see a help page for driver-specific settings, use `-d` to select the driver and append `-- --help` as demonstrated below. This will print all driver-specific settings and descriptions.
|
||||
|
||||
```shell
|
||||
python video2x.py -i sample_input.mp4 -o sample_output.mp4 -m gpu -r 2 -d waifu2x_converter
|
||||
python video2x.py -d waifu2x_caffe -- --help
|
||||
```
|
||||
|
||||
### CPU
|
||||
---
|
||||
|
||||
Enlarge the video to 1920x1080 using the CPU. You may also use the `-r/--ratio` option. This is potentially much slower than using a GPU. The configuration file for this method is similar to the previous methods.
|
||||
## Recent Changes
|
||||
|
||||
```shell
|
||||
python video2x.py -i sample_input.mp4 -o sample_output.mp4 -m cpu --width=1920 --height=1080
|
||||
```
|
||||
### 4.0.0 (May 5, 2020)
|
||||
|
||||
- Added internationalization support
|
||||
- Added language zh_CN (简体中文)
|
||||
- Language will change automatically according to system locale settings
|
||||
- Added support for [Anime4KCPP](https://github.com/TianZerL/Anime4KCPP) in replacement for Anime4K (Java)
|
||||
- Driver-specific settings can now be specified in the command line by specifying them after a `--`
|
||||
- All driver-specific settings are parsed by the corresponding driver
|
||||
- Modularized driver wrappers in Video2X
|
||||
- Cleaned up some clutters in the code
|
||||
|
||||
### 3.2.0 (April 26, 2020)
|
||||
|
||||
- Added support for [SRMD-NCNN-Vulkan](https://github.com/nihui/srmd-ncnn-vulkan)
|
||||
|
||||
### 3.1.0 (February 26, 2020)
|
||||
|
||||
- Removed the redundant layer of multi-threading since multi-process has to be implemented for launching Windows PE files in sub-processes
|
||||
- Added support for graceful exit upon `KeyboardInterrupt` or termination signals
|
||||
- Other minor improvements such as replacing `' '.join(execute)` with `shlex.join(execute)`
|
||||
|
||||
### Setup Script 1.8.0 (May 5, 2020)
|
||||
|
||||
- Added support for Anime4KCPP
|
||||
|
||||
---
|
||||
|
||||
# Full Usage
|
||||
|
||||
## General Options
|
||||
## Video2X Options
|
||||
|
||||
### -h, --help
|
||||
show this help message and exit
|
||||
|
||||
## File Options
|
||||
|
||||
### -i INPUT, --input INPUT
|
||||
Source video file/directory (default: None)
|
||||
source video file/directory
|
||||
|
||||
### -o OUTPUT, --output OUTPUT
|
||||
Output video file/directory (default: None)
|
||||
output video file/directory
|
||||
|
||||
### -c CONFIG, --config CONFIG
|
||||
video2x config file path
|
||||
|
||||
### -v, --version
|
||||
display version, lawful information and exit
|
||||
|
||||
## Upscaling Options
|
||||
|
||||
### -m {cpu,gpu,cudnn}, --method {cpu,gpu,cudnn}
|
||||
Upscaling method (default: gpu)
|
||||
### -d DRIVER, --driver DRIVER
|
||||
upscaling driver (default: waifu2x_caffe)
|
||||
|
||||
### -d {waifu2x_caffe,waifu2x_converter}, --driver {waifu2x_caffe,waifu2x_converter}
|
||||
Waifu2x driver (default: waifu2x_caffe)
|
||||
Available options are:
|
||||
|
||||
### -y MODEL_DIR, --model_dir MODEL_DIR
|
||||
Folder containing model JSON files
|
||||
|
||||
### -t THREADS, --threads THREADS
|
||||
Number of threads to use for upscaling (default: 5)
|
||||
|
||||
### -c CONFIG, --config CONFIG
|
||||
Video2X config file location (default: video2x\bin\video2x.json)
|
||||
|
||||
### -b, --batch
|
||||
Enable batch mode (select all default values to questions)
|
||||
|
||||
## Scaling Options
|
||||
|
||||
### --width WIDTH
|
||||
Output video width
|
||||
|
||||
### --height HEIGHT
|
||||
Output video height
|
||||
- waifu2x_caffe
|
||||
- waifu2x_converter_cpp
|
||||
- waifu2x_ncnn_vulkan
|
||||
- srmd_ncnn_vulkan
|
||||
- anime4kcpp
|
||||
|
||||
### -r RATIO, --ratio RATIO
|
||||
Scaling 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)
|
||||
|
||||
---
|
||||
|
||||
@@ -217,22 +247,27 @@ https://www.gnu.org/licenses/gpl-3.0.txt
|
||||
|
||||

|
||||
|
||||
(C) 2018-2019 K4YT3X
|
||||
(C) 2018-2020 K4YT3X
|
||||
|
||||
## Credits
|
||||
|
||||
This project relies on the following software and projects.
|
||||
|
||||
- [FFmpeg]('https://www.ffmpeg.org/')
|
||||
- [FFmpeg](https://www.ffmpeg.org/)
|
||||
- [waifu2x-caffe](https://github.com/lltcggie/waifu2x-caffe)
|
||||
- [waifu2x-converter-cpp](https://github.com/DeadSix27/waifu2x-converter-cpp)
|
||||
- [waifu2x-ncnn-vulkan](https://github.com/nihui/waifu2x-ncnn-vulkan)
|
||||
- [srmd-ncnn-vulkan](https://github.com/nihui/srmd-ncnn-vulkan)
|
||||
- [Anime4KCPP](https://github.com/TianZerL/Anime4KCPP)
|
||||
|
||||
## Special Thanks
|
||||
|
||||
Appreciations given to the following contributors:
|
||||
Appreciations given to the following code contributors:
|
||||
|
||||
- @BrianPetkovsek
|
||||
- @SAT3LL
|
||||
|
||||
## Related Resources
|
||||
## Related Projects
|
||||
|
||||
- [Dandere2x](https://github.com/CardinalPanda/dandere2x): `Dandere2x` is a lossy video upscaler also built around `waifu2x`, but with video compression techniques to shorten the time needed to process a video.
|
||||
- [Dandere2x](https://github.com/CardinalPanda/dandere2x): A lossy video upscaler also built around `waifu2x`, but with video compression techniques to shorten the time needed to process a video.
|
||||
- [Waifu2x-Extension-GUI](https://github.com/AaronFeng753/Waifu2x-Extension-GUI): A similar project that focuses more and only on building a better graphical user interface. It is built using C++ and Qt5, and currently only supports the Windows platform.
|
||||
|
||||
1
_config.yml
Normal file
1
_config.yml
Normal file
@@ -0,0 +1 @@
|
||||
theme: jekyll-theme-slate
|
||||
@@ -1,13 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- code:utf-8 -*-
|
||||
"""
|
||||
Name: Video2X Exceptions
|
||||
Dev: K4YT3X
|
||||
Date Created: December 13, 2018
|
||||
Last Modified: March 19, 2019
|
||||
"""
|
||||
|
||||
|
||||
class ArgumentError(Exception):
|
||||
def __init__(self, message):
|
||||
super().__init__(message)
|
||||
307
bin/upscaler.py
307
bin/upscaler.py
@@ -1,307 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Video2X Upscaler
|
||||
Author: K4YT3X
|
||||
Date Created: December 10, 2018
|
||||
Last Modified: April 28, 2019
|
||||
|
||||
Licensed under the GNU General Public License Version 3 (GNU GPL v3),
|
||||
available at: https://www.gnu.org/licenses/gpl-3.0.txt
|
||||
|
||||
(C) 2018-2019 K4YT3X
|
||||
"""
|
||||
|
||||
from avalon_framework import Avalon
|
||||
from exceptions import *
|
||||
from ffmpeg import Ffmpeg
|
||||
from fractions import Fraction
|
||||
from image_cleaner import ImageCleaner
|
||||
from tqdm import tqdm
|
||||
from waifu2x_caffe import Waifu2xCaffe
|
||||
from waifu2x_converter import Waifu2xConverter
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class Upscaler:
|
||||
""" An instance of this class is a upscaler that will
|
||||
upscale all images in the given directory.
|
||||
|
||||
Raises:
|
||||
Exception -- all exceptions
|
||||
ArgumentError -- if argument is not valid
|
||||
"""
|
||||
|
||||
def __init__(self, input_video, output_video, method, waifu2x_settings, ffmpeg_settings):
|
||||
# mandatory arguments
|
||||
self.input_video = input_video
|
||||
self.output_video = output_video
|
||||
self.method = method
|
||||
self.waifu2x_settings = waifu2x_settings
|
||||
self.ffmpeg_settings = ffmpeg_settings
|
||||
|
||||
# optional arguments
|
||||
self.waifu2x_driver = 'waifu2x_caffe'
|
||||
self.scale_width = None
|
||||
self.scale_height = None
|
||||
self.scale_ratio = None
|
||||
self.model_dir = None
|
||||
self.threads = 5
|
||||
self.video2x_cache_directory = f'{tempfile.gettempdir()}\\video2x'
|
||||
self.image_format = 'png'
|
||||
self.preserve_frames = False
|
||||
|
||||
def create_temp_directories(self):
|
||||
"""create temporary directory
|
||||
"""
|
||||
self.extracted_frames = tempfile.mkdtemp(dir=self.video2x_cache_directory)
|
||||
Avalon.debug_info(f'Extracted frames are being saved to: {self.extracted_frames}')
|
||||
self.upscaled_frames = tempfile.mkdtemp(dir=self.video2x_cache_directory)
|
||||
Avalon.debug_info(f'Upscaled frames are being saved to: {self.upscaled_frames}')
|
||||
|
||||
def cleanup_temp_directories(self):
|
||||
"""delete temp directories when done
|
||||
"""
|
||||
if not self.preserve_frames:
|
||||
for directory in [self.extracted_frames, self.upscaled_frames]:
|
||||
try:
|
||||
# avalon framework cannot be used if python is shutting down
|
||||
# therefore, plain print is used
|
||||
print(f'Cleaning up cache directory: {directory}')
|
||||
shutil.rmtree(directory)
|
||||
except (OSError, FileNotFoundError):
|
||||
pass
|
||||
|
||||
def _check_arguments(self):
|
||||
# check if arguments are valid / all necessary argument
|
||||
# values are specified
|
||||
if not self.input_video:
|
||||
raise ArgumentError('You need to specify the video to process')
|
||||
elif (not self.scale_width or not self.scale_height) and not self.scale_ratio:
|
||||
raise ArgumentError('You must specify output video width and height or upscale factor')
|
||||
elif not self.output_video:
|
||||
raise ArgumentError('You need to specify the output video name')
|
||||
elif not self.method:
|
||||
raise ArgumentError('You need to specify the enlarging processing unit')
|
||||
|
||||
def _progress_bar(self, extracted_frames_directories):
|
||||
""" This method prints a progress bar
|
||||
|
||||
This method prints a progress bar by keeping track
|
||||
of the amount of frames in the input directory
|
||||
and the output directory. This is originally
|
||||
suggested by @ArmandBernard.
|
||||
"""
|
||||
# get number of extracted frames
|
||||
total_frames = 0
|
||||
for directory in extracted_frames_directories:
|
||||
total_frames += len([f for f in os.listdir(directory) if f[-4:] == '.png'])
|
||||
|
||||
with tqdm(total=total_frames, ascii=True, desc='Upscaling Progress') 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.
|
||||
previous_cycle_frames = 0
|
||||
while not self.progress_bar_exit_signal:
|
||||
|
||||
try:
|
||||
total_frames_upscaled = len([f for f in os.listdir(self.upscaled_frames) if f[-4:] == '.png'])
|
||||
delta = total_frames_upscaled - previous_cycle_frames
|
||||
previous_cycle_frames = total_frames_upscaled
|
||||
|
||||
# if upscaling is finished
|
||||
if total_frames_upscaled >= total_frames:
|
||||
return
|
||||
|
||||
# adds the detla into the progress bar
|
||||
progress_bar.update(delta)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
def _upscale_frames(self, w2):
|
||||
""" Upscale video frames with waifu2x-caffe
|
||||
|
||||
This function upscales all the frames extracted
|
||||
by ffmpeg using the waifu2x-caffe binary.
|
||||
|
||||
Arguments:
|
||||
w2 {Waifu2x Object} -- initialized waifu2x object
|
||||
"""
|
||||
|
||||
# progress bar thread exit signal
|
||||
self.progress_bar_exit_signal = False
|
||||
|
||||
# create a container for exceptions in threads
|
||||
# if this thread is not empty, then an exception has occured
|
||||
self.upscaler_exceptions = []
|
||||
|
||||
# it's easier to do multi-threading with waifu2x_converter
|
||||
# the number of threads can be passed directly to waifu2x_converter
|
||||
if self.waifu2x_driver == 'waifu2x_converter':
|
||||
|
||||
progress_bar = threading.Thread(target=self._progress_bar, args=([self.extracted_frames],))
|
||||
progress_bar.start()
|
||||
|
||||
w2.upscale(self.extracted_frames, self.upscaled_frames, self.scale_ratio, self.threads, self.image_format, self.upscaler_exceptions)
|
||||
for image in [f for f in os.listdir(self.upscaled_frames) if os.path.isfile(os.path.join(self.upscaled_frames, f))]:
|
||||
renamed = re.sub(f'_\[.*-.*\]\[x(\d+(\.\d+)?)\]\.{self.image_format}', f'.{self.image_format}', image)
|
||||
shutil.move(f'{self.upscaled_frames}\\{image}', f'{self.upscaled_frames}\\{renamed}')
|
||||
|
||||
self.progress_bar_exit_signal = True
|
||||
progress_bar.join()
|
||||
return
|
||||
|
||||
# create a container for all upscaler threads
|
||||
upscaler_threads = []
|
||||
|
||||
# list all images in the extracted frames
|
||||
frames = [os.path.join(self.extracted_frames, f) for f in os.listdir(self.extracted_frames) if os.path.isfile(os.path.join(self.extracted_frames, f))]
|
||||
|
||||
# if we have less images than threads,
|
||||
# create only the threads necessary
|
||||
if len(frames) < self.threads:
|
||||
self.threads = len(frames)
|
||||
|
||||
# create a directory for each thread and append directory
|
||||
# name into a list
|
||||
|
||||
thread_pool = []
|
||||
thread_directories = []
|
||||
for thread_id in range(self.threads):
|
||||
thread_directory = f'{self.extracted_frames}\\{str(thread_id)}'
|
||||
thread_directories.append(thread_directory)
|
||||
|
||||
# delete old directories and create new directories
|
||||
if os.path.isdir(thread_directory):
|
||||
shutil.rmtree(thread_directory)
|
||||
os.mkdir(thread_directory)
|
||||
|
||||
# append directory path into list
|
||||
thread_pool.append((thread_directory, thread_id))
|
||||
|
||||
# evenly distribute images into each directory
|
||||
# until there is none left in the directory
|
||||
for image in frames:
|
||||
# move image
|
||||
shutil.move(image, thread_pool[0][0])
|
||||
# rotate list
|
||||
thread_pool = thread_pool[-1:] + thread_pool[:-1]
|
||||
|
||||
# create threads and start them
|
||||
for thread_info in thread_pool:
|
||||
# create thread
|
||||
if self.scale_ratio:
|
||||
thread = threading.Thread(target=w2.upscale, args=(thread_info[0], self.upscaled_frames, self.scale_ratio, False, False, self.image_format, self.upscaler_exceptions))
|
||||
else:
|
||||
thread = threading.Thread(target=w2.upscale, args=(thread_info[0], self.upscaled_frames, False, self.scale_width, self.scale_height, self.image_format, self.upscaler_exceptions))
|
||||
thread.name = thread_info[1]
|
||||
|
||||
# add threads into the pool
|
||||
upscaler_threads.append(thread)
|
||||
|
||||
# start progress bar in a different thread
|
||||
progress_bar = threading.Thread(target=self._progress_bar, args=(thread_directories,))
|
||||
progress_bar.start()
|
||||
|
||||
# create the clearer and start it
|
||||
Avalon.debug_info('Starting upscaled image cleaner')
|
||||
image_cleaner = ImageCleaner(self.extracted_frames, self.upscaled_frames, len(upscaler_threads))
|
||||
image_cleaner.start()
|
||||
|
||||
# start all threads
|
||||
for thread in upscaler_threads:
|
||||
thread.start()
|
||||
|
||||
# wait for threads to finish
|
||||
for thread in upscaler_threads:
|
||||
thread.join()
|
||||
|
||||
# upscaling done, kill the clearer
|
||||
Avalon.debug_info('Killing upscaled image cleaner')
|
||||
image_cleaner.stop()
|
||||
|
||||
self.progress_bar_exit_signal = True
|
||||
|
||||
if len(self.upscaler_exceptions) != 0:
|
||||
raise(self.upscaler_exceptions[0])
|
||||
|
||||
def run(self):
|
||||
"""Main controller for Video2X
|
||||
|
||||
This function controls the flow of video conversion
|
||||
and handles all necessary functions.
|
||||
"""
|
||||
|
||||
# parse arguments for waifu2x
|
||||
# check argument sanity
|
||||
self._check_arguments()
|
||||
|
||||
# convert paths to absolute paths
|
||||
self.input_video = os.path.abspath(self.input_video)
|
||||
self.output_video = os.path.abspath(self.output_video)
|
||||
|
||||
# initialize objects for ffmpeg and waifu2x-caffe
|
||||
fm = Ffmpeg(self.ffmpeg_settings, self.image_format)
|
||||
|
||||
# initialize waifu2x driver
|
||||
if self.waifu2x_driver == 'waifu2x_caffe':
|
||||
w2 = Waifu2xCaffe(self.waifu2x_settings, self.method, self.model_dir)
|
||||
elif self.waifu2x_driver == 'waifu2x_converter':
|
||||
w2 = Waifu2xConverter(self.waifu2x_settings, self.model_dir)
|
||||
else:
|
||||
raise Exception(f'Unrecognized waifu2x driver: {self.waifu2x_driver}')
|
||||
|
||||
# extract frames from video
|
||||
fm.extract_frames(self.input_video, self.extracted_frames)
|
||||
|
||||
Avalon.info('Reading video information')
|
||||
video_info = fm.get_video_info(self.input_video)
|
||||
# analyze original video with ffprobe and retrieve framerate
|
||||
# width, height = info['streams'][0]['width'], info['streams'][0]['height']
|
||||
|
||||
# find index of video stream
|
||||
video_stream_index = None
|
||||
for stream in video_info['streams']:
|
||||
if stream['codec_type'] == 'video':
|
||||
video_stream_index = stream['index']
|
||||
break
|
||||
|
||||
# exit if no video stream found
|
||||
if video_stream_index is None:
|
||||
Avalon.error('Aborting: No video stream found')
|
||||
exit(1)
|
||||
|
||||
# get average frame rate of video stream
|
||||
framerate = float(Fraction(video_info['streams'][video_stream_index]['avg_frame_rate']))
|
||||
Avalon.info(f'Framerate: {framerate}')
|
||||
|
||||
# width/height will be coded width/height x upscale factor
|
||||
if self.scale_ratio:
|
||||
original_width = video_info['streams'][video_stream_index]['width']
|
||||
original_height = video_info['streams'][video_stream_index]['height']
|
||||
self.scale_width = int(self.scale_ratio * original_width)
|
||||
self.scale_height = int(self.scale_ratio * original_height)
|
||||
|
||||
# upscale images one by one using waifu2x
|
||||
Avalon.info('Starting to upscale extracted images')
|
||||
self._upscale_frames(w2)
|
||||
Avalon.info('Upscaling completed')
|
||||
|
||||
# frames to Video
|
||||
Avalon.info('Converting extracted frames into video')
|
||||
|
||||
# use user defined output size
|
||||
fm.convert_video(framerate, f'{self.scale_width}x{self.scale_height}', self.upscaled_frames)
|
||||
Avalon.info('Conversion completed')
|
||||
|
||||
# migrate audio tracks and subtitles
|
||||
Avalon.info('Migrating audio tracks and subtitles to upscaled video')
|
||||
fm.migrate_audio_tracks_subtitles(self.input_video, self.output_video, self.upscaled_frames)
|
||||
@@ -1,79 +0,0 @@
|
||||
{
|
||||
"waifu2x_caffe": {
|
||||
"waifu2x_caffe_path": "C:\\Users\\K4YT3X\\AppData\\Local\\video2x\\waifu2x-caffe\\waifu2x-caffe-cui.exe",
|
||||
"input_extention_list": null,
|
||||
"output_extention": null,
|
||||
"mode": "noise_scale",
|
||||
"scale_ratio": null,
|
||||
"scale_width": null,
|
||||
"scale_height": null,
|
||||
"noise_level": 3,
|
||||
"process": "gpu",
|
||||
"crop_size": 128,
|
||||
"output_quality": -1,
|
||||
"output_depth": 8,
|
||||
"batch_size": 1,
|
||||
"gpu": 0,
|
||||
"tta": 0,
|
||||
"input_path": null,
|
||||
"output_path": null,
|
||||
"model_dir": null,
|
||||
"crop_w": null,
|
||||
"crop_h": null
|
||||
},
|
||||
"waifu2x_converter": {
|
||||
"waifu2x_converter_path": "C:\\Users\\K4YT3X\\AppData\\Local\\video2x\\waifu2x-converter-cpp",
|
||||
"output-format": null,
|
||||
"png-compression": null,
|
||||
"image-quality": null,
|
||||
"block-size": null,
|
||||
"disable-gpu": null,
|
||||
"force-OpenCL": null,
|
||||
"processor": null,
|
||||
"jobs": null,
|
||||
"model-dir": null,
|
||||
"scale-ratio": null,
|
||||
"noise-level": 3,
|
||||
"mode": "noise-scale",
|
||||
"silent": true,
|
||||
"output": null,
|
||||
"input": null
|
||||
},
|
||||
"ffmpeg": {
|
||||
"ffmpeg_path": "C:\\Users\\K4YT3X\\AppData\\Local\\video2x\\ffmpeg-latest-win64-static\\bin",
|
||||
"video_to_frames": {
|
||||
"-qscale:v": null,
|
||||
"-hwaccel": "auto",
|
||||
"-y": true
|
||||
},
|
||||
"frames_to_video": {
|
||||
"input_options":{
|
||||
"-qscale:v": null,
|
||||
"-qscale:a": null,
|
||||
"-f": "image2"
|
||||
},
|
||||
"output_options":{
|
||||
"-vcodec": "libx264",
|
||||
"-crf": 17,
|
||||
"-b:v": null,
|
||||
"-pix_fmt": "yuv420p"
|
||||
},
|
||||
"-y": true
|
||||
},
|
||||
"migrating_tracks": {
|
||||
"output_options":{
|
||||
"-map": "0:v:0?",
|
||||
"-map": "1?",
|
||||
"-c": "copy",
|
||||
"-map": "-1:v?",
|
||||
"-pix_fmt": "yuv420p"
|
||||
},
|
||||
"-y": true
|
||||
}
|
||||
},
|
||||
"video2x": {
|
||||
"video2x_cache_directory": null,
|
||||
"image_format": "png",
|
||||
"preserve_frames": false
|
||||
}
|
||||
}
|
||||
358
bin/video2x.py
358
bin/video2x.py
@@ -1,358 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
|
||||
__ __ _ _ ___ __ __
|
||||
\ \ / / (_) | | |__ \ \ \ / /
|
||||
\ \ / / _ __| | ___ ___ ) | \ V /
|
||||
\ \/ / | | / _` | / _ \ / _ \ / / > <
|
||||
\ / | | | (_| | | __/ | (_) | / /_ / . \
|
||||
\/ |_| \__,_| \___| \___/ |____| /_/ \_\
|
||||
|
||||
|
||||
Name: Video2X Controller
|
||||
Author: K4YT3X
|
||||
Date Created: Feb 24, 2018
|
||||
Last Modified: April 28, 2019
|
||||
|
||||
Licensed under the GNU General Public License Version 3 (GNU GPL v3),
|
||||
available at: https://www.gnu.org/licenses/gpl-3.0.txt
|
||||
|
||||
(C) 2018-2019 K4YT3X
|
||||
|
||||
Video2X is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Video2X is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Description: Video2X is an automation software based on waifu2x image
|
||||
enlarging engine. It extracts frames from a video, enlarge it by a
|
||||
number of times without losing any details or quality, keeping lines
|
||||
smooth and edges sharp.
|
||||
"""
|
||||
from avalon_framework import Avalon
|
||||
from upscaler import Upscaler
|
||||
import argparse
|
||||
import GPUtil
|
||||
import json
|
||||
import os
|
||||
import psutil
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
|
||||
VERSION = '2.7.1'
|
||||
|
||||
# each thread might take up to 2.5 GB during initialization.
|
||||
# (system memory, not to be confused with GPU memory)
|
||||
SYS_MEM_PER_THREAD = 2.5
|
||||
GPU_MEM_PER_THREAD = 3.5
|
||||
|
||||
|
||||
def process_arguments():
|
||||
"""Processes CLI arguments
|
||||
|
||||
This function parses all arguments
|
||||
This allows users to customize options
|
||||
for the output video.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
|
||||
# video options
|
||||
file_options = parser.add_argument_group('File Options')
|
||||
file_options.add_argument('-i', '--input', help='Source video file/directory', action='store', required=True)
|
||||
file_options.add_argument('-o', '--output', help='Output video file/directory', action='store', required=True)
|
||||
|
||||
# upscaler options
|
||||
upscaler_options = parser.add_argument_group('Upscaler Options')
|
||||
upscaler_options.add_argument('-m', '--method', help='Upscaling method', action='store', default='gpu', choices=['cpu', 'gpu', 'cudnn'], required=True)
|
||||
upscaler_options.add_argument('-d', '--driver', help='Waifu2x driver', action='store', default='waifu2x_caffe', choices=['waifu2x_caffe', 'waifu2x_converter'])
|
||||
upscaler_options.add_argument('-y', '--model_dir', help='directory containing model JSON files', action='store')
|
||||
upscaler_options.add_argument('-t', '--threads', help='Number of threads to use for upscaling', action='store', type=int, default=1)
|
||||
upscaler_options.add_argument('-c', '--config', help='Video2X config file location', action='store', default=f'{os.path.dirname(os.path.abspath(sys.argv[0]))}\\video2x.json')
|
||||
upscaler_options.add_argument('-b', '--batch', help='Enable batch mode (select all default values to questions)', action='store_true')
|
||||
|
||||
# scaling options
|
||||
scaling_options = parser.add_argument_group('Scaling Options')
|
||||
scaling_options.add_argument('--width', help='Output video width', action='store', type=int)
|
||||
scaling_options.add_argument('--height', help='Output video height', action='store', type=int)
|
||||
scaling_options.add_argument('-r', '--ratio', help='Scaling ratio', action='store', type=float)
|
||||
|
||||
# parse arguments
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def print_logo():
|
||||
print('__ __ _ _ ___ __ __')
|
||||
print('\\ \\ / / (_) | | |__ \\ \\ \\ / /')
|
||||
print(' \\ \\ / / _ __| | ___ ___ ) | \\ V /')
|
||||
print(' \\ \\/ / | | / _` | / _ \\ / _ \\ / / > <')
|
||||
print(' \\ / | | | (_| | | __/ | (_) | / /_ / . \\')
|
||||
print(' \\/ |_| \\__,_| \\___| \\___/ |____| /_/ \\_\\')
|
||||
print('\n Video2X Video Enlarger')
|
||||
spaces = ((44 - len(f'Version {VERSION}')) // 2) * ' '
|
||||
print(f'{Avalon.FM.BD}\n{spaces} Version {VERSION}\n{Avalon.FM.RST}')
|
||||
|
||||
|
||||
def check_memory():
|
||||
""" Check usable system memory
|
||||
Warn the user if insufficient memory is available for
|
||||
the number of threads that the user have chosen.
|
||||
"""
|
||||
|
||||
memory_status = []
|
||||
# get system available memory
|
||||
system_memory_available = psutil.virtual_memory().available / (1024 ** 3)
|
||||
memory_status.append(('system', system_memory_available))
|
||||
|
||||
# check if Nvidia-smi is available
|
||||
# GPUtil requires nvidia-smi.exe to interact with GPU
|
||||
if args.method == 'gpu' or args.method == 'cudnn':
|
||||
if not os.path.isfile('C:\\Program Files\\NVIDIA Corporation\\NVSMI\\nvidia-smi.exe'):
|
||||
# Nvidia System Management Interface not available
|
||||
Avalon.warning('Nvidia-smi not available, skipping available memory check')
|
||||
Avalon.warning('If you experience error \"cudaSuccess out of memory\", try reducing number of threads you\'re using')
|
||||
else:
|
||||
try:
|
||||
# "0" is GPU ID. Both waifu2x drivers use the first GPU available, therefore only 0 makes sense
|
||||
gpu_memory_available = (GPUtil.getGPUs()[0].memoryTotal - GPUtil.getGPUs()[0].memoryUsed) / 1024
|
||||
memory_status.append(('GPU', gpu_memory_available))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# go though each checkable memory type and check availability
|
||||
for memory_type, memory_available in memory_status:
|
||||
|
||||
if memory_type == 'system':
|
||||
mem_per_thread = SYS_MEM_PER_THREAD
|
||||
else:
|
||||
mem_per_thread = GPU_MEM_PER_THREAD
|
||||
|
||||
# if user doesn't even have enough memory to run even one thread
|
||||
if memory_available < mem_per_thread:
|
||||
Avalon.warning(f'You might have insufficient amount of {memory_type} memory available to run this program ({memory_available} GB)')
|
||||
Avalon.warning('Proceed with caution')
|
||||
if args.threads > 1:
|
||||
if Avalon.ask('Reduce number of threads to avoid crashing?', default=True, batch=args.batch):
|
||||
args.threads = 1
|
||||
# if memory available is less than needed, warn the user
|
||||
elif memory_available < (mem_per_thread * args.threads):
|
||||
Avalon.warning(f'Each waifu2x-caffe thread will require up to {SYS_MEM_PER_THREAD} GB of system memory')
|
||||
Avalon.warning(f'You demanded {args.threads} threads to be created, but you only have {round(memory_available, 4)} GB {memory_type} memory available')
|
||||
Avalon.warning(f'{mem_per_thread * args.threads} GB of {memory_type} memory is recommended for {args.threads} threads')
|
||||
Avalon.warning(f'With your current amount of {memory_type} memory available, {int(memory_available // mem_per_thread)} threads is recommended')
|
||||
|
||||
# ask the user if he / she wants to change to the recommended
|
||||
# number of threads
|
||||
if Avalon.ask('Change to the recommended value?', default=True, batch=args.batch):
|
||||
args.threads = int(memory_available // mem_per_thread)
|
||||
else:
|
||||
Avalon.warning('Proceed with caution')
|
||||
|
||||
|
||||
def read_config(config_file):
|
||||
""" Reads configuration file
|
||||
|
||||
Returns a dictionary read by JSON.
|
||||
"""
|
||||
with open(config_file, 'r') as raw_config:
|
||||
config = json.load(raw_config)
|
||||
return config
|
||||
|
||||
|
||||
def absolutify_paths(config):
|
||||
""" Check to see if paths to binaries are absolute
|
||||
|
||||
This function checks if paths to binary files are absolute.
|
||||
If not, then absolutify the path.
|
||||
|
||||
Arguments:
|
||||
config {dict} -- configuration file dictionary
|
||||
|
||||
Returns:
|
||||
dict -- configuration file dictionary
|
||||
"""
|
||||
current_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
|
||||
|
||||
# check waifu2x-caffe path
|
||||
if not re.match('^[a-z]:', config['waifu2x_caffe']['waifu2x_caffe_path'], re.IGNORECASE):
|
||||
config['waifu2x_caffe']['waifu2x_caffe_path'] = f'{current_directory}\\{config["waifu2x_caffe"]["waifu2x_caffe_path"]}'
|
||||
|
||||
# check waifu2x-converter-cpp path
|
||||
if not re.match('^[a-z]:', config['waifu2x_converter']['waifu2x_converter_path'], re.IGNORECASE):
|
||||
config['waifu2x_converter']['waifu2x_converter_path'] = f'{current_directory}\\{config["waifu2x_converter"]["waifu2x_converter_path"]}'
|
||||
|
||||
# check ffmpeg path
|
||||
if not re.match('^[a-z]:', config['ffmpeg']['ffmpeg_path'], re.IGNORECASE):
|
||||
config['ffmpeg']['ffmpeg_path'] = f'{current_directory}\\{config["ffmpeg"]["ffmpeg_path"]}'
|
||||
|
||||
# check video2x cache path
|
||||
if config['video2x']['video2x_cache_directory']:
|
||||
if not re.match('^[a-z]:', config['video2x']['video2x_cache_directory'], re.IGNORECASE):
|
||||
config['video2x']['video2x_cache_directory'] = f'{current_directory}\\{config["video2x"]["video2x_cache_directory"]}'
|
||||
|
||||
return config
|
||||
|
||||
|
||||
# /////////////////// Execution /////////////////// #
|
||||
|
||||
# this is not a library
|
||||
if __name__ != '__main__':
|
||||
Avalon.error('This file cannot be imported')
|
||||
raise ImportError(f'{__file__} cannot be imported')
|
||||
|
||||
print_logo()
|
||||
|
||||
# process CLI arguments
|
||||
args = process_arguments()
|
||||
|
||||
# arguments sanity check
|
||||
if args.driver == 'waifu2x_converter' and args.width and args.height:
|
||||
Avalon.error('Waifu2x Converter CPP accepts only scaling ratio')
|
||||
exit(1)
|
||||
if (args.width or args.height) and args.ratio:
|
||||
Avalon.error('You can only specify either scaling ratio or output width and height')
|
||||
exit(1)
|
||||
if (args.width and not args.height) or (not args.width and args.height):
|
||||
Avalon.error('You must specify both width and height')
|
||||
exit(1)
|
||||
|
||||
# check available memory
|
||||
check_memory()
|
||||
|
||||
# read configurations from JSON
|
||||
config = read_config(args.config)
|
||||
config = absolutify_paths(config)
|
||||
|
||||
# load waifu2x configuration
|
||||
if args.driver == 'waifu2x_caffe':
|
||||
waifu2x_settings = config['waifu2x_caffe']
|
||||
if not os.path.isfile(waifu2x_settings['waifu2x_caffe_path']):
|
||||
Avalon.error('Specified waifu2x-caffe directory doesn\'t exist')
|
||||
Avalon.error('Please check the configuration file settings')
|
||||
raise FileNotFoundError(waifu2x_settings['waifu2x_caffe_path'])
|
||||
elif args.driver == 'waifu2x_converter':
|
||||
waifu2x_settings = config['waifu2x_converter']
|
||||
if not os.path.isdir(waifu2x_settings['waifu2x_converter_path']):
|
||||
Avalon.error('Specified waifu2x-conver-cpp directory doesn\'t exist')
|
||||
Avalon.error('Please check the configuration file settings')
|
||||
raise FileNotFoundError(waifu2x_settings['waifu2x_converter_path'])
|
||||
|
||||
# check if waifu2x path is valid
|
||||
|
||||
|
||||
# read FFMPEG configuration
|
||||
ffmpeg_settings = config['ffmpeg']
|
||||
|
||||
# load video2x settings
|
||||
video2x_cache_directory = config['video2x']['video2x_cache_directory']
|
||||
image_format = config['video2x']['image_format'].lower()
|
||||
preserve_frames = config['video2x']['preserve_frames']
|
||||
|
||||
# create temp directories if they don't exist
|
||||
if not video2x_cache_directory:
|
||||
video2x_cache_directory = f'{tempfile.gettempdir()}\\video2x'
|
||||
|
||||
if video2x_cache_directory and not os.path.isdir(video2x_cache_directory):
|
||||
if not os.path.isfile(video2x_cache_directory) and not os.path.islink(video2x_cache_directory):
|
||||
Avalon.warning(f'Specified cache directory {video2x_cache_directory} does not exist')
|
||||
if Avalon.ask('Create directory?', default=True, batch=args.batch):
|
||||
if os.mkdir(video2x_cache_directory) is None:
|
||||
Avalon.info(f'{video2x_cache_directory} created')
|
||||
else:
|
||||
Avalon.error(f'Unable to create {video2x_cache_directory}')
|
||||
Avalon.error('Aborting...')
|
||||
exit(1)
|
||||
else:
|
||||
Avalon.error('Specified cache directory is a file/link')
|
||||
Avalon.error('Unable to continue, exiting...')
|
||||
exit(1)
|
||||
|
||||
|
||||
# start execution
|
||||
try:
|
||||
# start timer
|
||||
begin_time = time.time()
|
||||
|
||||
# if input specified is a single file
|
||||
if os.path.isfile(args.input):
|
||||
""" Upscale single video file """
|
||||
Avalon.info(f'Upscaling single video file: {args.input}')
|
||||
|
||||
# check for input output format mismatch
|
||||
if os.path.isdir(args.output):
|
||||
Avalon.error('Input and output path type mismatch')
|
||||
Avalon.error('Input is single file but output is directory')
|
||||
raise Exception('input output path type mismatch')
|
||||
if not re.search('.*\..*$', args.output):
|
||||
Avalon.error('No suffix found in output file path')
|
||||
Avalon.error('Suffix must be specified for FFmpeg')
|
||||
raise Exception('No suffix specified')
|
||||
|
||||
upscaler = Upscaler(input_video=args.input, output_video=args.output, method=args.method, waifu2x_settings=waifu2x_settings, ffmpeg_settings=ffmpeg_settings)
|
||||
|
||||
# set optional options
|
||||
upscaler.waifu2x_driver = args.driver
|
||||
upscaler.scale_width = args.width
|
||||
upscaler.scale_height = args.height
|
||||
upscaler.scale_ratio = args.ratio
|
||||
upscaler.model_dir = args.model_dir
|
||||
upscaler.threads = args.threads
|
||||
upscaler.video2x_cache_directory = video2x_cache_directory
|
||||
upscaler.image_format = image_format
|
||||
upscaler.preserve_frames = preserve_frames
|
||||
|
||||
# run upscaler
|
||||
upscaler.create_temp_directories()
|
||||
upscaler.run()
|
||||
upscaler.cleanup_temp_directories()
|
||||
|
||||
# if input specified is a directory
|
||||
elif os.path.isdir(args.input):
|
||||
""" Upscale videos in a directory """
|
||||
Avalon.info(f'Upscaling videos in directory: {args.input}')
|
||||
for input_video in [f for f in os.listdir(args.input) if os.path.isfile(os.path.join(args.input, f))]:
|
||||
output_video = f'{args.output}\\{input_video}'
|
||||
upscaler = Upscaler(input_video=os.path.join(args.input, input_video), output_video=output_video, method=args.method, waifu2x_settings=waifu2x_settings, ffmpeg_settings=ffmpeg_settings)
|
||||
|
||||
# set optional options
|
||||
upscaler.waifu2x_driver = args.driver
|
||||
upscaler.scale_width = args.width
|
||||
upscaler.scale_height = args.height
|
||||
upscaler.scale_ratio = args.ratio
|
||||
upscaler.model_dir = args.model_dir
|
||||
upscaler.threads = args.threads
|
||||
upscaler.video2x_cache_directory = video2x_cache_directory
|
||||
upscaler.image_format = image_format
|
||||
upscaler.preserve_frames = preserve_frames
|
||||
|
||||
# run upscaler
|
||||
upscaler.create_temp_directories()
|
||||
upscaler.run()
|
||||
upscaler.cleanup_temp_directories()
|
||||
else:
|
||||
Avalon.error('Input path is neither a file nor a directory')
|
||||
raise FileNotFoundError(f'{args.input} is neither file nor directory')
|
||||
|
||||
Avalon.info(f'Program completed, taking {round((time.time() - begin_time), 5)} seconds')
|
||||
except Exception:
|
||||
Avalon.error('An exception has occurred')
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
# remove Video2X Cache directory
|
||||
try:
|
||||
if not preserve_frames:
|
||||
shutil.rmtree(video2x_cache_directory)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
@@ -1,233 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Video2X Setup Script
|
||||
Author: K4YT3X
|
||||
Date Created: November 28, 2018
|
||||
Last Modified: April 28, 2019
|
||||
|
||||
Licensed under the GNU General Public License Version 3 (GNU GPL v3),
|
||||
available at: https://www.gnu.org/licenses/gpl-3.0.txt
|
||||
|
||||
(C) 2018-2019 K4YT3X
|
||||
|
||||
Description: This script helps installing all dependencies of video2x
|
||||
and generates a configuration for it.
|
||||
|
||||
Installation Details:
|
||||
- ffmpeg: %LOCALAPPDATA%\\video2x\\ffmpeg
|
||||
- waifu2x-caffe: %LOCALAPPDATA%\\video2x\\waifu2x-caffe
|
||||
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
import zipfile
|
||||
|
||||
# Requests doesn't come with windows, therefore
|
||||
# it will be installed as a dependency and imported
|
||||
# later in the script.
|
||||
# import requests
|
||||
|
||||
VERSION = '1.2.1'
|
||||
|
||||
|
||||
def process_arguments():
|
||||
"""Processes CLI arguments
|
||||
"""
|
||||
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
|
||||
# video options
|
||||
general_options = parser.add_argument_group('General Options')
|
||||
general_options.add_argument('-d', '--driver', help='driver to download and configure', action='store', choices=['all', 'waifu2x_caffe', 'waifu2x_converter'], default='all')
|
||||
|
||||
# parse arguments
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
class Video2xSetup:
|
||||
""" 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.
|
||||
"""
|
||||
|
||||
def __init__(self, driver, download_python_modules):
|
||||
self.driver = driver
|
||||
self.download_python_modules = download_python_modules
|
||||
self.trash = []
|
||||
|
||||
def run(self):
|
||||
if self.download_python_modules:
|
||||
print('\nInstalling Python libraries')
|
||||
self._install_python_requirements()
|
||||
|
||||
print('\nInstalling FFMPEG')
|
||||
self._install_ffmpeg()
|
||||
|
||||
if self.driver == 'all':
|
||||
self._install_waifu2x_caffe()
|
||||
self._install_waifu2x_converter_cpp()
|
||||
elif self.driver == 'waifu2x_caffe':
|
||||
self._install_waifu2x_caffe()
|
||||
elif self.driver == 'waifu2x_converter':
|
||||
self._install_waifu2x_converter_cpp()
|
||||
|
||||
print('\nGenerating Video2X configuration file')
|
||||
self._generate_config()
|
||||
|
||||
print('\nCleaning up temporary files')
|
||||
self._cleanup()
|
||||
|
||||
def _install_python_requirements(self):
|
||||
""" Read requirements.txt and return its content
|
||||
"""
|
||||
with open('requirements.txt', 'r') as req:
|
||||
for line in req:
|
||||
package = line.split('==')[0]
|
||||
pip_install(package)
|
||||
|
||||
def _cleanup(self):
|
||||
""" Cleanup all the temp files downloaded
|
||||
"""
|
||||
for file in self.trash:
|
||||
try:
|
||||
print(f'Deleting: {file}')
|
||||
os.remove(file)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
def _install_ffmpeg(self):
|
||||
""" Install FFMPEG
|
||||
"""
|
||||
latest_release = 'https://ffmpeg.zeranoe.com/builds/win64/static/ffmpeg-latest-win64-static.zip'
|
||||
|
||||
ffmpeg_zip = download(latest_release, tempfile.gettempdir())
|
||||
self.trash.append(ffmpeg_zip)
|
||||
|
||||
with zipfile.ZipFile(ffmpeg_zip) as zipf:
|
||||
zipf.extractall(f'{os.getenv("localappdata")}\\video2x')
|
||||
|
||||
def _install_waifu2x_caffe(self):
|
||||
""" Install waifu2x_caffe
|
||||
"""
|
||||
print('\nInstalling waifu2x-caffe')
|
||||
import requests
|
||||
|
||||
# Get latest release of waifu2x-caffe via GitHub API
|
||||
latest_release = json.loads(requests.get('https://api.github.com/repos/lltcggie/waifu2x-caffe/releases/latest').content)
|
||||
|
||||
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(f'{os.getenv("localappdata")}\\video2x')
|
||||
|
||||
def _install_waifu2x_converter_cpp(self):
|
||||
""" Install waifu2x_caffe
|
||||
"""
|
||||
print('\nInstalling waifu2x-converter-cpp')
|
||||
import re
|
||||
import requests
|
||||
|
||||
# Get latest release of waifu2x-caffe via GitHub API
|
||||
latest_release = json.loads(requests.get('https://api.github.com/repos/DeadSix27/waifu2x-converter-cpp/releases/latest').content)
|
||||
|
||||
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(f'{os.getenv("localappdata")}\\video2x\\waifu2x-converter-cpp')
|
||||
|
||||
def _generate_config(self):
|
||||
""" Generate video2x config
|
||||
"""
|
||||
# Open current video2x.json file as template
|
||||
with open('video2x.json', 'r') as template:
|
||||
template_dict = json.load(template)
|
||||
template.close()
|
||||
|
||||
local_app_data = os.getenv('localappdata')
|
||||
|
||||
# configure only the specified drivers
|
||||
if self.driver == 'all':
|
||||
template_dict['waifu2x_caffe']['waifu2x_caffe_path'] = f'{local_app_data}\\video2x\\waifu2x-caffe\\waifu2x-caffe-cui.exe'
|
||||
template_dict['waifu2x_converter']['waifu2x_converter_path'] = f'{local_app_data}\\video2x\\waifu2x-converter-cpp'
|
||||
elif self.driver == 'waifu2x_caffe':
|
||||
template_dict['waifu2x_caffe']['waifu2x_caffe_path'] = f'{local_app_data}\\video2x\\waifu2x-caffe\\waifu2x-caffe-cui.exe'
|
||||
elif self.driver == 'waifu2x_converter':
|
||||
template_dict['waifu2x_converter']['waifu2x_converter_path'] = f'{local_app_data}\\video2x\\waifu2x-converter-cpp'
|
||||
|
||||
template_dict['ffmpeg']['ffmpeg_path'] = f'{local_app_data}\\video2x\\ffmpeg-latest-win64-static\\bin'
|
||||
template_dict['video2x']['video2x_cache_directory'] = None
|
||||
template_dict['video2x']['preserve_frames'] = False
|
||||
|
||||
# Write configuration into file
|
||||
with open('video2x.json', 'w') as config:
|
||||
json.dump(template_dict, config, indent=4)
|
||||
config.close()
|
||||
|
||||
|
||||
def download(url, save_path, chunk_size=4096):
|
||||
""" Download file to local with requests library
|
||||
"""
|
||||
from tqdm import tqdm
|
||||
import requests
|
||||
|
||||
output_file = f'{save_path}\\{url.split("/")[-1]}'
|
||||
print(f'Downloading: {url}')
|
||||
print(f'Chunk size: {chunk_size}')
|
||||
print(f'Saving to: {output_file}')
|
||||
|
||||
stream = requests.get(url, stream=True)
|
||||
total_size = int(stream.headers['content-length'])
|
||||
|
||||
# Write content into file
|
||||
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:
|
||||
output.write(chunk)
|
||||
progress_bar.update(len(chunk))
|
||||
|
||||
return output_file
|
||||
|
||||
|
||||
def pip_install(package):
|
||||
""" 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(['python', '-m', 'pip', 'install', '-U', package]).returncode
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
args = process_arguments()
|
||||
print('Video2X Setup Script')
|
||||
print(f'Version: {VERSION}')
|
||||
|
||||
# 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')
|
||||
download_python_modules = False
|
||||
|
||||
setup = Video2xSetup(args.driver, download_python_modules)
|
||||
setup.run()
|
||||
print('\nScript finished successfully')
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
print('An error has occurred')
|
||||
print('Video2X Automatic Setup has failed')
|
||||
exit(1)
|
||||
@@ -1,93 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Waifu2x Caffe Driver
|
||||
Author: K4YT3X
|
||||
Date Created: Feb 24, 2018
|
||||
Last Modified: April 28, 2019
|
||||
|
||||
Description: This class is a high-level wrapper
|
||||
for waifu2x-caffe.
|
||||
"""
|
||||
from avalon_framework import Avalon
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
|
||||
class Waifu2xCaffe:
|
||||
"""This class communicates with waifu2x cui engine
|
||||
|
||||
An object will be created for this class, containing information
|
||||
about the binary address and the processing method. When being called
|
||||
by the main program, other detailed information will be passed to
|
||||
the upscale function.
|
||||
"""
|
||||
|
||||
def __init__(self, waifu2x_settings, process, model_dir):
|
||||
self.waifu2x_settings = waifu2x_settings
|
||||
self.waifu2x_settings['process'] = process
|
||||
self.waifu2x_settings['model_dir'] = model_dir
|
||||
|
||||
# arguments passed through command line overwrites config file values
|
||||
self.process = process
|
||||
self.model_dir = model_dir
|
||||
self.print_lock = threading.Lock()
|
||||
|
||||
def upscale(self, input_directory, output_directory, scale_ratio, scale_width, scale_height, image_format, upscaler_exceptions):
|
||||
"""This is the core function for WAIFU2X class
|
||||
|
||||
Arguments:
|
||||
input_directory {string} -- source directory path
|
||||
output_directory {string} -- output directory path
|
||||
width {int} -- output video width
|
||||
height {int} -- output video height
|
||||
"""
|
||||
|
||||
try:
|
||||
# overwrite config file settings
|
||||
self.waifu2x_settings['input_path'] = input_directory
|
||||
self.waifu2x_settings['output_path'] = output_directory
|
||||
|
||||
if scale_ratio:
|
||||
self.waifu2x_settings['scale_ratio'] = scale_ratio
|
||||
elif scale_width and scale_height:
|
||||
self.waifu2x_settings['scale_width'] = scale_width
|
||||
self.waifu2x_settings['scale_height'] = scale_height
|
||||
|
||||
self.waifu2x_settings['output_extention'] = image_format
|
||||
|
||||
# print thread start message
|
||||
self.print_lock.acquire()
|
||||
Avalon.debug_info(f'[upscaler] Thread {threading.current_thread().name} started')
|
||||
self.print_lock.release()
|
||||
|
||||
# list to be executed
|
||||
execute = []
|
||||
|
||||
execute.append(self.waifu2x_settings['waifu2x_caffe_path'])
|
||||
for key in self.waifu2x_settings.keys():
|
||||
|
||||
value = self.waifu2x_settings[key]
|
||||
|
||||
# is executable key or null or None means that leave this option out (keep default)
|
||||
if key == 'waifu2x_caffe_path' or value is None or value is False:
|
||||
continue
|
||||
else:
|
||||
if len(key) == 1:
|
||||
execute.append(f'-{key}')
|
||||
else:
|
||||
execute.append(f'--{key}')
|
||||
execute.append(str(value))
|
||||
|
||||
Avalon.debug_info(f'Executing: {execute}')
|
||||
completed_command = subprocess.run(execute, check=True)
|
||||
|
||||
# print thread exiting message
|
||||
self.print_lock.acquire()
|
||||
Avalon.debug_info(f'[upscaler] Thread {threading.current_thread().name} exiting')
|
||||
self.print_lock.release()
|
||||
|
||||
# return command execution return code
|
||||
return completed_command.returncode
|
||||
except Exception as e:
|
||||
upscaler_exceptions.append(e)
|
||||
@@ -1,99 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Waifu2x Converter CPP Driver
|
||||
Author: K4YT3X
|
||||
Date Created: February 8, 2019
|
||||
Last Modified: April 28, 2019
|
||||
|
||||
Description: This class is a high-level wrapper
|
||||
for waifu2x-converter-cpp.
|
||||
"""
|
||||
from avalon_framework import Avalon
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
|
||||
class Waifu2xConverter:
|
||||
"""This class communicates with waifu2x cui engine
|
||||
|
||||
An object will be created for this class, containing information
|
||||
about the binary address and the processing method. When being called
|
||||
by the main program, other detailed information will be passed to
|
||||
the upscale function.
|
||||
"""
|
||||
|
||||
def __init__(self, waifu2x_settings, model_dir):
|
||||
self.waifu2x_settings = waifu2x_settings
|
||||
self.waifu2x_settings['model_dir'] = model_dir
|
||||
self.print_lock = threading.Lock()
|
||||
|
||||
def upscale(self, input_directory, output_directory, scale_ratio, jobs, image_format, upscaler_exceptions):
|
||||
""" Waifu2x Converter Driver Upscaler
|
||||
This method executes the upscaling of extracted frames.
|
||||
|
||||
Arguments:
|
||||
input_directory {string} -- source directory path
|
||||
output_directory {string} -- output directory path
|
||||
scale_ratio {int} -- frames' scale ratio
|
||||
threads {int} -- number of threads
|
||||
"""
|
||||
|
||||
try:
|
||||
# overwrite config file settings
|
||||
self.waifu2x_settings['input'] = input_directory
|
||||
self.waifu2x_settings['output'] = output_directory
|
||||
|
||||
# temporary fix for https://github.com/DeadSix27/waifu2x-converter-cpp/issues/109
|
||||
"""
|
||||
self.waifu2x_settings['i'] = input_directory
|
||||
self.waifu2x_settings['o'] = output_directory
|
||||
self.waifu2x_settings['input'] = None
|
||||
self.waifu2x_settings['output'] = None
|
||||
"""
|
||||
|
||||
self.waifu2x_settings['scale-ratio'] = scale_ratio
|
||||
self.waifu2x_settings['jobs'] = jobs
|
||||
self.waifu2x_settings['output-format'] = image_format
|
||||
|
||||
# models_rgb must be specified manually for waifu2x-converter-cpp
|
||||
# if it's not specified in the arguments, create automatically
|
||||
if self.waifu2x_settings['model-dir'] is None:
|
||||
self.waifu2x_settings['model-dir'] = f'{self.waifu2x_settings["waifu2x_converter_path"]}\\models_rgb'
|
||||
|
||||
# print thread start message
|
||||
self.print_lock.acquire()
|
||||
Avalon.debug_info(f'[upscaler] Thread {threading.current_thread().name} started')
|
||||
self.print_lock.release()
|
||||
|
||||
# list to be executed
|
||||
execute = []
|
||||
|
||||
for key in self.waifu2x_settings.keys():
|
||||
|
||||
value = self.waifu2x_settings[key]
|
||||
|
||||
# the key doesn't need to be passed in this case
|
||||
if key == 'waifu2x_converter_path':
|
||||
execute.append(f'{str(value)}\\waifu2x-converter-cpp.exe')
|
||||
|
||||
# null or None means that leave this option out (keep default)
|
||||
elif value is None or value is False:
|
||||
continue
|
||||
else:
|
||||
if len(key) == 1:
|
||||
execute.append(f'-{key}')
|
||||
else:
|
||||
execute.append(f'--{key}')
|
||||
|
||||
# true means key is an option
|
||||
if value is True:
|
||||
continue
|
||||
|
||||
execute.append(str(value))
|
||||
|
||||
Avalon.debug_info(f'Executing: {execute}')
|
||||
return subprocess.run(execute, check=True).returncode
|
||||
|
||||
except Exception as e:
|
||||
upscaler_exceptions.append(e)
|
||||
92
src/build.ps1
Normal file
92
src/build.ps1
Normal file
@@ -0,0 +1,92 @@
|
||||
<#
|
||||
Name: Video2X Build Script
|
||||
Creator: K4YT3X
|
||||
Date Created: May 6, 2020
|
||||
Last Modified: May 7, 2020
|
||||
|
||||
Description: A PowerShell script that will build Video2X
|
||||
executable (PE) releases automatically using PyInstaller.
|
||||
This script is currently only tuned for K4YT3X's environment.
|
||||
|
||||
To start a PowerShell session with execution policy bypass
|
||||
powershell –ExecutionPolicy Bypass
|
||||
#>
|
||||
|
||||
if ($args.count -ne 1){
|
||||
Write-Host -ForegroundColor White "Usage:`n .\build.ps1 VIDEO2X_VERSION"
|
||||
Exit
|
||||
}
|
||||
|
||||
# version number
|
||||
$SCRIPT_VERSION = "1.0.1"
|
||||
$VIDEO2X_VERSION = $args[0]
|
||||
|
||||
Write-Host -ForegroundColor White "Video2X Building Script Version $($SCRIPT_VERSION)
|
||||
Starting to build Video2X release packages
|
||||
Building Video2X release $($VIDEO2X_VERSION)"
|
||||
|
||||
# build Video2X CLI
|
||||
Write-Host -ForegroundColor White "`nBuilding Video2X CLI"
|
||||
pyinstaller --noconfirm --log-level=WARN `
|
||||
--onefile `
|
||||
--add-data="wrappers;wrappers" `
|
||||
--icon="images\video2x.ico" `
|
||||
video2x.py
|
||||
|
||||
# build Video2X GUI
|
||||
Write-Host -ForegroundColor White "`nBuilding Video2X GUI"
|
||||
pyinstaller --noconfirm --log-level=WARN `
|
||||
--onefile `
|
||||
--add-data="images;images" `
|
||||
--add-data="locale;locale" `
|
||||
--add-data="video2x_gui.ui;." `
|
||||
--add-data="wrappers;wrappers" `
|
||||
--icon="images\video2x.ico" `
|
||||
video2x_gui.py
|
||||
|
||||
# build setup script
|
||||
Write-Host -ForegroundColor White "`nBuilding Video2X setup script"
|
||||
pyinstaller --noconfirm --log-level=WARN `
|
||||
--onefile `
|
||||
--icon="images\video2x.ico" `
|
||||
video2x_setup.py
|
||||
|
||||
# remove old builds if found
|
||||
if (Test-Path "$($VIDEO2X_VERSION)" -PathType any) {
|
||||
Remove-Item -path "$($VIDEO2X_VERSION)" -recurse
|
||||
}
|
||||
|
||||
# create build directory
|
||||
New-Item "$($VIDEO2X_VERSION)" -ItemType Directory
|
||||
|
||||
# copy files into corresponding builds
|
||||
# full edition
|
||||
Write-Host -ForegroundColor White "`nCreating full package"
|
||||
New-Item "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-full" -ItemType Directory
|
||||
Copy-Item "dist\video2x.exe" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-full\"
|
||||
Copy-Item "dist\video2x_gui.exe" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-full\"
|
||||
Copy-Item -Path "$env:LOCALAPPDATA\video2x" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-full\dependencies" -Recurse
|
||||
|
||||
# overwrite paths to relative paths
|
||||
(Get-Content "video2x.yaml").replace("%LOCALAPPDATA%\video2x", "dependencies") | Set-Content "video2x.yaml.relative"
|
||||
Move-Item "video2x.yaml.relative" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-full\video2x.yaml"
|
||||
|
||||
# light edition
|
||||
Write-Host -ForegroundColor White "`nCreating light package"
|
||||
New-Item "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-light" -ItemType Directory
|
||||
Copy-Item "dist\video2x.exe" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-light\"
|
||||
Copy-Item "dist\video2x_gui.exe" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-light\"
|
||||
Copy-Item "dist\video2x_setup.exe" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-light\"
|
||||
Copy-Item "video2x.yaml" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-light\"
|
||||
Copy-Item "requirements.txt" -Destination "$($VIDEO2X_VERSION)\video2x-$($VIDEO2X_VERSION)-win32-light\"
|
||||
|
||||
# clean up temporary files
|
||||
Write-Host -ForegroundColor White "`nDeleting temporary files"
|
||||
$pathsToRemove = "__pycache__", "build", "dist", "*.spec"
|
||||
|
||||
foreach ($path in $pathsToRemove){
|
||||
Write-Host "Removing path: $($path)"
|
||||
Remove-Item -path $path -recurse
|
||||
}
|
||||
|
||||
Write-Host -ForegroundColor White "`nBuild script finished"
|
||||
28
src/exceptions.py
Executable file
28
src/exceptions.py
Executable file
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Video2X Exceptions
|
||||
Dev: K4YT3X
|
||||
Date Created: December 13, 2018
|
||||
Last Modified: July 27, 2019
|
||||
"""
|
||||
|
||||
|
||||
class ArgumentError(Exception):
|
||||
def __init__(self, message):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class StreamNotFoundError(Exception):
|
||||
def __init__(self, message):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class UnrecognizedDriverError(Exception):
|
||||
def __init__(self, message):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class UnsupportedPixelError(Exception):
|
||||
def __init__(self, message):
|
||||
super().__init__(message)
|
||||
27
bin/image_cleaner.py → src/image_cleaner.py
Normal file → Executable file
27
bin/image_cleaner.py → src/image_cleaner.py
Normal file → Executable file
@@ -3,15 +3,20 @@
|
||||
"""
|
||||
Name: Video2X Image Cleaner
|
||||
Author: BrianPetkovsek
|
||||
Author: K4YT3X
|
||||
Date Created: March 24, 2019
|
||||
Last Modified: April 28, 2019
|
||||
Last Modified: July 27, 2019
|
||||
|
||||
Editor: K4YT3X
|
||||
Last Modified: March 23, 2020
|
||||
|
||||
Editor: 28598519a
|
||||
Last Modified: March 23, 2020
|
||||
|
||||
Description: This class is to remove the extracted frames
|
||||
that have already been upscaled.
|
||||
"""
|
||||
|
||||
import os
|
||||
# built-in imports
|
||||
import threading
|
||||
import time
|
||||
|
||||
@@ -58,19 +63,17 @@ class ImageCleaner(threading.Thread):
|
||||
"""
|
||||
|
||||
# list all images in the extracted frames
|
||||
output_frames = [f for f in os.listdir(self.output_directory) if os.path.isfile(os.path.join(self.output_directory, f))]
|
||||
output_frames = [f.name for f in self.output_directory.iterdir() if f.is_file()]
|
||||
|
||||
# compare and remove frames downscaled images that finished being upscaled
|
||||
# within each thread's extracted frames directory
|
||||
for i in range(self.threads):
|
||||
dir_path = os.path.join(self.input_directory, str(i))
|
||||
for thread_id in range(self.threads):
|
||||
dir_path = self.input_directory / str(thread_id)
|
||||
|
||||
# for each file within all the directories
|
||||
for f in os.listdir(dir_path):
|
||||
file_path = os.path.join(dir_path, f)
|
||||
|
||||
for file in dir_path.iterdir():
|
||||
# if file also exists in the output directory, then the file
|
||||
# has already been processed, thus not needed anymore
|
||||
if os.path.isfile(file_path) and f in output_frames:
|
||||
os.remove(file_path)
|
||||
output_frames.remove(f)
|
||||
if file.is_file() and file.name in output_frames:
|
||||
file.unlink()
|
||||
output_frames.remove(file.name)
|
||||
BIN
src/images/Video2X Banner.png
Normal file
BIN
src/images/Video2X Banner.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
BIN
src/images/Video2X Banner.psd
Normal file
BIN
src/images/Video2X Banner.psd
Normal file
Binary file not shown.
BIN
src/images/Video2X GitHub Social Preview.png
Normal file
BIN
src/images/Video2X GitHub Social Preview.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
BIN
src/images/Video2X GitHub Social Preview.psd
Normal file
BIN
src/images/Video2X GitHub Social Preview.psd
Normal file
Binary file not shown.
BIN
src/images/Video2X Icon.psd
Normal file
BIN
src/images/Video2X Icon.psd
Normal file
Binary file not shown.
BIN
src/images/Video2X Logo.psd
Normal file
BIN
src/images/Video2X Logo.psd
Normal file
Binary file not shown.
BIN
src/images/video2x.ico
Normal file
BIN
src/images/video2x.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 110 KiB |
BIN
src/images/video2x.png
Normal file
BIN
src/images/video2x.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
BIN
src/locale/zh_CN/LC_MESSAGES/video2x.mo
Normal file
BIN
src/locale/zh_CN/LC_MESSAGES/video2x.mo
Normal file
Binary file not shown.
BIN
src/locale/zh_CN/LC_MESSAGES/zh_CN.mo
Normal file
BIN
src/locale/zh_CN/LC_MESSAGES/zh_CN.mo
Normal file
Binary file not shown.
298
src/locale/zh_CN/LC_MESSAGES/zh_CN.po
Normal file
298
src/locale/zh_CN/LC_MESSAGES/zh_CN.po
Normal file
@@ -0,0 +1,298 @@
|
||||
# SOME DESCRIPTIVE TITLE.
|
||||
# Copyright (C) YEAR ORGANIZATION
|
||||
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
|
||||
#
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: \n"
|
||||
"POT-Creation-Date: 2020-05-11 04:39-0400\n"
|
||||
"PO-Revision-Date: 2020-05-11 04:40-0400\n"
|
||||
"Last-Translator: \n"
|
||||
"Language-Team: \n"
|
||||
"Language: zh_CN\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Generated-By: pygettext.py 1.5\n"
|
||||
"X-Generator: Poedit 2.3.1\n"
|
||||
"Plural-Forms: nplurals=1; plural=0;\n"
|
||||
|
||||
#: progress_monitor.py:42
|
||||
msgid "Upscaling Progress"
|
||||
msgstr "放大进度"
|
||||
|
||||
#: upscaler.py:104
|
||||
msgid "Specified or default cache directory is a file/link"
|
||||
msgstr "指定或默认的缓存目录是文件/链接"
|
||||
|
||||
#: upscaler.py:110
|
||||
msgid "Creating cache directory {}"
|
||||
msgstr "创建缓存目录 {}"
|
||||
|
||||
#: upscaler.py:113
|
||||
msgid "Unable to create {}"
|
||||
msgstr "无法创建 {}"
|
||||
|
||||
#: upscaler.py:118
|
||||
msgid "Extracted frames are being saved to: {}"
|
||||
msgstr "提取的帧将被保存到:{}"
|
||||
|
||||
#: upscaler.py:120
|
||||
msgid "Upscaled frames are being saved to: {}"
|
||||
msgstr "已放大的帧将被保存到:{}"
|
||||
|
||||
#: upscaler.py:130
|
||||
msgid "Cleaning up cache directory: {}"
|
||||
msgstr "清理缓存目录:{}"
|
||||
|
||||
#: upscaler.py:133
|
||||
msgid "Unable to delete: {}"
|
||||
msgstr "无法删除:{}"
|
||||
|
||||
#: upscaler.py:139 upscaler.py:154 upscaler.py:165
|
||||
msgid "Input and output path type mismatch"
|
||||
msgstr "输入和输出路径类型不匹配"
|
||||
|
||||
#: upscaler.py:140
|
||||
msgid "Input is multiple files but output is not directory"
|
||||
msgstr "输入是多个文件,但输出不是目录"
|
||||
|
||||
#: upscaler.py:144
|
||||
msgid "Input path {} is neither a file nor a directory"
|
||||
msgstr "输入路径 {} 既不是文件也不是目录"
|
||||
|
||||
#: upscaler.py:148 upscaler.py:170
|
||||
msgid "Input directory and output directory cannot be the same"
|
||||
msgstr "输入目录和输出目录不能相同"
|
||||
|
||||
#: upscaler.py:155
|
||||
msgid "Input is single file but output is directory"
|
||||
msgstr "所选的输入路径是单个文件,但输出路径是目录"
|
||||
|
||||
#: upscaler.py:158
|
||||
msgid "No suffix found in output file path"
|
||||
msgstr "在输出文件路径中未找到后缀"
|
||||
|
||||
#: upscaler.py:159
|
||||
msgid "Suffix must be specified for FFmpeg"
|
||||
msgstr "必须为 FFmpeg 指定后缀"
|
||||
|
||||
#: upscaler.py:166
|
||||
msgid "Input is directory but output is existing single file"
|
||||
msgstr "输入是目录,但输出是现有的单个文件"
|
||||
|
||||
#: upscaler.py:175
|
||||
msgid "Input path is neither a file nor a directory"
|
||||
msgstr "输入路径既不是文件也不是目录"
|
||||
|
||||
#: upscaler.py:184
|
||||
msgid "FFmpeg or FFprobe cannot be found under the specified path"
|
||||
msgstr "在指定的路径下找不到 FFmpeg 或 FFprobe"
|
||||
|
||||
#: upscaler.py:185 upscaler.py:195
|
||||
msgid "Please check the configuration file settings"
|
||||
msgstr "请检查配置文件设置"
|
||||
|
||||
#: upscaler.py:194
|
||||
msgid "Specified driver executable directory doesn't exist"
|
||||
msgstr "指定驱动的可执行文件不存在"
|
||||
|
||||
#: upscaler.py:221
|
||||
msgid "Failed to parse driver argument: {}"
|
||||
msgstr "解析驱动程序参数失败:{}"
|
||||
|
||||
#: upscaler.py:253
|
||||
msgid "Unrecognized driver: {}"
|
||||
msgstr "无法识别的驱动名称:{}"
|
||||
|
||||
#: upscaler.py:293
|
||||
msgid "Starting progress monitor"
|
||||
msgstr "启动进度监视器"
|
||||
|
||||
#: upscaler.py:298
|
||||
msgid "Starting upscaled image cleaner"
|
||||
msgstr "启动已放大图像清理程序"
|
||||
|
||||
#: upscaler.py:307 upscaler.py:324
|
||||
msgid "Killing progress monitor"
|
||||
msgstr "终结进度监视器"
|
||||
|
||||
#: upscaler.py:310 upscaler.py:327
|
||||
msgid "Killing upscaled image cleaner"
|
||||
msgstr "终结已放大图像清理程序"
|
||||
|
||||
#: upscaler.py:331
|
||||
msgid "Terminating all processes"
|
||||
msgstr "正在终止所有进程"
|
||||
|
||||
#: upscaler.py:338
|
||||
msgid "Main process waiting for subprocesses to exit"
|
||||
msgstr "主进程开始等待子进程结束"
|
||||
|
||||
#: upscaler.py:357 upscaler.py:361
|
||||
msgid "Subprocess {} exited with code {}"
|
||||
msgstr "子进程 {} 结束,返回码 {}"
|
||||
|
||||
#: upscaler.py:367
|
||||
msgid "Stop signal received"
|
||||
msgstr "收到停止信号"
|
||||
|
||||
#: upscaler.py:372
|
||||
msgid "Subprocess execution ran into an error"
|
||||
msgstr "子进程执行遇到错误"
|
||||
|
||||
#: upscaler.py:421
|
||||
msgid "Upscaling single video file: {}"
|
||||
msgstr "放大单个视频文件:{}"
|
||||
|
||||
#: upscaler.py:443 upscaler.py:502
|
||||
msgid "Starting to upscale extracted images"
|
||||
msgstr "开始对提取的帧进行放大"
|
||||
|
||||
#: upscaler.py:448 upscaler.py:504
|
||||
msgid "Upscaling completed"
|
||||
msgstr "放大完成"
|
||||
|
||||
#: upscaler.py:457
|
||||
msgid "Reading video information"
|
||||
msgstr "读取视频信息"
|
||||
|
||||
#: upscaler.py:471
|
||||
msgid "Aborting: No video stream found"
|
||||
msgstr "程序中止:文件中未找到视频流"
|
||||
|
||||
#: upscaler.py:490
|
||||
msgid "Unsupported pixel format: {}"
|
||||
msgstr "不支持的像素格式:{}"
|
||||
|
||||
#: upscaler.py:493
|
||||
msgid "Framerate: {}"
|
||||
msgstr "帧率:{}"
|
||||
|
||||
#: upscaler.py:507
|
||||
msgid "Converting extracted frames into video"
|
||||
msgstr "正在将提取的帧转换为视频"
|
||||
|
||||
#: upscaler.py:514
|
||||
msgid "Conversion completed"
|
||||
msgstr "转换已完成"
|
||||
|
||||
#: upscaler.py:518
|
||||
msgid "Migrating audio, subtitles and other streams to upscaled video"
|
||||
msgstr "正在将音频、字幕和其他流迁移到放大后的视频"
|
||||
|
||||
#: upscaler.py:527
|
||||
msgid "Failed to migrate streams"
|
||||
msgstr "迁移流失败"
|
||||
|
||||
#: upscaler.py:528
|
||||
msgid "Trying to output video without additional streams"
|
||||
msgstr "正在尝试输出不含其他流的视频"
|
||||
|
||||
#: upscaler.py:535
|
||||
msgid "Output video file exists, aborting"
|
||||
msgstr "输出目标文件已存在,取消输出"
|
||||
|
||||
#: upscaler.py:539
|
||||
msgid "Writing intermediate file to: {}"
|
||||
msgstr "正在将中间视频文件写入至:{}"
|
||||
|
||||
#: video2x.py:84
|
||||
msgid ""
|
||||
"Video2X Version: {}\n"
|
||||
"Author: K4YT3X\n"
|
||||
"License: GNU GPL v3\n"
|
||||
"Github Page: https://github.com/k4yt3x/video2x\n"
|
||||
"Contact: k4yt3x@k4yt3x.com"
|
||||
msgstr ""
|
||||
"Video2X 版本: {}\n"
|
||||
"作者: K4YT3X\n"
|
||||
"开源许可: GNU GPL v3\n"
|
||||
"GitHub 主页:https://github.com/k4yt3x/video2x\n"
|
||||
"联系方式:k4yt3x@k4yt3x.com"
|
||||
|
||||
#: video2x.py:106
|
||||
msgid "Video2X Options"
|
||||
msgstr "Video2X 选项"
|
||||
|
||||
#: video2x.py:107
|
||||
msgid "show this help message and exit"
|
||||
msgstr "显示此帮助消息并退出"
|
||||
|
||||
#: video2x.py:108
|
||||
msgid "source video file/directory"
|
||||
msgstr "源视频文件/目录"
|
||||
|
||||
#: video2x.py:109
|
||||
msgid "output video file/directory"
|
||||
msgstr "输出视频文件/目录"
|
||||
|
||||
#: video2x.py:110
|
||||
msgid "video2x config file path"
|
||||
msgstr "video2x 配置文件路径"
|
||||
|
||||
#: video2x.py:112
|
||||
msgid "display version, lawful information and exit"
|
||||
msgstr "显示版本和法律信息并退出"
|
||||
|
||||
#: video2x.py:115
|
||||
msgid "Upscaling Options"
|
||||
msgstr "视频放大选项"
|
||||
|
||||
#: video2x.py:116
|
||||
msgid "upscaling driver"
|
||||
msgstr "视频放大驱动"
|
||||
|
||||
#: video2x.py:117
|
||||
msgid "scaling ratio"
|
||||
msgstr "缩放比"
|
||||
|
||||
#: video2x.py:118
|
||||
msgid "number of processes to use for upscaling"
|
||||
msgstr "并发进程数"
|
||||
|
||||
#: video2x.py:119
|
||||
msgid "preserve extracted and upscaled frames"
|
||||
msgstr "保留提取的和放大的帧"
|
||||
|
||||
#: video2x.py:159
|
||||
msgid "This file cannot be imported"
|
||||
msgstr "此文件无法被当作模块导入"
|
||||
|
||||
#: video2x.py:229
|
||||
msgid "Program completed, taking {} seconds"
|
||||
msgstr "程序执行完毕,总计花费 {} 秒"
|
||||
|
||||
#: video2x.py:232
|
||||
msgid "An exception has occurred"
|
||||
msgstr "发生了异常"
|
||||
|
||||
#~ msgid "output video width"
|
||||
#~ msgstr "输出视频宽度"
|
||||
|
||||
#~ msgid "output video height"
|
||||
#~ msgstr "输出视频高度"
|
||||
|
||||
#~ msgid "You must specify input video file/directory path"
|
||||
#~ msgstr "您必须指定输入视频文件/目录路径"
|
||||
|
||||
#~ msgid "You must specify output video file/directory path"
|
||||
#~ msgstr "您必须指定输出视频文件/目录路径"
|
||||
|
||||
#~ msgid "Selected driver accepts only scaling ratio"
|
||||
#~ msgstr "所选驱动程序仅接受缩放比率"
|
||||
|
||||
#~ msgid "Scaling ratio must be 1 or 2 for waifu2x_ncnn_vulkan"
|
||||
#~ msgstr "waifu2x_ncnn_vulkan 的缩放比必须为 1 或 2"
|
||||
|
||||
#~ msgid "Scaling ratio must be one of 2, 3 or 4 for srmd_ncnn_vulkan"
|
||||
#~ msgstr "srmd_ncnn_vulkan 的缩放比必须为 2、3 或 4"
|
||||
|
||||
#~ msgid "You can only specify either scaling ratio or output width and height"
|
||||
#~ msgstr "您只能指定缩放比或输出宽度和高度两者之一"
|
||||
|
||||
#~ msgid "You must specify both width and height"
|
||||
#~ msgstr "您必须同时指定宽度和高度"
|
||||
|
||||
#~ msgid "Upscaling videos in directory: {}"
|
||||
#~ msgstr "放大该文件夹中的所有视频:{}"
|
||||
64
src/progress_monitor.py
Normal file
64
src/progress_monitor.py
Normal file
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Video2X Upscale Progress Monitor
|
||||
Author: BrianPetkovsek
|
||||
Date Created: May 7, 2020
|
||||
Last Modified: May 10, 2020
|
||||
"""
|
||||
|
||||
# built-in imports
|
||||
import contextlib
|
||||
import threading
|
||||
import time
|
||||
|
||||
# third-party imports
|
||||
from tqdm import tqdm
|
||||
|
||||
|
||||
class ProgressMonitor(threading.Thread):
|
||||
""" progress monitor
|
||||
|
||||
This class provides progress monitoring functionalities
|
||||
by keeping track of the amount of frames in the input
|
||||
directory and the output directory. This is originally
|
||||
suggested by @ArmandBernard.
|
||||
"""
|
||||
|
||||
def __init__(self, upscaler, extracted_frames_directories):
|
||||
threading.Thread.__init__(self)
|
||||
self.upscaler = upscaler
|
||||
self.extracted_frames_directories = extracted_frames_directories
|
||||
self.running = False
|
||||
|
||||
def run(self):
|
||||
self.running = True
|
||||
|
||||
# get number of extracted frames
|
||||
self.upscaler.total_frames = 0
|
||||
for directory in self.extracted_frames_directories:
|
||||
self.upscaler.total_frames += len([f for f in directory.iterdir() if str(f).lower().endswith(self.upscaler.image_format.lower())])
|
||||
|
||||
with tqdm(total=self.upscaler.total_frames, ascii=True, desc=_('Upscaling Progress')) 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.
|
||||
previous_cycle_frames = 0
|
||||
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.image_format.lower())]
|
||||
if len(upscaled_frames) >= 1:
|
||||
self.upscaler.last_frame_upscaled = sorted(upscaled_frames)[-1]
|
||||
self.upscaler.total_frames_upscaled = len(upscaled_frames)
|
||||
|
||||
# update progress bar
|
||||
delta = self.upscaler.total_frames_upscaled - previous_cycle_frames
|
||||
previous_cycle_frames = self.upscaler.total_frames_upscaled
|
||||
progress_bar.update(delta)
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
def stop(self):
|
||||
self.running = False
|
||||
self.join()
|
||||
@@ -1,6 +1,9 @@
|
||||
avalon_framework
|
||||
colorama
|
||||
GPUtil
|
||||
patool
|
||||
psutil
|
||||
pyqt5
|
||||
pyunpack
|
||||
pyyaml
|
||||
requests
|
||||
tqdm
|
||||
tqdm
|
||||
555
src/upscaler.py
Executable file
555
src/upscaler.py
Executable file
@@ -0,0 +1,555 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Video2X Upscaler
|
||||
Author: K4YT3X
|
||||
Date Created: December 10, 2018
|
||||
Last Modified: May 10, 2020
|
||||
|
||||
Description: This file contains the Upscaler class. Each
|
||||
instance of the Upscaler class is an upscaler on an image or
|
||||
a folder.
|
||||
"""
|
||||
|
||||
# local imports
|
||||
from exceptions import *
|
||||
from image_cleaner import ImageCleaner
|
||||
from progress_monitor import ProgressMonitor
|
||||
from wrappers.ffmpeg import Ffmpeg
|
||||
|
||||
# built-in imports
|
||||
from fractions import Fraction
|
||||
import contextlib
|
||||
import copy
|
||||
import gettext
|
||||
import importlib
|
||||
import locale
|
||||
import os
|
||||
import pathlib
|
||||
import queue
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
|
||||
# third-party imports
|
||||
from avalon_framework import Avalon
|
||||
|
||||
# internationalization constants
|
||||
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.install()
|
||||
_ = language.gettext
|
||||
|
||||
# these names are consistent for
|
||||
# - driver selection in command line
|
||||
# - driver wrapper file names
|
||||
# - config file keys
|
||||
AVAILABLE_DRIVERS = ['waifu2x_caffe',
|
||||
'waifu2x_converter_cpp',
|
||||
'waifu2x_ncnn_vulkan',
|
||||
'srmd_ncnn_vulkan',
|
||||
'anime4kcpp']
|
||||
|
||||
|
||||
class Upscaler:
|
||||
""" An instance of this class is a upscaler that will
|
||||
upscale all images in the given directory.
|
||||
|
||||
Raises:
|
||||
Exception -- all exceptions
|
||||
ArgumentError -- if argument is not valid
|
||||
"""
|
||||
|
||||
def __init__(self, input_path, output_path, driver_settings, ffmpeg_settings):
|
||||
# mandatory arguments
|
||||
self.input = input_path
|
||||
self.output = output_path
|
||||
self.driver_settings = driver_settings
|
||||
self.ffmpeg_settings = ffmpeg_settings
|
||||
|
||||
# optional arguments
|
||||
self.driver = 'waifu2x_caffe'
|
||||
self.scale_ratio = None
|
||||
self.processes = 1
|
||||
self.video2x_cache_directory = pathlib.Path(tempfile.gettempdir()) / 'video2x'
|
||||
self.image_format = 'png'
|
||||
self.preserve_frames = False
|
||||
|
||||
# other internal members and signals
|
||||
self.running = False
|
||||
self.total_frames_upscaled = 0
|
||||
self.total_frames = 0
|
||||
self.total_videos = 0
|
||||
self.total_processed = 0
|
||||
self.current_input_video = pathlib.Path()
|
||||
self.last_frame_upscaled = pathlib.Path()
|
||||
|
||||
def create_temp_directories(self):
|
||||
"""create temporary directories
|
||||
"""
|
||||
|
||||
# if cache directory unspecified, use %TEMP%\video2x
|
||||
if self.video2x_cache_directory is None:
|
||||
self.video2x_cache_directory = pathlib.Path(tempfile.gettempdir()) / 'video2x'
|
||||
|
||||
# if specified cache path exists and isn't a directory
|
||||
if self.video2x_cache_directory.exists() and not self.video2x_cache_directory.is_dir():
|
||||
Avalon.error(_('Specified or default cache directory is a file/link'))
|
||||
raise FileExistsError('Specified or default cache directory is a file/link')
|
||||
|
||||
# if cache directory doesn't exist, try creating it
|
||||
if not self.video2x_cache_directory.exists():
|
||||
try:
|
||||
Avalon.debug_info(_('Creating cache directory {}').format(self.video2x_cache_directory))
|
||||
self.video2x_cache_directory.mkdir(parents=True, exist_ok=True)
|
||||
except Exception as exception:
|
||||
Avalon.error(_('Unable to create {}').format(self.video2x_cache_directory))
|
||||
raise exception
|
||||
|
||||
# create temp directories for extracted frames and upscaled frames
|
||||
self.extracted_frames = pathlib.Path(tempfile.mkdtemp(dir=self.video2x_cache_directory))
|
||||
Avalon.debug_info(_('Extracted frames are being saved to: {}').format(self.extracted_frames))
|
||||
self.upscaled_frames = pathlib.Path(tempfile.mkdtemp(dir=self.video2x_cache_directory))
|
||||
Avalon.debug_info(_('Upscaled frames are being saved to: {}').format(self.upscaled_frames))
|
||||
|
||||
def cleanup_temp_directories(self):
|
||||
"""delete temp directories when done
|
||||
"""
|
||||
if not self.preserve_frames:
|
||||
for directory in [self.extracted_frames, self.upscaled_frames, self.video2x_cache_directory]:
|
||||
try:
|
||||
# avalon framework cannot be used if python is shutting down
|
||||
# therefore, plain print is used
|
||||
print(_('Cleaning up cache directory: {}').format(directory))
|
||||
shutil.rmtree(directory)
|
||||
except (OSError, FileNotFoundError):
|
||||
print(_('Unable to delete: {}').format(directory))
|
||||
traceback.print_exc()
|
||||
|
||||
def _check_arguments(self):
|
||||
if isinstance(self.input, list):
|
||||
if self.output.exists() and not self.output.is_dir():
|
||||
Avalon.error(_('Input and output path type mismatch'))
|
||||
Avalon.error(_('Input is multiple files but output is not directory'))
|
||||
raise ArgumentError('input output path type mismatch')
|
||||
for input_path in self.input:
|
||||
if not input_path.is_file() and not input_path.is_dir():
|
||||
Avalon.error(_('Input path {} is neither a file nor a directory').format(input_path))
|
||||
raise FileNotFoundError(f'{input_path} is neither file nor directory')
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
if input_path.samefile(self.output):
|
||||
Avalon.error(_('Input directory and output directory cannot be the same'))
|
||||
raise FileExistsError('input directory and output directory are the same')
|
||||
|
||||
# if input is a file
|
||||
elif self.input.is_file():
|
||||
if self.output.is_dir():
|
||||
Avalon.error(_('Input and output path type mismatch'))
|
||||
Avalon.error(_('Input is single file but output is directory'))
|
||||
raise ArgumentError('input output path type mismatch')
|
||||
if not re.search(r'.*\..*$', str(self.output)):
|
||||
Avalon.error(_('No suffix found in output file path'))
|
||||
Avalon.error(_('Suffix must be specified for FFmpeg'))
|
||||
raise ArgumentError('no output video suffix specified')
|
||||
|
||||
# if input is a directory
|
||||
elif self.input.is_dir():
|
||||
if self.output.is_file():
|
||||
Avalon.error(_('Input and output path type mismatch'))
|
||||
Avalon.error(_('Input is directory but output is existing single file'))
|
||||
raise ArgumentError('input output path type mismatch')
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
if self.input.samefile(self.output):
|
||||
Avalon.error(_('Input directory and output directory cannot be the same'))
|
||||
raise FileExistsError('input directory and output directory are the same')
|
||||
|
||||
# if input is neither
|
||||
else:
|
||||
Avalon.error(_('Input path is neither a file nor a directory'))
|
||||
raise FileNotFoundError(f'{self.input} is neither file nor directory')
|
||||
|
||||
# check FFmpeg settings
|
||||
ffmpeg_path = pathlib.Path(self.ffmpeg_settings['ffmpeg_path'])
|
||||
if not ((pathlib.Path(ffmpeg_path / 'ffmpeg.exe').is_file() and
|
||||
pathlib.Path(ffmpeg_path / 'ffprobe.exe').is_file()) or
|
||||
(pathlib.Path(ffmpeg_path / 'ffmpeg').is_file() and
|
||||
pathlib.Path(ffmpeg_path / 'ffprobe').is_file())):
|
||||
Avalon.error(_('FFmpeg or FFprobe cannot be found under the specified path'))
|
||||
Avalon.error(_('Please check the configuration file settings'))
|
||||
raise FileNotFoundError(self.ffmpeg_settings['ffmpeg_path'])
|
||||
|
||||
# check if driver settings
|
||||
driver_settings = copy.deepcopy(self.driver_settings)
|
||||
driver_path = driver_settings.pop('path')
|
||||
|
||||
# check if driver path exists
|
||||
if not (pathlib.Path(driver_path).is_file() or pathlib.Path(f'{driver_path}.exe').is_file()):
|
||||
Avalon.error(_('Specified driver executable directory doesn\'t exist'))
|
||||
Avalon.error(_('Please check the configuration file settings'))
|
||||
raise FileNotFoundError(driver_path)
|
||||
|
||||
# parse driver arguments using driver's parser
|
||||
# the parser will throw AttributeError if argument doesn't satisfy constraints
|
||||
try:
|
||||
driver_arguments = []
|
||||
for key in driver_settings.keys():
|
||||
|
||||
value = driver_settings[key]
|
||||
|
||||
if value is None or value is False:
|
||||
continue
|
||||
|
||||
else:
|
||||
if len(key) == 1:
|
||||
driver_arguments.append(f'-{key}')
|
||||
else:
|
||||
driver_arguments.append(f'--{key}')
|
||||
# true means key is an option
|
||||
if value is not True:
|
||||
driver_arguments.append(str(value))
|
||||
|
||||
DriverWrapperMain = getattr(importlib.import_module(f'wrappers.{self.driver}'), 'WrapperMain')
|
||||
DriverWrapperMain.parse_arguments(driver_arguments)
|
||||
except AttributeError as e:
|
||||
Avalon.error(_('Failed to parse driver argument: {}').format(e.args[0]))
|
||||
raise e
|
||||
|
||||
# waifu2x-caffe scale_ratio, scale_width and scale_height check
|
||||
if self.driver == 'waifu2x_caffe':
|
||||
if (driver_settings['scale_width'] != 0 and driver_settings['scale_height'] == 0 or
|
||||
driver_settings['scale_width'] == 0 and driver_settings['scale_height'] != 0):
|
||||
Avalon.error('Only one of scale_width and scale_height is specified for waifu2x-caffe')
|
||||
raise AttributeError('only one of scale_width and scale_height is specified for waifu2x-caffe')
|
||||
|
||||
# if scale_width and scale_height are specified, ensure scale_ratio is None
|
||||
elif self.driver_settings['scale_width'] != 0 and self.driver_settings['scale_height'] != 0:
|
||||
self.driver_settings['scale_ratio'] = None
|
||||
|
||||
# if scale_width and scale_height not specified
|
||||
# ensure they are None, not 0
|
||||
else:
|
||||
self.driver_settings['scale_width'] = None
|
||||
self.driver_settings['scale_height'] = None
|
||||
|
||||
def _upscale_frames(self):
|
||||
""" Upscale video frames with waifu2x-caffe
|
||||
|
||||
This function upscales all the frames extracted
|
||||
by ffmpeg using the waifu2x-caffe binary.
|
||||
|
||||
Arguments:
|
||||
w2 {Waifu2x Object} -- initialized waifu2x object
|
||||
"""
|
||||
|
||||
# initialize waifu2x driver
|
||||
if self.driver not in AVAILABLE_DRIVERS:
|
||||
raise UnrecognizedDriverError(_('Unrecognized driver: {}').format(self.driver))
|
||||
|
||||
# list all images in the extracted frames
|
||||
frames = [(self.extracted_frames / f) for f in self.extracted_frames.iterdir() if f.is_file]
|
||||
|
||||
# if we have less images than processes,
|
||||
# create only the processes necessary
|
||||
if len(frames) < self.processes:
|
||||
self.processes = len(frames)
|
||||
|
||||
# create a directory for each process and append directory
|
||||
# name into a list
|
||||
process_directories = []
|
||||
for process_id in range(self.processes):
|
||||
process_directory = self.extracted_frames / str(process_id)
|
||||
process_directories.append(process_directory)
|
||||
|
||||
# delete old directories and create new directories
|
||||
if process_directory.is_dir():
|
||||
shutil.rmtree(process_directory)
|
||||
process_directory.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# waifu2x-converter-cpp will perform multi-threading within its own process
|
||||
if self.driver in ['waifu2x_converter_cpp', 'waifu2x_ncnn_vulkan', 'srmd_ncnn_vulkan']:
|
||||
process_directories = [self.extracted_frames]
|
||||
|
||||
else:
|
||||
# evenly distribute images into each directory
|
||||
# until there is none left in the directory
|
||||
for image in frames:
|
||||
# move image
|
||||
image.rename(process_directories[0] / image.name)
|
||||
# rotate list
|
||||
process_directories = process_directories[-1:] + process_directories[:-1]
|
||||
|
||||
# create driver processes and start them
|
||||
for process_directory in process_directories:
|
||||
self.process_pool.append(self.driver_object.upscale(process_directory, self.upscaled_frames))
|
||||
|
||||
# start progress bar in a different thread
|
||||
Avalon.debug_info(_('Starting progress monitor'))
|
||||
self.progress_monitor = ProgressMonitor(self, process_directories)
|
||||
self.progress_monitor.start()
|
||||
|
||||
# create the clearer and start it
|
||||
Avalon.debug_info(_('Starting upscaled image cleaner'))
|
||||
self.image_cleaner = ImageCleaner(self.extracted_frames, self.upscaled_frames, len(self.process_pool))
|
||||
self.image_cleaner.start()
|
||||
|
||||
# wait for all process to exit
|
||||
try:
|
||||
self._wait()
|
||||
except (Exception, KeyboardInterrupt, SystemExit) as e:
|
||||
# cleanup
|
||||
Avalon.debug_info(_('Killing progress monitor'))
|
||||
self.progress_monitor.stop()
|
||||
|
||||
Avalon.debug_info(_('Killing upscaled image cleaner'))
|
||||
self.image_cleaner.stop()
|
||||
raise e
|
||||
|
||||
# if the driver is waifu2x-converter-cpp
|
||||
# images need to be renamed to be recognizable for FFmpeg
|
||||
if self.driver == 'waifu2x_converter_cpp':
|
||||
for image in [f for f in self.upscaled_frames.iterdir() if f.is_file()]:
|
||||
renamed = re.sub(f'_\\[.*\\]\\[x(\\d+(\\.\\d+)?)\\]\\.{self.image_format}',
|
||||
f'.{self.image_format}',
|
||||
str(image.name))
|
||||
(self.upscaled_frames / image).rename(self.upscaled_frames / renamed)
|
||||
|
||||
# upscaling done, kill helper threads
|
||||
Avalon.debug_info(_('Killing progress monitor'))
|
||||
self.progress_monitor.stop()
|
||||
|
||||
Avalon.debug_info(_('Killing upscaled image cleaner'))
|
||||
self.image_cleaner.stop()
|
||||
|
||||
def _terminate_subprocesses(self):
|
||||
Avalon.warning(_('Terminating all processes'))
|
||||
for process in self.process_pool:
|
||||
process.terminate()
|
||||
|
||||
def _wait(self):
|
||||
""" wait for subprocesses in process pool to complete
|
||||
"""
|
||||
Avalon.debug_info(_('Main process waiting for subprocesses to exit'))
|
||||
|
||||
try:
|
||||
# while process pool not empty
|
||||
while self.process_pool:
|
||||
|
||||
# if stop signal received, terminate all processes
|
||||
if self.running is False:
|
||||
raise SystemExit
|
||||
|
||||
for process in self.process_pool:
|
||||
process_status = process.poll()
|
||||
|
||||
# if process finished
|
||||
if process_status is None:
|
||||
continue
|
||||
|
||||
# if return code is not 0
|
||||
elif process_status != 0:
|
||||
Avalon.error(_('Subprocess {} exited with code {}').format(process.pid, process_status))
|
||||
raise subprocess.CalledProcessError(process_status, process.args)
|
||||
|
||||
else:
|
||||
Avalon.debug_info(_('Subprocess {} exited with code {}').format(process.pid, process_status))
|
||||
self.process_pool.remove(process)
|
||||
|
||||
time.sleep(0.1)
|
||||
|
||||
except (KeyboardInterrupt, SystemExit) as e:
|
||||
Avalon.warning(_('Stop signal received'))
|
||||
self._terminate_subprocesses()
|
||||
raise e
|
||||
|
||||
except (Exception, subprocess.CalledProcessError) as e:
|
||||
Avalon.error(_('Subprocess execution ran into an error'))
|
||||
self._terminate_subprocesses()
|
||||
raise e
|
||||
|
||||
def run(self):
|
||||
""" Main controller for Video2X
|
||||
|
||||
This function controls the flow of video conversion
|
||||
and handles all necessary functions.
|
||||
"""
|
||||
|
||||
# external stop signal when called in a thread
|
||||
self.running = True
|
||||
|
||||
# define process pool to contain processes
|
||||
self.process_pool = []
|
||||
|
||||
# load driver modules
|
||||
DriverWrapperMain = getattr(importlib.import_module(f'wrappers.{self.driver}'), 'WrapperMain')
|
||||
self.driver_object = DriverWrapperMain(self.driver_settings)
|
||||
|
||||
# load options from upscaler class into driver settings
|
||||
self.driver_object.load_configurations(self)
|
||||
|
||||
# parse arguments for waifu2x
|
||||
# check argument sanity
|
||||
self._check_arguments()
|
||||
|
||||
# define processing queue
|
||||
self.processing_queue = queue.Queue()
|
||||
|
||||
# if input is a list of files
|
||||
if isinstance(self.input, list):
|
||||
# make output directory if it doesn't exist
|
||||
self.output.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for input_path in self.input:
|
||||
|
||||
if input_path.is_file():
|
||||
output_video = self.output / input_path.name
|
||||
self.processing_queue.put((input_path.absolute(), output_video.absolute()))
|
||||
|
||||
elif input_path.is_dir():
|
||||
for input_video in [f for f in input_path.iterdir() if f.is_file()]:
|
||||
output_video = self.output / input_video.name
|
||||
self.processing_queue.put((input_video.absolute(), output_video.absolute()))
|
||||
|
||||
# if input specified is single file
|
||||
elif self.input.is_file():
|
||||
Avalon.info(_('Upscaling single video file: {}').format(self.input))
|
||||
self.processing_queue.put((self.input.absolute(), self.output.absolute()))
|
||||
|
||||
# if input specified is a directory
|
||||
elif self.input.is_dir():
|
||||
|
||||
# make output directory if it doesn't exist
|
||||
self.output.mkdir(parents=True, exist_ok=True)
|
||||
for input_video in [f for f in self.input.iterdir() if f.is_file()]:
|
||||
output_video = self.output / input_video.name
|
||||
self.processing_queue.put((input_video.absolute(), output_video.absolute()))
|
||||
|
||||
# record video count for external calls
|
||||
self.total_videos = self.processing_queue.qsize()
|
||||
|
||||
while not self.processing_queue.empty():
|
||||
self.current_input_video, output_video = self.processing_queue.get()
|
||||
# drivers that have native support for video processing
|
||||
if self.driver == 'anime4kcpp':
|
||||
# append FFmpeg path to the end of PATH
|
||||
# Anime4KCPP will then use FFmpeg to migrate audio tracks
|
||||
os.environ['PATH'] += f';{self.ffmpeg_settings["ffmpeg_path"]}'
|
||||
Avalon.info(_('Starting to upscale extracted images'))
|
||||
|
||||
# run Anime4KCPP
|
||||
self.process_pool.append(self.driver_object.upscale(self.current_input_video, output_video))
|
||||
self._wait()
|
||||
Avalon.info(_('Upscaling completed'))
|
||||
|
||||
else:
|
||||
try:
|
||||
self.create_temp_directories()
|
||||
|
||||
# initialize objects for ffmpeg and waifu2x-caffe
|
||||
fm = Ffmpeg(self.ffmpeg_settings, self.image_format)
|
||||
|
||||
Avalon.info(_('Reading video information'))
|
||||
video_info = fm.get_video_info(self.current_input_video)
|
||||
# analyze original video with FFprobe and retrieve framerate
|
||||
# width, height = info['streams'][0]['width'], info['streams'][0]['height']
|
||||
|
||||
# find index of video stream
|
||||
video_stream_index = None
|
||||
for stream in video_info['streams']:
|
||||
if stream['codec_type'] == 'video':
|
||||
video_stream_index = stream['index']
|
||||
break
|
||||
|
||||
# exit if no video stream found
|
||||
if video_stream_index is None:
|
||||
Avalon.error(_('Aborting: No video stream found'))
|
||||
raise StreamNotFoundError('no video stream found')
|
||||
|
||||
# extract frames from video
|
||||
self.process_pool.append((fm.extract_frames(self.current_input_video, self.extracted_frames)))
|
||||
self._wait()
|
||||
|
||||
# get average frame rate of video stream
|
||||
framerate = float(Fraction(video_info['streams'][video_stream_index]['r_frame_rate']))
|
||||
fm.pixel_format = video_info['streams'][video_stream_index]['pix_fmt']
|
||||
|
||||
if self.driver == 'waifu2x_caffe':
|
||||
# get a dict of all pixel formats and corresponding bit depth
|
||||
pixel_formats = fm.get_pixel_formats()
|
||||
|
||||
# try getting pixel format's corresponding bti depth
|
||||
try:
|
||||
self.driver_settings['output_depth'] = pixel_formats[fm.pixel_format]
|
||||
except KeyError:
|
||||
Avalon.error(_('Unsupported pixel format: {}').format(fm.pixel_format))
|
||||
raise UnsupportedPixelError(f'unsupported pixel format {fm.pixel_format}')
|
||||
|
||||
Avalon.info(_('Framerate: {}').format(framerate))
|
||||
|
||||
# width/height will be coded width/height x upscale factor
|
||||
original_width = video_info['streams'][video_stream_index]['width']
|
||||
original_height = video_info['streams'][video_stream_index]['height']
|
||||
scale_width = int(self.scale_ratio * original_width)
|
||||
scale_height = int(self.scale_ratio * original_height)
|
||||
|
||||
# upscale images one by one using waifu2x
|
||||
Avalon.info(_('Starting to upscale extracted images'))
|
||||
self._upscale_frames()
|
||||
Avalon.info(_('Upscaling completed'))
|
||||
|
||||
# frames to Video
|
||||
Avalon.info(_('Converting extracted frames into video'))
|
||||
|
||||
# use user defined output size
|
||||
self.process_pool.append(fm.assemble_video(framerate,
|
||||
f'{scale_width}x{scale_height}',
|
||||
self.upscaled_frames))
|
||||
self._wait()
|
||||
Avalon.info(_('Conversion completed'))
|
||||
|
||||
try:
|
||||
# migrate audio tracks and subtitles
|
||||
Avalon.info(_('Migrating audio, subtitles and other streams to upscaled video'))
|
||||
self.process_pool.append(fm.migrate_streams(self.current_input_video,
|
||||
output_video,
|
||||
self.upscaled_frames))
|
||||
self._wait()
|
||||
|
||||
# if failed to copy streams
|
||||
# use file with only video stream
|
||||
except subprocess.CalledProcessError:
|
||||
Avalon.error(_('Failed to migrate streams'))
|
||||
Avalon.warning(_('Trying to output video without additional streams'))
|
||||
|
||||
# construct output file path
|
||||
output_video_path = output_video.parent / f'{output_video.stem}{fm.intermediate_file_name.suffix}'
|
||||
|
||||
# if output file already exists, cancel
|
||||
if output_video_path.exists():
|
||||
Avalon.error(_('Output video file exists, aborting'))
|
||||
|
||||
# otherwise, rename intermediate file to the output file
|
||||
else:
|
||||
Avalon.info(_('Writing intermediate file to: {}').format(output_video_path.absolute()))
|
||||
(self.upscaled_frames / fm.intermediate_file_name).rename(output_video_path)
|
||||
|
||||
# destroy temp directories
|
||||
self.cleanup_temp_directories()
|
||||
|
||||
except (Exception, KeyboardInterrupt, SystemExit) as e:
|
||||
with contextlib.suppress(ValueError):
|
||||
self.cleanup_temp_directories()
|
||||
self.running = False
|
||||
raise e
|
||||
|
||||
# increment total number of videos processed
|
||||
self.total_processed += 1
|
||||
|
||||
# signal upscaling completion
|
||||
self.running = False
|
||||
262
src/video2x.pot
Normal file
262
src/video2x.pot
Normal file
@@ -0,0 +1,262 @@
|
||||
# SOME DESCRIPTIVE TITLE.
|
||||
# Copyright (C) YEAR ORGANIZATION
|
||||
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
|
||||
#
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: PACKAGE VERSION\n"
|
||||
"POT-Creation-Date: 2020-05-11 04:39-0400\n"
|
||||
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
|
||||
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
||||
"Language-Team: LANGUAGE <LL@li.org>\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=cp1252\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Generated-By: pygettext.py 1.5\n"
|
||||
|
||||
|
||||
#: progress_monitor.py:42
|
||||
msgid "Upscaling Progress"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:104
|
||||
msgid "Specified or default cache directory is a file/link"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:110
|
||||
msgid "Creating cache directory {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:113
|
||||
msgid "Unable to create {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:118
|
||||
msgid "Extracted frames are being saved to: {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:120
|
||||
msgid "Upscaled frames are being saved to: {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:130
|
||||
msgid "Cleaning up cache directory: {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:133
|
||||
msgid "Unable to delete: {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:139 upscaler.py:154 upscaler.py:165
|
||||
msgid "Input and output path type mismatch"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:140
|
||||
msgid "Input is multiple files but output is not directory"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:144
|
||||
msgid "Input path {} is neither a file nor a directory"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:148 upscaler.py:170
|
||||
msgid "Input directory and output directory cannot be the same"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:155
|
||||
msgid "Input is single file but output is directory"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:158
|
||||
msgid "No suffix found in output file path"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:159
|
||||
msgid "Suffix must be specified for FFmpeg"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:166
|
||||
msgid "Input is directory but output is existing single file"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:175
|
||||
msgid "Input path is neither a file nor a directory"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:184
|
||||
msgid "FFmpeg or FFprobe cannot be found under the specified path"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:185 upscaler.py:195
|
||||
msgid "Please check the configuration file settings"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:194
|
||||
msgid "Specified driver executable directory doesn't exist"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:221
|
||||
msgid "Failed to parse driver argument: {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:253
|
||||
msgid "Unrecognized driver: {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:293
|
||||
msgid "Starting progress monitor"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:298
|
||||
msgid "Starting upscaled image cleaner"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:307 upscaler.py:324
|
||||
msgid "Killing progress monitor"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:310 upscaler.py:327
|
||||
msgid "Killing upscaled image cleaner"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:331
|
||||
msgid "Terminating all processes"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:338
|
||||
msgid "Main process waiting for subprocesses to exit"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:357 upscaler.py:361
|
||||
msgid "Subprocess {} exited with code {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:367
|
||||
msgid "Stop signal received"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:372
|
||||
msgid "Subprocess execution ran into an error"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:421
|
||||
msgid "Upscaling single video file: {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:443 upscaler.py:502
|
||||
msgid "Starting to upscale extracted images"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:448 upscaler.py:504
|
||||
msgid "Upscaling completed"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:457
|
||||
msgid "Reading video information"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:471
|
||||
msgid "Aborting: No video stream found"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:490
|
||||
msgid "Unsupported pixel format: {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:493
|
||||
msgid "Framerate: {}"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:507
|
||||
msgid "Converting extracted frames into video"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:514
|
||||
msgid "Conversion completed"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:518
|
||||
msgid "Migrating audio, subtitles and other streams to upscaled video"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:527
|
||||
msgid "Failed to migrate streams"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:528
|
||||
msgid "Trying to output video without additional streams"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:535
|
||||
msgid "Output video file exists, aborting"
|
||||
msgstr ""
|
||||
|
||||
#: upscaler.py:539
|
||||
msgid "Writing intermediate file to: {}"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:84
|
||||
msgid ""
|
||||
"Video2X Version: {}\n"
|
||||
"Author: K4YT3X\n"
|
||||
"License: GNU GPL v3\n"
|
||||
"Github Page: https://github.com/k4yt3x/video2x\n"
|
||||
"Contact: k4yt3x@k4yt3x.com"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:106
|
||||
msgid "Video2X Options"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:107
|
||||
msgid "show this help message and exit"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:108
|
||||
msgid "source video file/directory"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:109
|
||||
msgid "output video file/directory"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:110
|
||||
msgid "video2x config file path"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:112
|
||||
msgid "display version, lawful information and exit"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:115
|
||||
msgid "Upscaling Options"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:116
|
||||
msgid "upscaling driver"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:117
|
||||
msgid "scaling ratio"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:118
|
||||
msgid "number of processes to use for upscaling"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:119
|
||||
msgid "preserve extracted and upscaled frames"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:159
|
||||
msgid "This file cannot be imported"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:229
|
||||
msgid "Program completed, taking {} seconds"
|
||||
msgstr ""
|
||||
|
||||
#: video2x.py:232
|
||||
msgid "An exception has occurred"
|
||||
msgstr ""
|
||||
|
||||
233
src/video2x.py
Executable file
233
src/video2x.py
Executable file
@@ -0,0 +1,233 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
r"""
|
||||
|
||||
__ __ _ _ ___ __ __
|
||||
\ \ / / (_) | | |__ \ \ \ / /
|
||||
\ \ / / _ __| | ___ ___ ) | \ V /
|
||||
\ \/ / | | / _` | / _ \ / _ \ / / > <
|
||||
\ / | | | (_| | | __/ | (_) | / /_ / . \
|
||||
\/ |_| \__,_| \___| \___/ |____| /_/ \_\
|
||||
|
||||
|
||||
Name: Video2X Controller
|
||||
Creator: K4YT3X
|
||||
Date Created: Feb 24, 2018
|
||||
Last Modified: May 10, 2020
|
||||
|
||||
Editor: BrianPetkovsek
|
||||
Last Modified: June 17, 2019
|
||||
|
||||
Editor: SAT3LL
|
||||
Last Modified: June 25, 2019
|
||||
|
||||
Editor: 28598519a
|
||||
Last Modified: March 23, 2020
|
||||
|
||||
Licensed under the GNU General Public License Version 3 (GNU GPL v3),
|
||||
available at: https://www.gnu.org/licenses/gpl-3.0.txt
|
||||
|
||||
(C) 2018 - 2020 K4YT3X
|
||||
|
||||
Video2X is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Video2X is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Description: Video2X is an automation software based on waifu2x image
|
||||
enlarging engine. It extracts frames from a video, enlarge it by a
|
||||
number of times without losing any details or quality, keeping lines
|
||||
smooth and edges sharp.
|
||||
"""
|
||||
|
||||
# local imports
|
||||
from upscaler import AVAILABLE_DRIVERS
|
||||
from upscaler import Upscaler
|
||||
|
||||
# built-in imports
|
||||
import argparse
|
||||
import gettext
|
||||
import importlib
|
||||
import locale
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
import yaml
|
||||
|
||||
# third-party imports
|
||||
from avalon_framework import Avalon
|
||||
|
||||
# internationalization constants
|
||||
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.install()
|
||||
_ = language.gettext
|
||||
|
||||
|
||||
VERSION = '4.0.0'
|
||||
|
||||
LEGAL_INFO = _('''Video2X Version: {}
|
||||
Author: K4YT3X
|
||||
License: GNU GPL v3
|
||||
Github Page: https://github.com/k4yt3x/video2x
|
||||
Contact: k4yt3x@k4yt3x.com''').format(VERSION)
|
||||
|
||||
LOGO = r'''
|
||||
__ __ _ _ ___ __ __
|
||||
\ \ / / (_) | | |__ \ \ \ / /
|
||||
\ \ / / _ __| | ___ ___ ) | \ V /
|
||||
\ \/ / | | / _` | / _ \ / _ \ / / > <
|
||||
\ / | | | (_| | | __/ | (_) | / /_ / . \
|
||||
\/ |_| \__,_| \___| \___/ |____| /_/ \_\
|
||||
'''
|
||||
|
||||
|
||||
def parse_arguments():
|
||||
""" 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('-h', '--help', action='help', help=_('show this help message and exit'))
|
||||
video2x_options.add_argument('-i', '--input', type=pathlib.Path, help=_('source video file/directory'))
|
||||
video2x_options.add_argument('-o', '--output', type=pathlib.Path, help=_('output video file/directory'))
|
||||
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('-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('-d', '--driver', help=_('upscaling driver'), choices=AVAILABLE_DRIVERS, default='waifu2x_caffe')
|
||||
upscaling_options.add_argument('-r', '--ratio', help=_('scaling ratio'), action='store', type=float, default=2.0)
|
||||
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:
|
||||
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:])
|
||||
return video2x_args, driver_args
|
||||
|
||||
|
||||
def print_logo():
|
||||
"""print video2x logo"""
|
||||
print(LOGO)
|
||||
print(f'\n{"Video2X Video Enlarger".rjust(40, " ")}')
|
||||
print(f'\n{Avalon.FM.BD}{f"Version {VERSION}".rjust(36, " ")}{Avalon.FM.RST}\n')
|
||||
|
||||
|
||||
def read_config(config_file: pathlib.Path) -> dict:
|
||||
""" read video2x configurations from config file
|
||||
|
||||
Arguments:
|
||||
config_file {pathlib.Path} -- video2x configuration file pathlib.Path
|
||||
|
||||
Returns:
|
||||
dict -- dictionary of video2x configuration
|
||||
"""
|
||||
|
||||
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')
|
||||
|
||||
# print video2x logo
|
||||
print_logo()
|
||||
|
||||
# parse command line arguments
|
||||
video2x_args, driver_args = parse_arguments()
|
||||
|
||||
# display version and lawful informaition
|
||||
if video2x_args.version:
|
||||
print(LEGAL_INFO)
|
||||
sys.exit(0)
|
||||
|
||||
# read configurations from configuration file
|
||||
config = read_config(video2x_args.config)
|
||||
|
||||
# load waifu2x configuration
|
||||
driver_settings = config[video2x_args.driver]
|
||||
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'])
|
||||
|
||||
# load video2x settings
|
||||
image_format = config['video2x']['image_format'].lower()
|
||||
preserve_frames = config['video2x']['preserve_frames']
|
||||
|
||||
# if preserve frames specified in command line
|
||||
# overwrite config file options
|
||||
if video2x_args.preserve_frames is True:
|
||||
preserve_frames = 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')
|
||||
else:
|
||||
video2x_cache_directory = pathlib.Path(config['video2x']['video2x_cache_directory'])
|
||||
|
||||
# overwrite driver_settings with driver_args
|
||||
if driver_args is not None:
|
||||
driver_args_dict = vars(driver_args)
|
||||
for key in driver_args_dict:
|
||||
if driver_args_dict[key] is not None:
|
||||
driver_settings[key] = driver_args_dict[key]
|
||||
|
||||
# start execution
|
||||
try:
|
||||
# start timer
|
||||
begin_time = time.time()
|
||||
|
||||
# initialize upscaler object
|
||||
upscaler = Upscaler(input_path=video2x_args.input,
|
||||
output_path=video2x_args.output,
|
||||
driver_settings=driver_settings,
|
||||
ffmpeg_settings=ffmpeg_settings)
|
||||
|
||||
# set upscaler optional options
|
||||
upscaler.driver = video2x_args.driver
|
||||
upscaler.scale_ratio = video2x_args.ratio
|
||||
upscaler.processes = video2x_args.processes
|
||||
upscaler.video2x_cache_directory = video2x_cache_directory
|
||||
upscaler.image_format = image_format
|
||||
upscaler.preserve_frames = preserve_frames
|
||||
|
||||
# run upscaler
|
||||
upscaler.run()
|
||||
|
||||
Avalon.info(_('Program completed, taking {} seconds').format(round((time.time() - begin_time), 5)))
|
||||
|
||||
except Exception:
|
||||
Avalon.error(_('An exception has occurred'))
|
||||
traceback.print_exc()
|
||||
144
src/video2x.yaml
Normal file
144
src/video2x.yaml
Normal file
@@ -0,0 +1,144 @@
|
||||
# Name: Video2X Configuration File
|
||||
# Creator: K4YT3X
|
||||
# Date Created: October 23, 2018
|
||||
# Last Modified: May 9, 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
|
||||
# or parameters handled by Video2X internally.
|
||||
waifu2x_caffe:
|
||||
path: '%LOCALAPPDATA%\video2x\waifu2x-caffe\waifu2x-caffe-cui'
|
||||
tta: 0 # <0|1> 8x slower and slightly high quality
|
||||
gpu: 0 # gpu device no
|
||||
batch_size: 1 # input batch size
|
||||
crop_h: null # input image split size(height)
|
||||
crop_w: null # input image split size(width)
|
||||
crop_size: 128 # input image split size
|
||||
output_depth: 8 # output image chanel depth bit
|
||||
output_quality: -1 # output image quality
|
||||
process: gpu # <cpu|gpu|cudnn> process mode
|
||||
model_dir: null # path to custom model directory (don't append last / )
|
||||
scale_height: 0 # custom scale height (specifying this will overwrite scale_ratio)
|
||||
scale_width: 0 # custom scale width (specifying this will overwrite scale_ratio)
|
||||
#scale_ratio: null # custom scale ratio
|
||||
noise_level: 3 # <0|1|2|3> noise reduction level
|
||||
mode: noise_scale # <noise|scale|noise_scale|auto_scale> image processing mode
|
||||
output_extention: null # extension to output image file when output_path is (auto) or input_path is folder
|
||||
input_extention_list: null # extension to input image file when input_path is folder
|
||||
#output_path: null # path to output image file (when input_path is folder, output_path must be folder)
|
||||
#input_path: null # (required) path to input image file
|
||||
waifu2x_converter_cpp:
|
||||
path: '%LOCALAPPDATA%\video2x\waifu2x-converter-cpp\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
|
||||
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
|
||||
disable-gpu: false # disable GPU
|
||||
force-OpenCL: false # force to use OpenCL on Intel Platform
|
||||
processor: -1 # set target processor (-1 uses default device)
|
||||
jobs: 0 # number of threads launching at the same time
|
||||
model-dir: null # path to custom model directory (don't append last / ) default: models_rgb
|
||||
#scale-ratio: 2.0 # custom scale ratio
|
||||
noise-level: 1 # <0|1|2|3> noise reduction level
|
||||
mode: noise-scale # <noise|scale|noise-scale> image processing mode
|
||||
log-level: 1 # <0|1|2|3|4> Set log level
|
||||
silent: true # Enable silent mode. (same as --log-level 1)
|
||||
tta: 0 # Enable Test-Time Augmentation mode. (0 or 1)
|
||||
#generate-subdir: 0 # Generate sub folder when recursive directory is enabled.
|
||||
#auto-naming: 0 # Add postfix to output name when output path is not specified.
|
||||
#recursive-directory: 0 # Search recursively through directories to find more images to process.
|
||||
#output: null # path to output image file or directory (you should use the full path)
|
||||
#input: null # (required) path to input image file or directory (you should use the full path)
|
||||
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
|
||||
'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)
|
||||
x: false # enable tta mode
|
||||
srmd_ncnn_vulkan:
|
||||
path: '%LOCALAPPDATA%\video2x\srmd-ncnn-vulkan\srmd-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
|
||||
'n': 3 # noise-level: denoise level (-1/0/1/2/3/4/5/6/7/8/9/10, default=3)
|
||||
s: 2 # upscale ratio (2/3/4, default=2)
|
||||
t: 400 # tile-size: tile size (>=32, default=400)
|
||||
m: null # srmd model path (default=models-srmd)
|
||||
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
|
||||
anime4kcpp:
|
||||
path: '%LOCALAPPDATA%\video2x\anime4kcpp\CLI\Anime4KCPP_CLI\Anime4KCPP_CLI'
|
||||
#input: null # File for loading (string [=./pic/p1.png])
|
||||
#output: null # File for outputting (string [=output.png])
|
||||
passes: 2 # Passes for processing (int [=2])
|
||||
pushColorCount: 2 # Limit the number of color pushes (int [=2])
|
||||
strengthColor: 0.3 # Strength for pushing color,range 0 to 1,higher for thinner (double [=0.3])
|
||||
strengthGradient: 1.0 # Strength for pushing gradient,range 0 to 1,higher for sharper (double [=1])
|
||||
zoomFactor: 2.0 # zoom factor for resizing (double [=2])
|
||||
threads: 16 # Threads count for video processing (unsigned int [=16])
|
||||
fastMode: false # Faster but maybe low quality
|
||||
videoMode: true # Video process
|
||||
preview: null # Preview image
|
||||
preprocessing: False # Enable pre processing
|
||||
postprocessing: False # Enable post processing
|
||||
preFilters: 4 # 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) (unsigned int [=4])
|
||||
postFilters: 40 # 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 (unsigned int [=40])
|
||||
GPUMode: False # Enable GPU acceleration
|
||||
listGPUs: null # list GPUs
|
||||
platformID: 0 # Specify the platform ID (unsigned int [=0])
|
||||
deviceID: 0 # Specify the device ID (unsigned int [=0])
|
||||
codec: mp4v # 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])
|
||||
ffmpeg:
|
||||
ffmpeg_path: '%LOCALAPPDATA%\video2x\ffmpeg-latest-win64-static\bin'
|
||||
intermediate_file_name: 'intermediate.mkv'
|
||||
# step 1: extract all frames from original video
|
||||
# into temporary directory
|
||||
video_to_frames:
|
||||
output_options:
|
||||
'-qscale:v': null
|
||||
'-pix_fmt': rgba64be
|
||||
'-hwaccel': auto
|
||||
'-y': true
|
||||
# step 2: stitch all frames back into a video
|
||||
# with only a video track
|
||||
frames_to_video:
|
||||
input_options:
|
||||
'-qscale:v': null
|
||||
'-qscale:a': null
|
||||
'-f': image2
|
||||
output_options:
|
||||
'-vcodec': libx264
|
||||
'-crf': 17
|
||||
'-b:v': null
|
||||
'-pix_fmt': null
|
||||
'-hwaccel': auto
|
||||
'-y': true
|
||||
# step 3: migrate audio and subtitle tracks from original
|
||||
# video into the upscaled video
|
||||
migrating_tracks:
|
||||
output_options:
|
||||
'-map':
|
||||
- '0:v?'
|
||||
- '1:a?'
|
||||
- '1:s?'
|
||||
- '1:d?'
|
||||
- '1:t?'
|
||||
'-c': copy
|
||||
'-pix_fmt': null
|
||||
'-metadata': 'comment=Upscaled by Video2X'
|
||||
'-hwaccel': auto
|
||||
'-y': true
|
||||
video2x:
|
||||
video2x_cache_directory: null # default: %TEMP%\video2x
|
||||
image_format: png
|
||||
preserve_frames: false
|
||||
874
src/video2x_gui.py
Executable file
874
src/video2x_gui.py
Executable file
@@ -0,0 +1,874 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Creator: Video2X GUI
|
||||
Author: K4YT3X
|
||||
Date Created: May 5, 2020
|
||||
Last Modified: May 10, 2020
|
||||
"""
|
||||
|
||||
# local imports
|
||||
from upscaler import Upscaler
|
||||
|
||||
# built-in imports
|
||||
import contextlib
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
import urllib
|
||||
import yaml
|
||||
|
||||
# third-party imports
|
||||
from PyQt5 import QtGui, uic
|
||||
from PyQt5.QtCore import *
|
||||
from PyQt5.QtWidgets import *
|
||||
# QObject, pyqtSlot, pyqtSignal, QRunnable, QThreadPool, QAbstractTableModel, Qt
|
||||
|
||||
VERSION = '2.0.0'
|
||||
|
||||
LEGAL_INFO = f'''Video2X GUI Version: {VERSION}\\
|
||||
Author: K4YT3X\\
|
||||
License: GNU GPL v3\\
|
||||
Github Page: [https://github.com/k4yt3x/video2x](https://github.com/k4yt3x/video2x)\\
|
||||
Contact: [k4yt3x@k4yt3x.com](mailto:k4yt3x@k4yt3x.com)'''
|
||||
|
||||
AVAILABLE_DRIVERS = {
|
||||
'Waifu2X Caffe': 'waifu2x_caffe',
|
||||
'Waifu2X Converter CPP': 'waifu2x_converter_cpp',
|
||||
'Waifu2X NCNN Vulkan': 'waifu2x_ncnn_vulkan',
|
||||
'SRMD NCNN Vulkan': 'srmd_ncnn_vulkan',
|
||||
'Anime4KCPP': 'anime4kcpp'
|
||||
}
|
||||
|
||||
|
||||
def resource_path(relative_path: str) -> pathlib.Path:
|
||||
try:
|
||||
base_path = pathlib.Path(sys._MEIPASS)
|
||||
except AttributeError:
|
||||
base_path = pathlib.Path(__file__).parent
|
||||
return base_path / relative_path
|
||||
|
||||
|
||||
class WorkerSignals(QObject):
|
||||
progress = pyqtSignal(tuple)
|
||||
error = pyqtSignal(Exception)
|
||||
interrupted = pyqtSignal()
|
||||
finished = pyqtSignal()
|
||||
|
||||
|
||||
class ProgressMonitorWorkder(QRunnable):
|
||||
def __init__(self, fn, *args, **kwargs):
|
||||
super(ProgressMonitorWorkder, self).__init__()
|
||||
self.fn = fn
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
self.signals = WorkerSignals()
|
||||
self.kwargs['progress_callback'] = self.signals.progress
|
||||
|
||||
@pyqtSlot()
|
||||
def run(self):
|
||||
try:
|
||||
self.fn(*self.args, **self.kwargs)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class UpscalerWorker(QRunnable):
|
||||
|
||||
def __init__(self, fn, *args, **kwargs):
|
||||
super(UpscalerWorker, self).__init__()
|
||||
|
||||
# Store constructor arguments (re-used for processing)
|
||||
self.fn = fn
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
self.signals = WorkerSignals()
|
||||
|
||||
@pyqtSlot()
|
||||
def run(self):
|
||||
|
||||
# Retrieve args/kwargs here; and fire processing using them
|
||||
try:
|
||||
self.fn(*self.args, **self.kwargs)
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
self.signals.interrupted.emit()
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
self.signals.error.emit(e)
|
||||
else:
|
||||
self.signals.finished.emit()
|
||||
|
||||
|
||||
class InputTableModel(QAbstractTableModel):
|
||||
def __init__(self, data):
|
||||
super(InputTableModel, self).__init__()
|
||||
self._data = data
|
||||
|
||||
def data(self, index, role):
|
||||
if role == Qt.DisplayRole:
|
||||
|
||||
if index.column() == 0:
|
||||
return str(self._data[index.row()].absolute())
|
||||
else:
|
||||
if self._data[index.row()].is_file():
|
||||
return 'File'
|
||||
elif self._data[index.row()].is_dir():
|
||||
return 'Folder'
|
||||
else:
|
||||
return 'Unknown'
|
||||
|
||||
def rowCount(self, index):
|
||||
return len(self._data)
|
||||
|
||||
def columnCount(self, index):
|
||||
return 2
|
||||
|
||||
def removeRow(self, index):
|
||||
self._data.pop(index)
|
||||
|
||||
def headerData(self, section, orientation, role):
|
||||
# section is the index of the column/row.
|
||||
if role != Qt.DisplayRole:
|
||||
return None
|
||||
|
||||
horizontal_headers = ['File Path', 'Type']
|
||||
|
||||
# return the correspondign header
|
||||
if orientation == Qt.Horizontal:
|
||||
return horizontal_headers[section]
|
||||
|
||||
# simply return the line number
|
||||
if orientation == Qt.Vertical:
|
||||
return str(section)
|
||||
|
||||
|
||||
class Video2XMainWindow(QMainWindow):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
uic.loadUi(str(resource_path('video2x_gui.ui')), self)
|
||||
|
||||
# create thread pool for upscaler workers
|
||||
self.threadpool = QThreadPool()
|
||||
|
||||
# set window title and icon
|
||||
self.video2x_icon_path = str(resource_path('images/video2x.png'))
|
||||
self.setWindowTitle(f'Video2X GUI {VERSION}')
|
||||
self.setWindowIcon(QtGui.QIcon(self.video2x_icon_path))
|
||||
|
||||
# menu bar
|
||||
self.action_exit = self.findChild(QAction, 'actionExit')
|
||||
self.action_exit.triggered.connect(sys.exit)
|
||||
|
||||
self.action_about = self.findChild(QAction, 'actionAbout')
|
||||
self.action_about.triggered.connect(self.show_about)
|
||||
|
||||
# main tab
|
||||
# select input file/folder
|
||||
self.input_table_view = self.findChild(QTableView, 'inputTableView')
|
||||
self.input_table_view.dragEnterEvent = self.dragEnterEvent
|
||||
self.input_table_view.dropEvent = self.dropEvent
|
||||
|
||||
# initialize data in table
|
||||
self.input_table_data = []
|
||||
self.input_table_model = InputTableModel(self.input_table_data)
|
||||
self.input_table_view.setModel(self.input_table_model)
|
||||
# stretch file path and fill columns horizontally
|
||||
self.input_table_view.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
|
||||
|
||||
# input table buttons
|
||||
self.input_select_file_button = self.findChild(QPushButton, 'inputSelectFileButton')
|
||||
self.input_select_file_button.clicked.connect(self.select_input_file)
|
||||
self.input_select_folder_button = self.findChild(QPushButton, 'inputSelectFolderButton')
|
||||
self.input_select_folder_button.clicked.connect(self.select_input_folder)
|
||||
self.input_delete_selected_button = self.findChild(QPushButton, 'inputDeleteSelectedButton')
|
||||
self.input_delete_selected_button.clicked.connect(self.input_table_delete_selected)
|
||||
self.input_clear_all_button = self.findChild(QPushButton, 'inputClearAllButton')
|
||||
self.input_clear_all_button.clicked.connect(self.input_table_clear_all)
|
||||
|
||||
# other paths selection
|
||||
# select output file/folder
|
||||
self.output_line_edit = self.findChild(QLineEdit, 'outputLineEdit')
|
||||
self.enable_line_edit_file_drop(self.output_line_edit)
|
||||
self.output_line_edit.setText(str((pathlib.Path().cwd() / 'output').absolute()))
|
||||
self.output_select_file_button = self.findChild(QPushButton, 'outputSelectFileButton')
|
||||
self.output_select_file_button.clicked.connect(self.select_output_file)
|
||||
self.output_select_folder_button = self.findChild(QPushButton, 'outputSelectFolderButton')
|
||||
self.output_select_folder_button.clicked.connect(self.select_output_folder)
|
||||
|
||||
# config file
|
||||
self.config_line_edit = self.findChild(QLineEdit, 'configLineEdit')
|
||||
self.enable_line_edit_file_drop(self.config_line_edit)
|
||||
self.config_line_edit.setText(str((pathlib.Path(__file__).parent / 'video2x.yaml').absolute()))
|
||||
self.config_select_file_button = self.findChild(QPushButton, 'configSelectButton')
|
||||
self.config_select_file_button.clicked.connect(self.select_config_file)
|
||||
|
||||
# cache directory
|
||||
self.cache_line_edit = self.findChild(QLineEdit, 'cacheLineEdit')
|
||||
self.enable_line_edit_file_drop(self.cache_line_edit)
|
||||
self.cache_select_folder_button = self.findChild(QPushButton, 'cacheSelectFolderButton')
|
||||
self.cache_select_folder_button.clicked.connect(self.select_cache_folder)
|
||||
|
||||
# express settings
|
||||
self.driver_combo_box = self.findChild(QComboBox, 'driverComboBox')
|
||||
self.driver_combo_box.currentTextChanged.connect(self.update_gui_for_driver)
|
||||
self.processes_spin_box = self.findChild(QSpinBox, 'processesSpinBox')
|
||||
self.scale_ratio_double_spin_box = self.findChild(QDoubleSpinBox, 'scaleRatioDoubleSpinBox')
|
||||
self.preserve_frames_check_box = self.findChild(QCheckBox, 'preserveFramesCheckBox')
|
||||
|
||||
# frame preview
|
||||
self.frame_preview_show_preview_check_box = self.findChild(QCheckBox, 'framePreviewShowPreviewCheckBox')
|
||||
self.frame_preview_keep_aspect_ratio_check_box = self.findChild(QCheckBox, 'framePreviewKeepAspectRatioCheckBox')
|
||||
self.frame_preview_label = self.findChild(QLabel, 'framePreviewLabel')
|
||||
|
||||
# currently processing
|
||||
self.currently_processing_label = self.findChild(QLabel, 'currentlyProcessingLabel')
|
||||
self.current_progress_bar = self.findChild(QProgressBar, 'currentProgressBar')
|
||||
self.time_elapsed_label = self.findChild(QLabel, 'timeElapsedLabel')
|
||||
self.time_remaining_label = self.findChild(QLabel, 'timeRemainingLabel')
|
||||
self.rate_label = self.findChild(QLabel, 'rateLabel')
|
||||
self.frames_label = self.findChild(QLabel, 'framesLabel')
|
||||
|
||||
# overall progress
|
||||
self.overall_progress_bar = self.findChild(QProgressBar, 'overallProgressBar')
|
||||
self.overall_progress_label = self.findChild(QLabel, 'overallProgressLabel')
|
||||
self.start_button = self.findChild(QPushButton, 'startButton')
|
||||
self.start_button.clicked.connect(self.start)
|
||||
self.stop_button = self.findChild(QPushButton, 'stopButton')
|
||||
self.stop_button.clicked.connect(self.stop)
|
||||
|
||||
# driver settings
|
||||
# waifu2x-caffe
|
||||
self.waifu2x_caffe_path_line_edit = self.findChild(QLineEdit, 'waifu2xCaffePathLineEdit')
|
||||
self.enable_line_edit_file_drop(self.waifu2x_caffe_path_line_edit)
|
||||
self.waifu2x_caffe_path_select_button = self.findChild(QPushButton, 'waifu2xCaffePathSelectButton')
|
||||
self.waifu2x_caffe_path_select_button.clicked.connect(lambda: self.select_driver_binary_path(self.waifu2x_caffe_path_line_edit))
|
||||
self.waifu2x_caffe_scale_width_spin_box = self.findChild(QSpinBox, 'waifu2xCaffeScaleWidthSpinBox')
|
||||
self.waifu2x_caffe_scale_height_spin_box = self.findChild(QSpinBox, 'waifu2xCaffeScaleHeightSpinBox')
|
||||
self.waifu2x_caffe_mode_combo_box = self.findChild(QComboBox, 'waifu2xCaffeModeComboBox')
|
||||
self.waifu2x_caffe_noise_level_spin_box = self.findChild(QSpinBox, 'waifu2xCaffeNoiseLevelSpinBox')
|
||||
self.waifu2x_caffe_process_combo_box = self.findChild(QComboBox, 'waifu2xCaffeProcessComboBox')
|
||||
self.waifu2x_caffe_model_combobox = self.findChild(QComboBox, 'waifu2xCaffeModelComboBox')
|
||||
self.waifu2x_caffe_crop_size_spin_box = self.findChild(QSpinBox, 'waifu2xCaffeCropSizeSpinBox')
|
||||
self.waifu2x_caffe_output_quality_spin_box = self.findChild(QSpinBox, 'waifu2xCaffeOutputQualitySpinBox')
|
||||
self.waifu2x_caffe_output_depth_spin_box = self.findChild(QSpinBox, 'waifu2xCaffeOutputDepthSpinBox')
|
||||
self.waifu2x_caffe_batch_size_spin_box = self.findChild(QSpinBox, 'waifu2xCaffeBatchSizeSpinBox')
|
||||
self.waifu2x_caffe_gpu_spin_box = self.findChild(QSpinBox, 'waifu2xCaffeGpuSpinBox')
|
||||
self.waifu2x_caffe_tta_check_box = self.findChild(QCheckBox, 'waifu2xCaffeTtaCheckBox')
|
||||
|
||||
# waifu2x-converter-cpp
|
||||
self.waifu2x_converter_cpp_path_line_edit = self.findChild(QLineEdit, 'waifu2xConverterCppPathLineEdit')
|
||||
self.enable_line_edit_file_drop(self.waifu2x_converter_cpp_path_line_edit)
|
||||
self.waifu2x_converter_cpp_path_edit_button = self.findChild(QPushButton, 'waifu2xConverterCppPathSelectButton')
|
||||
self.waifu2x_converter_cpp_path_edit_button.clicked.connect(lambda: self.select_driver_binary_path(self.waifu2x_converter_cpp_path_line_edit))
|
||||
self.waifu2x_converter_cpp_png_compression_spin_box = self.findChild(QSpinBox, 'waifu2xConverterCppPngCompressionSpinBox')
|
||||
self.waifu2x_converter_cpp_image_quality_spin_box = self.findChild(QSpinBox, 'waifu2xConverterCppImageQualitySpinBox')
|
||||
self.waifu2x_converter_cpp_block_size_spin_box = self.findChild(QSpinBox, 'waifu2xConverterCppBlockSizeSpinBox')
|
||||
self.waifu2x_converter_cpp_processor_spin_box = self.findChild(QSpinBox, 'waifu2xConverterCppProcessorSpinBox')
|
||||
self.waifu2x_converter_cpp_model_combo_box = self.findChild(QComboBox, 'waifu2xConverterCppModelComboBox')
|
||||
self.waifu2x_converter_cpp_noise_level_spin_box = self.findChild(QSpinBox, 'waifu2xConverterCppNoiseLevelSpinBox')
|
||||
self.waifu2x_converter_cpp_mode_combo_box = self.findChild(QComboBox, 'waifu2xConverterCppModeComboBox')
|
||||
self.waifu2x_converter_cpp_log_level_spin_box = self.findChild(QSpinBox, 'waifu2xConverterCppLogLevelSpinBox')
|
||||
self.waifu2x_converter_cpp_disable_gpu_check_box = self.findChild(QCheckBox, 'waifu2xConverterCppDisableGpuCheckBox')
|
||||
self.waifu2x_converter_cpp_force_opencl_check_box = self.findChild(QCheckBox, 'waifu2xConverterCppForceOpenclCheckBox')
|
||||
self.waifu2x_converter_cpp_tta_check_box = self.findChild(QCheckBox, 'waifu2xConverterCppTtaCheckBox')
|
||||
|
||||
# waifu2x-ncnn-vulkan
|
||||
self.waifu2x_ncnn_vulkan_path_line_edit = self.findChild(QLineEdit, 'waifu2xNcnnVulkanPathLineEdit')
|
||||
self.enable_line_edit_file_drop(self.waifu2x_ncnn_vulkan_path_line_edit)
|
||||
self.waifu2x_ncnn_vulkan_path_select_button = self.findChild(QPushButton, 'waifu2xNcnnVulkanPathSelectButton')
|
||||
self.waifu2x_ncnn_vulkan_path_select_button.clicked.connect(lambda: self.select_driver_binary_path(self.waifu2x_ncnn_vulkan_path_line_edit))
|
||||
self.waifu2x_ncnn_vulkan_noise_level_spin_box = self.findChild(QSpinBox, 'waifu2xNcnnVulkanNoiseLevelSpinBox')
|
||||
self.waifu2x_ncnn_vulkan_tile_size_spin_box = self.findChild(QSpinBox, 'waifu2xNcnnVulkanTileSizeSpinBox')
|
||||
self.waifu2x_ncnn_vulkan_model_combo_box = self.findChild(QComboBox, 'waifu2xNcnnVulkanModelComboBox')
|
||||
self.waifu2x_ncnn_vulkan_gpu_id_spin_box = self.findChild(QSpinBox, 'waifu2xNcnnVulkanGpuIdSpinBox')
|
||||
self.waifu2x_ncnn_vulkan_jobs_line_edit = self.findChild(QLineEdit, 'waifu2xNcnnVulkanJobsLineEdit')
|
||||
self.waifu2x_ncnn_vulkan_tta_check_box = self.findChild(QCheckBox, 'waifu2xNcnnVulkanTtaCheckBox')
|
||||
|
||||
# srmd-ncnn-vulkan
|
||||
self.srmd_ncnn_vulkan_path_line_edit = self.findChild(QLineEdit, 'srmdNcnnVulkanPathLineEdit')
|
||||
self.enable_line_edit_file_drop(self.srmd_ncnn_vulkan_path_line_edit)
|
||||
self.srmd_ncnn_vulkan_path_select_button = self.findChild(QPushButton, 'srmdNcnnVulkanPathSelectButton')
|
||||
self.srmd_ncnn_vulkan_path_select_button.clicked.connect(lambda: self.select_driver_binary_path(self.srmd_ncnn_vulkan_path_line_edit))
|
||||
self.srmd_ncnn_vulkan_noise_level_spin_box = self.findChild(QSpinBox, 'srmdNcnnVulkanNoiseLevelSpinBox')
|
||||
self.srmd_ncnn_vulkan_tile_size_spin_box = self.findChild(QSpinBox, 'srmdNcnnVulkanTileSizeSpinBox')
|
||||
self.srmd_ncnn_vulkan_model_combo_box = self.findChild(QComboBox, 'srmdNcnnVulkanModelComboBox')
|
||||
self.srmd_ncnn_vulkan_gpu_id_spin_box = self.findChild(QSpinBox, 'srmdNcnnVulkanGpuIdSpinBox')
|
||||
self.srmd_ncnn_vulkan_jobs_line_edit = self.findChild(QLineEdit, 'srmdNcnnVulkanJobsLineEdit')
|
||||
self.srmd_ncnn_vulkan_tta_check_box = self.findChild(QCheckBox, 'srmdNcnnVulkanTtaCheckBox')
|
||||
|
||||
# anime4k
|
||||
self.anime4kcpp_path_line_edit = self.findChild(QLineEdit, 'anime4kCppPathLineEdit')
|
||||
self.enable_line_edit_file_drop(self.anime4kcpp_path_line_edit)
|
||||
self.anime4kcpp_path_select_button = self.findChild(QPushButton, 'anime4kCppPathSelectButton')
|
||||
self.anime4kcpp_path_select_button.clicked.connect(lambda: self.select_driver_binary_path(self.anime4kcpp_path_line_edit))
|
||||
self.anime4kcpp_passes_spin_box = self.findChild(QSpinBox, 'anime4kCppPassesSpinBox')
|
||||
self.anime4kcpp_push_color_count_spin_box = self.findChild(QSpinBox, 'anime4kCppPushColorCountSpinBox')
|
||||
self.anime4kcpp_strength_color_spin_box = self.findChild(QDoubleSpinBox, 'anime4kCppStrengthColorSpinBox')
|
||||
self.anime4kcpp_strength_gradient_spin_box = self.findChild(QDoubleSpinBox, 'anime4kCppStrengthGradientSpinBox')
|
||||
self.anime4kcpp_threads_spin_box = self.findChild(QSpinBox, 'anime4kCppThreadsSpinBox')
|
||||
self.anime4kcpp_pre_filters_spin_box = self.findChild(QSpinBox, 'anime4kCppPreFiltersSpinBox')
|
||||
self.anime4kcpp_post_filters_spin_box = self.findChild(QSpinBox, 'anime4kCppPostFiltersSpinBox')
|
||||
self.anime4kcpp_platform_id_spin_box = self.findChild(QSpinBox, 'anime4kCppPlatformIdSpinBox')
|
||||
self.anime4kcpp_device_id_spin_box = self.findChild(QSpinBox, 'anime4kCppDeviceIdSpinBox')
|
||||
self.anime4kcpp_codec_combo_box = self.findChild(QComboBox, 'anime4kCppCodecComboBox')
|
||||
self.anime4kcpp_fast_mode_check_box = self.findChild(QCheckBox, 'anime4kCppFastModeCheckBox')
|
||||
self.anime4kcpp_pre_processing_check_box = self.findChild(QCheckBox, 'anime4kCppPreProcessingCheckBox')
|
||||
self.anime4kcpp_post_processing_check_box = self.findChild(QCheckBox, 'anime4kCppPostProcessingCheckBox')
|
||||
self.anime4kcpp_gpu_mode_check_box = self.findChild(QCheckBox, 'anime4kCppGpuModeCheckBox')
|
||||
|
||||
# load configurations
|
||||
self.load_configurations()
|
||||
|
||||
def dragEnterEvent(self, event):
|
||||
if event.mimeData().hasUrls():
|
||||
event.accept()
|
||||
else:
|
||||
event.ignore()
|
||||
|
||||
def dropEvent(self, event):
|
||||
input_paths = [pathlib.Path(u.toLocalFile()) for u in event.mimeData().urls()]
|
||||
for path in input_paths:
|
||||
if (path.is_file() or path.is_dir()) and not self.input_table_path_exists(path):
|
||||
self.input_table_data.append(path)
|
||||
|
||||
self.update_input_table()
|
||||
self.update_output_path()
|
||||
|
||||
def enable_line_edit_file_drop(self, line_edit: QLineEdit):
|
||||
line_edit.dragEnterEvent = self.dragEnterEvent
|
||||
line_edit.dropEvent = lambda event: line_edit.setText(str(pathlib.Path(event.mimeData().urls()[0].toLocalFile()).absolute()))
|
||||
|
||||
@staticmethod
|
||||
def read_config(config_file: pathlib.Path) -> dict:
|
||||
""" read video2x configurations from config file
|
||||
|
||||
Arguments:
|
||||
config_file {pathlib.Path} -- video2x configuration file pathlib.Path
|
||||
|
||||
Returns:
|
||||
dict -- dictionary of video2x configuration
|
||||
"""
|
||||
|
||||
with open(config_file, 'r') as config:
|
||||
return yaml.load(config, Loader=yaml.FullLoader)
|
||||
|
||||
def load_configurations(self):
|
||||
|
||||
# get config file path from line edit
|
||||
config_file_path = pathlib.Path(os.path.expandvars(self.config_line_edit.text()))
|
||||
|
||||
# if file doesn't exist, return
|
||||
if not config_file_path.is_file():
|
||||
QErrorMessage(self).showMessage('Video2X configuration file not found, please specify manually.')
|
||||
return
|
||||
|
||||
# read configuration dict from config file
|
||||
self.config = self.read_config(config_file_path)
|
||||
|
||||
# load FFmpeg settings
|
||||
self.ffmpeg_settings = self.config['ffmpeg']
|
||||
self.ffmpeg_settings['ffmpeg_path'] = str(pathlib.Path(os.path.expandvars(self.ffmpeg_settings['ffmpeg_path'])).absolute())
|
||||
|
||||
# set cache directory path
|
||||
if self.config['video2x']['video2x_cache_directory'] is None:
|
||||
self.config['video2x']['video2x_cache_directory'] = str((pathlib.Path(tempfile.gettempdir()) / 'video2x').absolute())
|
||||
self.cache_line_edit.setText(self.config['video2x']['video2x_cache_directory'])
|
||||
|
||||
# load preserve frames settings
|
||||
self.preserve_frames_check_box.setChecked(self.config['video2x']['preserve_frames'])
|
||||
self.start_button.setEnabled(True)
|
||||
|
||||
# waifu2x-caffe
|
||||
settings = self.config['waifu2x_caffe']
|
||||
self.waifu2x_caffe_scale_width_spin_box.setValue(settings['scale_width'])
|
||||
self.waifu2x_caffe_scale_height_spin_box.setValue(settings['scale_height'])
|
||||
self.waifu2x_caffe_path_line_edit.setText(str(pathlib.Path(os.path.expandvars(settings['path'])).absolute()))
|
||||
self.waifu2x_caffe_mode_combo_box.setCurrentText(settings['mode'])
|
||||
self.waifu2x_caffe_noise_level_spin_box.setValue(settings['noise_level'])
|
||||
self.waifu2x_caffe_process_combo_box.setCurrentText(settings['process'])
|
||||
self.waifu2x_caffe_crop_size_spin_box.setValue(settings['crop_size'])
|
||||
self.waifu2x_caffe_output_quality_spin_box.setValue(settings['output_quality'])
|
||||
self.waifu2x_caffe_output_depth_spin_box.setValue(settings['output_depth'])
|
||||
self.waifu2x_caffe_batch_size_spin_box.setValue(settings['batch_size'])
|
||||
self.waifu2x_caffe_gpu_spin_box.setValue(settings['gpu'])
|
||||
self.waifu2x_caffe_tta_check_box.setChecked(bool(settings['tta']))
|
||||
|
||||
# waifu2x-converter-cpp
|
||||
settings = self.config['waifu2x_converter_cpp']
|
||||
self.waifu2x_converter_cpp_path_line_edit.setText(str(pathlib.Path(os.path.expandvars(settings['path'])).absolute()))
|
||||
self.waifu2x_converter_cpp_png_compression_spin_box.setValue(settings['png-compression'])
|
||||
self.waifu2x_converter_cpp_image_quality_spin_box.setValue(settings['image-quality'])
|
||||
self.waifu2x_converter_cpp_block_size_spin_box.setValue(settings['block-size'])
|
||||
self.waifu2x_converter_cpp_processor_spin_box.setValue(settings['processor'])
|
||||
self.waifu2x_converter_cpp_noise_level_spin_box.setValue(settings['noise-level'])
|
||||
self.waifu2x_converter_cpp_mode_combo_box.setCurrentText(settings['mode'])
|
||||
self.waifu2x_converter_cpp_log_level_spin_box.setValue(settings['log-level'])
|
||||
self.waifu2x_converter_cpp_disable_gpu_check_box.setChecked(settings['disable-gpu'])
|
||||
self.waifu2x_converter_cpp_force_opencl_check_box.setChecked(settings['force-OpenCL'])
|
||||
self.waifu2x_converter_cpp_tta_check_box.setChecked(bool(settings['tta']))
|
||||
|
||||
# waifu2x-ncnn-vulkan
|
||||
settings = self.config['waifu2x_ncnn_vulkan']
|
||||
self.waifu2x_ncnn_vulkan_path_line_edit.setText(str(pathlib.Path(os.path.expandvars(settings['path'])).absolute()))
|
||||
self.waifu2x_ncnn_vulkan_noise_level_spin_box.setValue(settings['n'])
|
||||
self.waifu2x_ncnn_vulkan_tile_size_spin_box.setValue(settings['t'])
|
||||
self.waifu2x_ncnn_vulkan_gpu_id_spin_box.setValue(settings['g'])
|
||||
self.waifu2x_ncnn_vulkan_jobs_line_edit.setText(settings['j'])
|
||||
self.waifu2x_ncnn_vulkan_tta_check_box.setChecked(settings['x'])
|
||||
|
||||
# srmd-ncnn-vulkan
|
||||
settings = self.config['srmd_ncnn_vulkan']
|
||||
self.srmd_ncnn_vulkan_path_line_edit.setText(str(pathlib.Path(os.path.expandvars(settings['path'])).absolute()))
|
||||
self.srmd_ncnn_vulkan_noise_level_spin_box.setValue(settings['n'])
|
||||
self.srmd_ncnn_vulkan_tile_size_spin_box.setValue(settings['t'])
|
||||
self.srmd_ncnn_vulkan_gpu_id_spin_box.setValue(settings['g'])
|
||||
self.srmd_ncnn_vulkan_jobs_line_edit.setText(settings['j'])
|
||||
self.srmd_ncnn_vulkan_tta_check_box.setChecked(settings['x'])
|
||||
|
||||
# anime4k
|
||||
settings = self.config['anime4kcpp']
|
||||
self.anime4kcpp_path_line_edit.setText(str(pathlib.Path(os.path.expandvars(settings['path'])).absolute()))
|
||||
self.anime4kcpp_passes_spin_box.setValue(settings['passes'])
|
||||
self.anime4kcpp_push_color_count_spin_box.setValue(settings['pushColorCount'])
|
||||
self.anime4kcpp_strength_color_spin_box.setValue(settings['strengthColor'])
|
||||
self.anime4kcpp_strength_gradient_spin_box.setValue(settings['strengthGradient'])
|
||||
self.anime4kcpp_threads_spin_box.setValue(settings['threads'])
|
||||
self.anime4kcpp_pre_filters_spin_box.setValue(settings['preFilters'])
|
||||
self.anime4kcpp_post_filters_spin_box.setValue(settings['postFilters'])
|
||||
self.anime4kcpp_platform_id_spin_box.setValue(settings['platformID'])
|
||||
self.anime4kcpp_device_id_spin_box.setValue(settings['deviceID'])
|
||||
self.anime4kcpp_codec_combo_box.setCurrentText(settings['codec'])
|
||||
self.anime4kcpp_fast_mode_check_box.setChecked(settings['fastMode'])
|
||||
self.anime4kcpp_pre_processing_check_box.setChecked(settings['preprocessing'])
|
||||
self.anime4kcpp_post_processing_check_box.setChecked(settings['postprocessing'])
|
||||
self.anime4kcpp_gpu_mode_check_box.setChecked(settings['GPUMode'])
|
||||
|
||||
def resolve_driver_settings(self):
|
||||
|
||||
# waifu2x-caffe
|
||||
self.config['waifu2x_caffe']['scale_width'] = self.waifu2x_caffe_scale_width_spin_box.value()
|
||||
self.config['waifu2x_caffe']['scale_height'] = self.waifu2x_caffe_scale_height_spin_box.value()
|
||||
self.config['waifu2x_caffe']['path'] = os.path.expandvars(self.waifu2x_caffe_path_line_edit.text())
|
||||
self.config['waifu2x_caffe']['mode'] = self.waifu2x_caffe_mode_combo_box.currentText()
|
||||
self.config['waifu2x_caffe']['noise_level'] = self.waifu2x_caffe_noise_level_spin_box.value()
|
||||
self.config['waifu2x_caffe']['process'] = self.waifu2x_caffe_process_combo_box.currentText()
|
||||
self.config['waifu2x_caffe']['model_dir'] = str((pathlib.Path(self.config['waifu2x_caffe']['path']).parent / 'models' / self.waifu2x_caffe_model_combobox.currentText()).absolute())
|
||||
self.config['waifu2x_caffe']['crop_size'] = self.waifu2x_caffe_crop_size_spin_box.value()
|
||||
self.config['waifu2x_caffe']['output_quality'] = self.waifu2x_caffe_output_depth_spin_box.value()
|
||||
self.config['waifu2x_caffe']['output_depth'] = self.waifu2x_caffe_output_depth_spin_box.value()
|
||||
self.config['waifu2x_caffe']['batch_size'] = self.waifu2x_caffe_batch_size_spin_box.value()
|
||||
self.config['waifu2x_caffe']['gpu'] = self.waifu2x_caffe_gpu_spin_box.value()
|
||||
self.config['waifu2x_caffe']['tta'] = int(self.waifu2x_caffe_tta_check_box.isChecked())
|
||||
|
||||
# waifu2x-converter-cpp
|
||||
self.config['waifu2x_converter_cpp']['path'] = os.path.expandvars(self.waifu2x_converter_cpp_path_line_edit.text())
|
||||
self.config['waifu2x_converter_cpp']['png-compression'] = self.waifu2x_converter_cpp_png_compression_spin_box.value()
|
||||
self.config['waifu2x_converter_cpp']['image-quality'] = self.waifu2x_converter_cpp_image_quality_spin_box.value()
|
||||
self.config['waifu2x_converter_cpp']['block-size'] = self.waifu2x_converter_cpp_block_size_spin_box.value()
|
||||
self.config['waifu2x_converter_cpp']['processor'] = self.waifu2x_converter_cpp_processor_spin_box.value()
|
||||
self.config['waifu2x_converter_cpp']['model-dir'] = str((pathlib.Path(self.config['waifu2x_converter_cpp']['path']).parent / self.waifu2x_converter_cpp_model_combo_box.currentText()).absolute())
|
||||
self.config['waifu2x_converter_cpp']['noise-level'] = self.waifu2x_converter_cpp_noise_level_spin_box.value()
|
||||
self.config['waifu2x_converter_cpp']['mode'] = self.waifu2x_converter_cpp_mode_combo_box.currentText()
|
||||
self.config['waifu2x_converter_cpp']['log-level'] = self.waifu2x_converter_cpp_log_level_spin_box.value()
|
||||
self.config['waifu2x_converter_cpp']['disable-gpu'] = bool(self.waifu2x_converter_cpp_disable_gpu_check_box.isChecked())
|
||||
self.config['waifu2x_converter_cpp']['force-OpenCL'] = bool(self.waifu2x_converter_cpp_force_opencl_check_box.isChecked())
|
||||
self.config['waifu2x_converter_cpp']['tta'] = int(self.waifu2x_converter_cpp_tta_check_box.isChecked())
|
||||
|
||||
# waifu2x-ncnn-vulkan
|
||||
self.config['waifu2x_ncnn_vulkan']['path'] = os.path.expandvars(self.waifu2x_ncnn_vulkan_path_line_edit.text())
|
||||
self.config['waifu2x_ncnn_vulkan']['n'] = self.waifu2x_ncnn_vulkan_noise_level_spin_box.value()
|
||||
self.config['waifu2x_ncnn_vulkan']['t'] = self.waifu2x_ncnn_vulkan_tile_size_spin_box.value()
|
||||
self.config['waifu2x_ncnn_vulkan']['m'] = str((pathlib.Path(self.config['waifu2x_ncnn_vulkan']['path']).parent / self.waifu2x_ncnn_vulkan_model_combo_box.currentText()).absolute())
|
||||
self.config['waifu2x_ncnn_vulkan']['g'] = self.waifu2x_ncnn_vulkan_gpu_id_spin_box.value()
|
||||
self.config['waifu2x_ncnn_vulkan']['j'] = self.waifu2x_ncnn_vulkan_jobs_line_edit.text()
|
||||
self.config['waifu2x_ncnn_vulkan']['x'] = self.waifu2x_ncnn_vulkan_tta_check_box.isChecked()
|
||||
|
||||
# srmd-ncnn-vulkan
|
||||
self.config['srmd_ncnn_vulkan']['path'] = os.path.expandvars(self.srmd_ncnn_vulkan_path_line_edit.text())
|
||||
self.config['srmd_ncnn_vulkan']['n'] = self.srmd_ncnn_vulkan_noise_level_spin_box.value()
|
||||
self.config['srmd_ncnn_vulkan']['t'] = self.srmd_ncnn_vulkan_tile_size_spin_box.value()
|
||||
self.config['srmd_ncnn_vulkan']['m'] = str((pathlib.Path(self.config['srmd_ncnn_vulkan']['path']).parent / self.srmd_ncnn_vulkan_model_combo_box.currentText()).absolute())
|
||||
self.config['srmd_ncnn_vulkan']['g'] = self.srmd_ncnn_vulkan_gpu_id_spin_box.value()
|
||||
self.config['srmd_ncnn_vulkan']['j'] = self.srmd_ncnn_vulkan_jobs_line_edit.text()
|
||||
self.config['srmd_ncnn_vulkan']['x'] = self.srmd_ncnn_vulkan_tta_check_box.isChecked()
|
||||
|
||||
# anime4k
|
||||
self.config['anime4kcpp']['path'] = os.path.expandvars(self.anime4kcpp_path_line_edit.text())
|
||||
self.config['anime4kcpp']['passes'] = self.anime4kcpp_passes_spin_box.value()
|
||||
self.config['anime4kcpp']['pushColorCount'] = self.anime4kcpp_push_color_count_spin_box.value()
|
||||
self.config['anime4kcpp']['strengthColor'] = self.anime4kcpp_strength_color_spin_box.value()
|
||||
self.config['anime4kcpp']['strengthGradient'] = self.anime4kcpp_strength_gradient_spin_box.value()
|
||||
self.config['anime4kcpp']['threads'] = self.anime4kcpp_threads_spin_box.value()
|
||||
self.config['anime4kcpp']['preFilters'] = self.anime4kcpp_pre_filters_spin_box.value()
|
||||
self.config['anime4kcpp']['postFilters'] = self.anime4kcpp_post_filters_spin_box.value()
|
||||
self.config['anime4kcpp']['platformID'] = self.anime4kcpp_platform_id_spin_box.value()
|
||||
self.config['anime4kcpp']['deviceID'] = self.anime4kcpp_device_id_spin_box.value()
|
||||
self.config['anime4kcpp']['codec'] = self.anime4kcpp_codec_combo_box.currentText()
|
||||
self.config['anime4kcpp']['fastMode'] = bool(self.anime4kcpp_fast_mode_check_box.isChecked())
|
||||
self.config['anime4kcpp']['preprocessing'] = bool(self.anime4kcpp_pre_processing_check_box.isChecked())
|
||||
self.config['anime4kcpp']['postprocessing'] = bool(self.anime4kcpp_post_processing_check_box.isChecked())
|
||||
self.config['anime4kcpp']['GPUMode'] = bool(self.anime4kcpp_gpu_mode_check_box.isChecked())
|
||||
|
||||
def update_gui_for_driver(self):
|
||||
current_driver = AVAILABLE_DRIVERS[self.driver_combo_box.currentText()]
|
||||
|
||||
# update scale ratio constraints
|
||||
if current_driver in ['waifu2x_caffe', 'waifu2x_converter_cpp', 'anime4kcpp']:
|
||||
self.scale_ratio_double_spin_box.setMinimum(0.0)
|
||||
self.scale_ratio_double_spin_box.setMaximum(999.0)
|
||||
self.scale_ratio_double_spin_box.setValue(2.0)
|
||||
elif current_driver == 'waifu2x_ncnn_vulkan':
|
||||
self.scale_ratio_double_spin_box.setMinimum(1.0)
|
||||
self.scale_ratio_double_spin_box.setMaximum(2.0)
|
||||
self.scale_ratio_double_spin_box.setValue(2.0)
|
||||
elif current_driver == 'srmd_ncnn_vulkan':
|
||||
self.scale_ratio_double_spin_box.setMinimum(2.0)
|
||||
self.scale_ratio_double_spin_box.setMaximum(4.0)
|
||||
self.scale_ratio_double_spin_box.setValue(2.0)
|
||||
|
||||
# update preferred processes/threads count
|
||||
if current_driver == 'anime4kcpp':
|
||||
self.processes_spin_box.setValue(16)
|
||||
else:
|
||||
self.processes_spin_box.setValue(1)
|
||||
|
||||
def update_input_table(self):
|
||||
# HACK: use insertRow, removeRow and signals
|
||||
del self.input_table_model
|
||||
self.input_table_model = InputTableModel(self.input_table_data)
|
||||
self.input_table_view.setModel(self.input_table_model)
|
||||
|
||||
def input_table_delete_selected(self):
|
||||
items_to_delete = []
|
||||
for index in [i.row() for i in self.input_table_view.selectedIndexes()]:
|
||||
items_to_delete.append(self.input_table_data[index])
|
||||
|
||||
for item in items_to_delete:
|
||||
self.input_table_data.remove(item)
|
||||
self.update_input_table()
|
||||
|
||||
def input_table_clear_all(self):
|
||||
self.input_table_data = []
|
||||
self.update_input_table()
|
||||
|
||||
def input_table_path_exists(self, input_path):
|
||||
for path in self.input_table_data:
|
||||
# not using Path.samefile since file may not exist
|
||||
if str(path.absolute()) == str(input_path.absolute()):
|
||||
return True
|
||||
return False
|
||||
|
||||
def select_file(self, *args, **kwargs) -> pathlib.Path:
|
||||
file_selected = QFileDialog.getOpenFileName(self, *args, **kwargs)
|
||||
if not isinstance(file_selected, tuple) or file_selected[0] == '':
|
||||
return None
|
||||
return pathlib.Path(file_selected[0])
|
||||
|
||||
def select_folder(self, *args, **kwargs) -> pathlib.Path:
|
||||
folder_selected = QFileDialog.getExistingDirectory(self, *args, **kwargs)
|
||||
if folder_selected == '':
|
||||
return None
|
||||
return pathlib.Path(folder_selected)
|
||||
|
||||
def update_output_path(self):
|
||||
# if there is more than one input
|
||||
if len(self.input_table_data) != 1:
|
||||
return
|
||||
|
||||
input_path = self.input_table_data[0]
|
||||
# give up if input path doesn't exist or isn't a file or a directory
|
||||
if not input_path.exists() or not (input_path.is_file() or input_path.is_dir()):
|
||||
return
|
||||
|
||||
if input_path.is_file():
|
||||
output_path = input_path.parent / f'{input_path.stem}_output.mp4'
|
||||
elif input_path.is_dir():
|
||||
output_path = input_path.parent / f'{input_path.stem}_output'
|
||||
|
||||
# try up to 1000 times
|
||||
output_path_id = 0
|
||||
while output_path.exists() and output_path_id <= 1000:
|
||||
if input_path.is_file():
|
||||
output_path = input_path.parent / pathlib.Path(f'{input_path.stem}_output_{output_path_id}.mp4')
|
||||
elif input_path.is_dir():
|
||||
output_path = input_path.parent / pathlib.Path(f'{input_path.stem}_output_{output_path_id}')
|
||||
output_path_id += 1
|
||||
|
||||
if not output_path.exists():
|
||||
self.output_line_edit.setText(str(output_path.absolute()))
|
||||
|
||||
def select_input_file(self):
|
||||
if ((input_file := self.select_file('Select Input File')) is None or
|
||||
self.input_table_path_exists(input_file)):
|
||||
return
|
||||
self.input_table_data.append(input_file)
|
||||
self.update_output_path()
|
||||
self.update_input_table()
|
||||
|
||||
def select_input_folder(self):
|
||||
if ((input_folder := self.select_folder('Select Input Folder')) is None or
|
||||
self.input_table_path_exists(input_folder)):
|
||||
return
|
||||
self.input_table_data.append(input_folder)
|
||||
self.update_output_path()
|
||||
self.update_input_table()
|
||||
|
||||
def select_output_file(self):
|
||||
if (output_file := self.select_file('Select Output File')) is None:
|
||||
return
|
||||
self.output_line_edit.setText(str(output_file.absolute()))
|
||||
|
||||
def select_output_folder(self):
|
||||
if (output_folder := self.select_folder('Select Output Folder')) is None:
|
||||
return
|
||||
self.output_line_edit.setText(str(output_folder.absolute()))
|
||||
|
||||
def select_cache_folder(self):
|
||||
if (cache_folder := self.select_folder('Select Cache Folder')) is None:
|
||||
return
|
||||
self.cache_line_edit.setText(str(cache_folder.absolute()))
|
||||
|
||||
def select_config_file(self):
|
||||
if (config_file := self.select_file('Select Config File', filter='(YAML files (*.yaml))')) is None:
|
||||
return
|
||||
self.config_line_edit.setText(str(config_file.absolute()))
|
||||
self.load_configurations()
|
||||
|
||||
def select_driver_binary_path(self, driver_line_edit):
|
||||
if (driver_binary_path := self.select_file('Select Driver Binary File')) is None:
|
||||
return
|
||||
driver_line_edit.setText(str(driver_binary_path.absolute()))
|
||||
|
||||
def show_about(self, message: str):
|
||||
message_box = QMessageBox(self)
|
||||
message_box.setWindowTitle('About Video2X')
|
||||
message_box.setIconPixmap(QtGui.QPixmap(self.video2x_icon_path).scaled(64, 64))
|
||||
message_box.setTextFormat(Qt.MarkdownText)
|
||||
message_box.setText(LEGAL_INFO)
|
||||
message_box.exec_()
|
||||
|
||||
def show_information(self, message: str):
|
||||
message_box = QMessageBox(self)
|
||||
message_box.setWindowTitle('Information')
|
||||
message_box.setIcon(QMessageBox.Information)
|
||||
message_box.setText(message)
|
||||
message_box.exec_()
|
||||
|
||||
def show_warning(self, message: str):
|
||||
message_box = QMessageBox(self)
|
||||
message_box.setWindowTitle('Warning')
|
||||
message_box.setIcon(QMessageBox.Warning)
|
||||
message_box.setText(message)
|
||||
message_box.exec_()
|
||||
|
||||
def show_error(self, exception: Exception):
|
||||
# QErrorMessage(self).showMessage(message.replace('\n', '<br>'))
|
||||
message_box = QMessageBox(self)
|
||||
message_box.setWindowTitle('Error')
|
||||
message_box.setIcon(QMessageBox.Critical)
|
||||
message_box.setTextFormat(Qt.MarkdownText)
|
||||
|
||||
error_message = '''Upscaler ran into an error:\\
|
||||
**{}**\\
|
||||
Check the console output for details.\\
|
||||
When reporting an error, please include console output.\\
|
||||
You can [submit an issue on GitHub](https://github.com/k4yt3x/video2x/issues/new?assignees=K4YT3X&labels=bug&template=bug-report.md&title={}) to report this error.'''
|
||||
message_box.setText(error_message.format(exception, urllib.parse.quote(str(exception))))
|
||||
message_box.exec_()
|
||||
|
||||
def progress_monitor(self, progress_callback):
|
||||
|
||||
# initialize progress bar values
|
||||
upscale_begin_time = time.time()
|
||||
progress_callback.emit((upscale_begin_time, 0, 0, 0, 0, pathlib.Path(), pathlib.Path()))
|
||||
|
||||
# keep querying upscaling process and feed information to callback signal
|
||||
while self.upscaler.running:
|
||||
|
||||
progress_callback.emit((upscale_begin_time,
|
||||
self.upscaler.total_frames_upscaled,
|
||||
self.upscaler.total_frames,
|
||||
self.upscaler.total_processed,
|
||||
self.upscaler.total_videos,
|
||||
self.upscaler.current_input_video,
|
||||
self.upscaler.last_frame_upscaled))
|
||||
time.sleep(1)
|
||||
|
||||
# upscale process will stop at 99%
|
||||
# so it's set to 100 manually when all is done
|
||||
progress_callback.emit((upscale_begin_time, 0, 0, 0, 0, pathlib.Path(), pathlib.Path()))
|
||||
|
||||
def set_progress(self, progress_information: tuple):
|
||||
upscale_begin_time = progress_information[0]
|
||||
total_frames_upscaled = progress_information[1]
|
||||
total_frames = progress_information[2]
|
||||
total_processed = progress_information[3]
|
||||
total_videos = progress_information[4]
|
||||
current_input_video = progress_information[5]
|
||||
last_frame_upscaled = progress_information[6]
|
||||
|
||||
# calculate fields based on frames and time elapsed
|
||||
time_elapsed = time.time() - upscale_begin_time
|
||||
try:
|
||||
rate = total_frames_upscaled / (time.time() - upscale_begin_time)
|
||||
time_remaining = (total_frames - total_frames_upscaled) / rate
|
||||
except Exception:
|
||||
rate = 0.0
|
||||
time_remaining = 0.0
|
||||
|
||||
# set calculated values in GUI
|
||||
self.current_progress_bar.setMaximum(total_frames)
|
||||
self.current_progress_bar.setValue(total_frames_upscaled)
|
||||
self.frames_label.setText('Frames: {}/{}'.format(total_frames_upscaled, total_frames))
|
||||
self.time_elapsed_label.setText('Time Elapsed: {}'.format(time.strftime("%H:%M:%S", time.gmtime(time_elapsed))))
|
||||
self.time_remaining_label.setText('Time Remaining: {}'.format(time.strftime("%H:%M:%S", time.gmtime(time_remaining))))
|
||||
self.rate_label.setText('Rate (FPS): {}'.format(round(rate, 2)))
|
||||
self.overall_progress_label.setText('Overall Progress: {}/{}'.format(total_processed, total_videos))
|
||||
self.overall_progress_bar.setMaximum(total_videos)
|
||||
self.overall_progress_bar.setValue(total_processed)
|
||||
self.currently_processing_label.setText('Currently Processing: {}'.format(str(current_input_video.name)))
|
||||
|
||||
# if show frame is checked, show preview image
|
||||
if self.frame_preview_show_preview_check_box.isChecked() and last_frame_upscaled.is_file():
|
||||
last_frame_pixmap = QtGui.QPixmap(str(last_frame_upscaled.absolute()))
|
||||
# the -2 here behind geometry subtracts frame size from width and height
|
||||
self.frame_preview_label.setPixmap(last_frame_pixmap.scaled(self.frame_preview_label.width() - 2,
|
||||
self.frame_preview_label.height() - 2,
|
||||
Qt.KeepAspectRatio))
|
||||
|
||||
# if keep aspect ratio is checked, don't stretch image
|
||||
if self.frame_preview_keep_aspect_ratio_check_box.isChecked():
|
||||
self.frame_preview_label.setScaledContents(False)
|
||||
else:
|
||||
self.frame_preview_label.setScaledContents(True)
|
||||
|
||||
# display image in label
|
||||
self.frame_preview_label.show()
|
||||
|
||||
# if show frame is unchecked, clear image
|
||||
elif self.frame_preview_show_preview_check_box.isChecked() is False:
|
||||
self.frame_preview_label.clear()
|
||||
|
||||
def reset_progress_display(self):
|
||||
# reset progress display UI elements
|
||||
self.current_progress_bar.setMaximum(100)
|
||||
self.current_progress_bar.setValue(0)
|
||||
self.frames_label.setText('Frames: {}/{}'.format(0, 0))
|
||||
self.time_elapsed_label.setText('Time Elapsed: {}'.format(time.strftime("%H:%M:%S", time.gmtime(0))))
|
||||
self.time_remaining_label.setText('Time Remaining: {}'.format(time.strftime("%H:%M:%S", time.gmtime(0))))
|
||||
self.rate_label.setText('Rate (FPS): {}'.format(0.0))
|
||||
self.overall_progress_label.setText('Overall Progress: {}/{}'.format(0, 0))
|
||||
self.overall_progress_bar.setMaximum(100)
|
||||
self.overall_progress_bar.setValue(0)
|
||||
self.currently_processing_label.setText('Currently Processing:')
|
||||
|
||||
def start(self):
|
||||
|
||||
# start execution
|
||||
try:
|
||||
# start timer
|
||||
self.begin_time = time.time()
|
||||
|
||||
# resolve input and output directories from GUI
|
||||
if len(self.input_table_data) == 0:
|
||||
self.show_warning('Input path unspecified')
|
||||
return
|
||||
if self.output_line_edit.text().strip() == '':
|
||||
self.show_warning('Output path unspecified')
|
||||
return
|
||||
|
||||
if len(self.input_table_data) == 1:
|
||||
input_directory = self.input_table_data[0]
|
||||
else:
|
||||
input_directory = self.input_table_data
|
||||
|
||||
# resolve output directory
|
||||
output_directory = pathlib.Path(os.path.expandvars(self.output_line_edit.text()))
|
||||
|
||||
# load driver settings from GUI
|
||||
self.resolve_driver_settings()
|
||||
|
||||
# load driver settings for the current driver
|
||||
self.driver_settings = self.config[AVAILABLE_DRIVERS[self.driver_combo_box.currentText()]]
|
||||
|
||||
self.upscaler = Upscaler(input_path=input_directory,
|
||||
output_path=output_directory,
|
||||
driver_settings=self.driver_settings,
|
||||
ffmpeg_settings=self.ffmpeg_settings)
|
||||
|
||||
# set optional options
|
||||
self.upscaler.driver = AVAILABLE_DRIVERS[self.driver_combo_box.currentText()]
|
||||
self.upscaler.scale_ratio = self.scale_ratio_double_spin_box.value()
|
||||
self.upscaler.processes = self.processes_spin_box.value()
|
||||
self.upscaler.video2x_cache_directory = pathlib.Path(os.path.expandvars(self.cache_line_edit.text()))
|
||||
self.upscaler.image_format = self.config['video2x']['image_format'].lower()
|
||||
self.upscaler.preserve_frames = bool(self.preserve_frames_check_box.isChecked())
|
||||
|
||||
# run upscaler
|
||||
worker = UpscalerWorker(self.upscaler.run)
|
||||
worker.signals.error.connect(self.upscale_errored)
|
||||
worker.signals.interrupted.connect(self.upscale_interrupted)
|
||||
worker.signals.finished.connect(self.upscale_successful)
|
||||
self.threadpool.start(worker)
|
||||
|
||||
# start progress monitoring
|
||||
progress_bar_worker = ProgressMonitorWorkder(self.progress_monitor)
|
||||
progress_bar_worker.signals.progress.connect(self.set_progress)
|
||||
self.threadpool.start(progress_bar_worker)
|
||||
|
||||
self.start_button.setEnabled(False)
|
||||
self.stop_button.setEnabled(True)
|
||||
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
self.upscale_errored(e)
|
||||
|
||||
def upscale_errored(self, exception: Exception):
|
||||
self.show_error(exception)
|
||||
self.threadpool.waitForDone(5)
|
||||
self.start_button.setEnabled(True)
|
||||
self.stop_button.setEnabled(False)
|
||||
self.reset_progress_display()
|
||||
|
||||
def upscale_interrupted(self):
|
||||
self.show_information('Upscale has been interrupted')
|
||||
self.threadpool.waitForDone(5)
|
||||
self.start_button.setEnabled(True)
|
||||
self.stop_button.setEnabled(False)
|
||||
self.reset_progress_display()
|
||||
|
||||
def upscale_successful(self):
|
||||
# if all threads have finished
|
||||
self.threadpool.waitForDone(5)
|
||||
self.show_information('Upscale finished successfully, taking {} seconds'.format(round((time.time() - self.begin_time), 5)))
|
||||
self.start_button.setEnabled(True)
|
||||
self.stop_button.setEnabled(False)
|
||||
self.reset_progress_display()
|
||||
|
||||
def stop(self):
|
||||
with contextlib.suppress(AttributeError):
|
||||
self.upscaler.running = False
|
||||
|
||||
def closeEvent(self, event):
|
||||
# try cleaning up temp directories
|
||||
self.stop()
|
||||
event.accept()
|
||||
|
||||
|
||||
# this file shouldn't be imported
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
app = QApplication(sys.argv)
|
||||
window = Video2XMainWindow()
|
||||
window.show()
|
||||
app.exec_()
|
||||
|
||||
# on GUI exception, print error message in console
|
||||
# and hold window open using input()
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
input('Press enter to close')
|
||||
3
src/video2x_gui.pyproject
Normal file
3
src/video2x_gui.pyproject
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"files": ["video2x_gui.ui","video2x_gui.py"]
|
||||
}
|
||||
190
src/video2x_gui.pyproject.user
Normal file
190
src/video2x_gui.pyproject.user
Normal file
@@ -0,0 +1,190 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE QtCreatorProject>
|
||||
<!-- Written by QtCreator 4.12.0, 2020-05-11T04:13:22. -->
|
||||
<qtcreator>
|
||||
<data>
|
||||
<variable>EnvironmentId</variable>
|
||||
<value type="QByteArray">{25c1e4a4-6b4a-4828-883b-6f32c3f7eba0}</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.ActiveTarget</variable>
|
||||
<value type="int">0</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.EditorSettings</variable>
|
||||
<valuemap type="QVariantMap">
|
||||
<value type="bool" key="EditorConfiguration.AutoIndent">true</value>
|
||||
<value type="bool" key="EditorConfiguration.AutoSpacesForTabs">false</value>
|
||||
<value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value>
|
||||
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
|
||||
<value type="QString" key="language">Cpp</value>
|
||||
<valuemap type="QVariantMap" key="value">
|
||||
<value type="QByteArray" key="CurrentPreferences">CppGlobal</value>
|
||||
</valuemap>
|
||||
</valuemap>
|
||||
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.1">
|
||||
<value type="QString" key="language">QmlJS</value>
|
||||
<valuemap type="QVariantMap" key="value">
|
||||
<value type="QByteArray" key="CurrentPreferences">QmlJSGlobal</value>
|
||||
</valuemap>
|
||||
</valuemap>
|
||||
<value type="int" key="EditorConfiguration.CodeStyle.Count">2</value>
|
||||
<value type="QByteArray" key="EditorConfiguration.Codec">UTF-8</value>
|
||||
<value type="bool" key="EditorConfiguration.ConstrainTooltips">false</value>
|
||||
<value type="int" key="EditorConfiguration.IndentSize">4</value>
|
||||
<value type="bool" key="EditorConfiguration.KeyboardTooltips">false</value>
|
||||
<value type="int" key="EditorConfiguration.MarginColumn">80</value>
|
||||
<value type="bool" key="EditorConfiguration.MouseHiding">true</value>
|
||||
<value type="bool" key="EditorConfiguration.MouseNavigation">true</value>
|
||||
<value type="int" key="EditorConfiguration.PaddingMode">1</value>
|
||||
<value type="bool" key="EditorConfiguration.ScrollWheelZooming">true</value>
|
||||
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
|
||||
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</value>
|
||||
<value type="bool" key="EditorConfiguration.SmartSelectionChanging">true</value>
|
||||
<value type="bool" key="EditorConfiguration.SpacesForTabs">true</value>
|
||||
<value type="int" key="EditorConfiguration.TabKeyBehavior">0</value>
|
||||
<value type="int" key="EditorConfiguration.TabSize">8</value>
|
||||
<value type="bool" key="EditorConfiguration.UseGlobal">true</value>
|
||||
<value type="int" key="EditorConfiguration.Utf8BomBehavior">1</value>
|
||||
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanIndentation">true</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
|
||||
<value type="bool" key="EditorConfiguration.inEntireDocument">false</value>
|
||||
</valuemap>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.PluginSettings</variable>
|
||||
<valuemap type="QVariantMap">
|
||||
<valuelist type="QVariantList" key="ClangCodeModel.CustomCommandLineKey">
|
||||
<value type="QString">-fno-delayed-template-parsing</value>
|
||||
</valuelist>
|
||||
<value type="bool" key="ClangCodeModel.UseGlobalConfig">true</value>
|
||||
<value type="QString" key="ClangCodeModel.WarningConfigId">Builtin.Questionable</value>
|
||||
<valuemap type="QVariantMap" key="ClangTools">
|
||||
<value type="bool" key="ClangTools.BuildBeforeAnalysis">true</value>
|
||||
<value type="QString" key="ClangTools.DiagnosticConfig">Builtin.DefaultTidyAndClazy</value>
|
||||
<value type="int" key="ClangTools.ParallelJobs">8</value>
|
||||
<valuelist type="QVariantList" key="ClangTools.SelectedDirs"/>
|
||||
<valuelist type="QVariantList" key="ClangTools.SelectedFiles"/>
|
||||
<valuelist type="QVariantList" key="ClangTools.SuppressedDiagnostics"/>
|
||||
<value type="bool" key="ClangTools.UseGlobalSettings">true</value>
|
||||
</valuemap>
|
||||
</valuemap>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.Target.0</variable>
|
||||
<valuemap type="QVariantMap">
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop (x86-windows-msvc2019-pe-64bit)</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop (x86-windows-msvc2019-pe-64bit)</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{5450e32e-f498-4c15-a0a5-7456f3375388}</value>
|
||||
<value type="int" key="ProjectExplorer.Target.ActiveBuildConfiguration">-1</value>
|
||||
<value type="int" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
|
||||
<value type="int" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
|
||||
<value type="int" key="ProjectExplorer.Target.BuildConfigurationCount">0</value>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
|
||||
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">0</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deploy</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Deploy</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.DeployConfiguration.CustomData"/>
|
||||
<value type="bool" key="ProjectExplorer.DeployConfiguration.CustomDataEnabled">false</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.DefaultDeployConfiguration</value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.Target.DeployConfigurationCount">1</value>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.Target.PluginSettings"/>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
|
||||
<value type="QString" key="Analyzer.Perf.CallgraphMode">dwarf</value>
|
||||
<valuelist type="QVariantList" key="Analyzer.Perf.Events">
|
||||
<value type="QString">cpu-cycles</value>
|
||||
</valuelist>
|
||||
<valuelist type="QVariantList" key="Analyzer.Perf.ExtraArguments"/>
|
||||
<value type="int" key="Analyzer.Perf.Frequency">250</value>
|
||||
<valuelist type="QVariantList" key="Analyzer.Perf.RecordArguments">
|
||||
<value type="QString">-e</value>
|
||||
<value type="QString">cpu-cycles</value>
|
||||
<value type="QString">--call-graph</value>
|
||||
<value type="QString">dwarf,4096</value>
|
||||
<value type="QString">-F</value>
|
||||
<value type="QString">250</value>
|
||||
</valuelist>
|
||||
<value type="QString" key="Analyzer.Perf.SampleMode">-F</value>
|
||||
<value type="bool" key="Analyzer.Perf.Settings.UseGlobalSettings">true</value>
|
||||
<value type="int" key="Analyzer.Perf.StackSize">4096</value>
|
||||
<value type="bool" key="Analyzer.QmlProfiler.AggregateTraces">false</value>
|
||||
<value type="bool" key="Analyzer.QmlProfiler.FlushEnabled">false</value>
|
||||
<value type="uint" key="Analyzer.QmlProfiler.FlushInterval">1000</value>
|
||||
<value type="QString" key="Analyzer.QmlProfiler.LastTraceFile"></value>
|
||||
<value type="bool" key="Analyzer.QmlProfiler.Settings.UseGlobalSettings">true</value>
|
||||
<valuelist type="QVariantList" key="Analyzer.Valgrind.AddedSuppressionFiles"/>
|
||||
<value type="bool" key="Analyzer.Valgrind.Callgrind.CollectBusEvents">false</value>
|
||||
<value type="bool" key="Analyzer.Valgrind.Callgrind.CollectSystime">false</value>
|
||||
<value type="bool" key="Analyzer.Valgrind.Callgrind.EnableBranchSim">false</value>
|
||||
<value type="bool" key="Analyzer.Valgrind.Callgrind.EnableCacheSim">false</value>
|
||||
<value type="bool" key="Analyzer.Valgrind.Callgrind.EnableEventToolTips">true</value>
|
||||
<value type="double" key="Analyzer.Valgrind.Callgrind.MinimumCostRatio">0.01</value>
|
||||
<value type="double" key="Analyzer.Valgrind.Callgrind.VisualisationMinimumCostRatio">10</value>
|
||||
<value type="bool" key="Analyzer.Valgrind.FilterExternalIssues">true</value>
|
||||
<value type="QString" key="Analyzer.Valgrind.KCachegrindExecutable">kcachegrind</value>
|
||||
<value type="int" key="Analyzer.Valgrind.LeakCheckOnFinish">1</value>
|
||||
<value type="int" key="Analyzer.Valgrind.NumCallers">25</value>
|
||||
<valuelist type="QVariantList" key="Analyzer.Valgrind.RemovedSuppressionFiles"/>
|
||||
<value type="int" key="Analyzer.Valgrind.SelfModifyingCodeDetection">1</value>
|
||||
<value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value>
|
||||
<value type="bool" key="Analyzer.Valgrind.ShowReachable">false</value>
|
||||
<value type="bool" key="Analyzer.Valgrind.TrackOrigins">true</value>
|
||||
<value type="QString" key="Analyzer.Valgrind.ValgrindExecutable">valgrind</value>
|
||||
<valuelist type="QVariantList" key="Analyzer.Valgrind.VisibleErrorKinds">
|
||||
<value type="int">0</value>
|
||||
<value type="int">1</value>
|
||||
<value type="int">2</value>
|
||||
<value type="int">3</value>
|
||||
<value type="int">4</value>
|
||||
<value type="int">5</value>
|
||||
<value type="int">6</value>
|
||||
<value type="int">7</value>
|
||||
<value type="int">8</value>
|
||||
<value type="int">9</value>
|
||||
<value type="int">10</value>
|
||||
<value type="int">11</value>
|
||||
<value type="int">12</value>
|
||||
<value type="int">13</value>
|
||||
<value type="int">14</value>
|
||||
</valuelist>
|
||||
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
|
||||
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">video2x_gui</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">PythonEditor.RunConfiguration.C:/Users/k4yt3x/Documents/Projects/video2x/src/video2x_gui.py</value>
|
||||
<value type="QString" key="ProjectExplorer.RunConfiguration.BuildKey">C:/Users/k4yt3x/Documents/Projects/video2x/src/video2x_gui.py</value>
|
||||
<value type="bool" key="PythonEditor.RunConfiguation.Buffered">false</value>
|
||||
<value type="QString" key="PythonEditor.RunConfiguation.Interpreter">{ffc39ed5-fbe0-4af8-8b16-9a60c393bdb8}</value>
|
||||
<value type="QString" key="PythonEditor.RunConfiguation.Script">C:\Users\k4yt3x\Documents\Projects\video2x\src\video2x_gui.py</value>
|
||||
<value type="QString" key="RunConfiguration.Arguments"></value>
|
||||
<value type="bool" key="RunConfiguration.Arguments.multi">false</value>
|
||||
<value type="QString" key="RunConfiguration.OverrideDebuggerStartup"></value>
|
||||
<value type="bool" key="RunConfiguration.UseCppDebugger">false</value>
|
||||
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
|
||||
<value type="bool" key="RunConfiguration.UseMultiProcess">false</value>
|
||||
<value type="bool" key="RunConfiguration.UseQmlDebugger">false</value>
|
||||
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
|
||||
<value type="QString" key="RunConfiguration.WorkingDirectory"></value>
|
||||
<value type="QString" key="RunConfiguration.WorkingDirectory.default"></value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
|
||||
</valuemap>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.TargetCount</variable>
|
||||
<value type="int">1</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.Updater.FileVersion</variable>
|
||||
<value type="int">22</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>Version</variable>
|
||||
<value type="int">22</value>
|
||||
</data>
|
||||
</qtcreator>
|
||||
1744
src/video2x_gui.ui
Normal file
1744
src/video2x_gui.ui
Normal file
File diff suppressed because it is too large
Load Diff
412
src/video2x_setup.py
Executable file
412
src/video2x_setup.py
Executable file
@@ -0,0 +1,412 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Video2X Setup Script
|
||||
Creator: K4YT3X
|
||||
Date Created: November 28, 2018
|
||||
Last Modified: May 8, 2020
|
||||
|
||||
Editor: BrianPetkovsek
|
||||
Editor: SAT3LL
|
||||
|
||||
Description: This script helps installing all dependencies of video2x
|
||||
and generates a configuration for it.
|
||||
|
||||
Installation Details:
|
||||
- ffmpeg: %LOCALAPPDATA%\\video2x\\ffmpeg
|
||||
- waifu2x-caffe: %LOCALAPPDATA%\\video2x\\waifu2x-caffe
|
||||
- waifu2x-cpp-converter: %LOCALAPPDATA%\\video2x\\waifu2x-converter-cpp
|
||||
- waifu2x_ncnn_vulkan: %LOCALAPPDATA%\\video2x\\waifu2x-ncnn-vulkan
|
||||
- anime4kcpp: %LOCALAPPDATA%\\video2x\\anime4kcpp
|
||||
- srmd_ncnn_vulkan: %LOCALAPPDATA%\\video2x\\srmd-ncnn-vulkan
|
||||
"""
|
||||
|
||||
# built-in imports
|
||||
from datetime import timedelta
|
||||
import argparse
|
||||
import contextlib
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
import urllib
|
||||
import zipfile
|
||||
|
||||
# Requests doesn't come with windows, therefore
|
||||
# it will be installed as a dependency and imported
|
||||
# later in the script.
|
||||
# import requests
|
||||
|
||||
VERSION = '1.8.0'
|
||||
|
||||
# global static variables
|
||||
LOCALAPPDATA = pathlib.Path(os.getenv('localappdata'))
|
||||
VIDEO2X_CONFIG = pathlib.Path(__file__).parent.absolute() / 'video2x.yaml'
|
||||
DRIVER_OPTIONS = ['all', 'ffmpeg', 'waifu2x_caffe', 'waifu2x_converter_cpp', 'waifu2x_ncnn_vulkan', 'anime4kcpp', 'srmd_ncnn_vulkan']
|
||||
|
||||
|
||||
def parse_arguments():
|
||||
"""Processes CLI arguments
|
||||
"""
|
||||
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
|
||||
# video options
|
||||
general_options = parser.add_argument_group('General Options')
|
||||
general_options.add_argument('-d', '--driver', help='driver to download and configure', action='store', choices=DRIVER_OPTIONS, default='all')
|
||||
|
||||
# parse arguments
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
class Video2xSetup:
|
||||
""" 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.
|
||||
"""
|
||||
|
||||
def __init__(self, driver, download_python_modules):
|
||||
self.driver = driver
|
||||
self.download_python_modules = download_python_modules
|
||||
self.trash = []
|
||||
|
||||
def run(self):
|
||||
if self.download_python_modules:
|
||||
print('\nInstalling Python libraries')
|
||||
self._install_python_requirements()
|
||||
|
||||
if self.driver == 'all':
|
||||
self._install_ffmpeg()
|
||||
self._install_waifu2x_caffe()
|
||||
self._install_waifu2x_converter_cpp()
|
||||
self._install_waifu2x_ncnn_vulkan()
|
||||
self._install_anime4kcpp()
|
||||
self._install_srmd_ncnn_vulkan()
|
||||
elif self.driver == 'ffmpeg':
|
||||
self._install_ffmpeg()
|
||||
elif self.driver == 'waifu2x_caffe':
|
||||
self._install_waifu2x_caffe()
|
||||
elif self.driver == 'waifu2x_converter_cpp':
|
||||
self._install_waifu2x_converter_cpp()
|
||||
elif self.driver == 'waifu2x_ncnn_vulkan':
|
||||
self._install_waifu2x_ncnn_vulkan()
|
||||
elif self.driver == 'anime4kcpp':
|
||||
self._install_anime4kcpp()
|
||||
elif self.driver == 'srmd_ncnn_vulkan':
|
||||
self._install_srmd_ncnn_vulkan()
|
||||
|
||||
print('\nGenerating Video2X configuration file')
|
||||
self._generate_config()
|
||||
|
||||
print('\nCleaning up temporary files')
|
||||
self._cleanup()
|
||||
|
||||
def _install_python_requirements(self):
|
||||
""" Read requirements.txt and return its content
|
||||
"""
|
||||
pip_install('requirements.txt')
|
||||
|
||||
def _cleanup(self):
|
||||
""" Cleanup all the temp files downloaded
|
||||
"""
|
||||
for file in self.trash:
|
||||
try:
|
||||
if file.is_dir():
|
||||
print(f'Deleting directory: {file}')
|
||||
shutil.rmtree(file)
|
||||
else:
|
||||
print(f'Deleting file: {file}')
|
||||
file.unlink()
|
||||
except Exception:
|
||||
print(f'Error deleting: {file}')
|
||||
traceback.print_exc()
|
||||
|
||||
def _install_ffmpeg(self):
|
||||
""" Install FFMPEG
|
||||
"""
|
||||
print('\nInstalling FFmpeg')
|
||||
|
||||
latest_release = 'https://ffmpeg.zeranoe.com/builds/win64/static/ffmpeg-latest-win64-static.zip'
|
||||
|
||||
ffmpeg_zip = download(latest_release, tempfile.gettempdir())
|
||||
self.trash.append(ffmpeg_zip)
|
||||
|
||||
with zipfile.ZipFile(ffmpeg_zip) as zipf:
|
||||
zipf.extractall(LOCALAPPDATA / 'video2x')
|
||||
|
||||
def _install_waifu2x_caffe(self):
|
||||
""" 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()
|
||||
|
||||
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')
|
||||
|
||||
def _install_waifu2x_converter_cpp(self):
|
||||
""" 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()
|
||||
|
||||
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')
|
||||
|
||||
def _install_waifu2x_ncnn_vulkan(self):
|
||||
""" 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()
|
||||
|
||||
for a in latest_release['assets']:
|
||||
if re.search(r'waifu2x-ncnn-vulkan-\d*\.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'
|
||||
with zipfile.ZipFile(waifu2x_ncnn_vulkan_zip) as zipf:
|
||||
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)
|
||||
|
||||
def _install_anime4kcpp(self):
|
||||
""" Install Anime4KCPP
|
||||
"""
|
||||
print('\nInstalling Anime4KCPP')
|
||||
|
||||
import pyunpack
|
||||
import requests
|
||||
|
||||
# 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()
|
||||
|
||||
for a in latest_release['assets']:
|
||||
if re.search(r'Anime4KCPP_CLI-.*-Win64-msvc\.7z', a['browser_download_url']):
|
||||
anime4kcpp_zip = download(a['browser_download_url'], tempfile.gettempdir())
|
||||
self.trash.append(anime4kcpp_zip)
|
||||
|
||||
# extract and rename
|
||||
# with py7zr.SevenZipFile(anime4kcpp_zip, mode='r') as archive:
|
||||
(LOCALAPPDATA / 'video2x' / 'anime4kcpp').mkdir(parents=True, exist_ok=True)
|
||||
pyunpack.Archive(anime4kcpp_zip).extractall(LOCALAPPDATA / 'video2x' / 'anime4kcpp')
|
||||
|
||||
def _install_srmd_ncnn_vulkan(self):
|
||||
""" 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()
|
||||
|
||||
for a in latest_release['assets']:
|
||||
if re.search(r'srmd-ncnn-vulkan-\d*\.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'
|
||||
with zipfile.ZipFile(srmd_ncnn_vulkan_zip) as zipf:
|
||||
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)
|
||||
|
||||
def _generate_config(self):
|
||||
""" Generate video2x config
|
||||
"""
|
||||
import yaml
|
||||
|
||||
# open current video2x configuration file as template
|
||||
with open(VIDEO2X_CONFIG, 'r') as template:
|
||||
template_dict = yaml.load(template, Loader=yaml.FullLoader)
|
||||
template.close()
|
||||
|
||||
# configure only the specified drivers
|
||||
if self.driver == 'all':
|
||||
template_dict['waifu2x_caffe']['path'] = str(LOCALAPPDATA / 'video2x' / 'waifu2x-caffe' / 'waifu2x-caffe-cui')
|
||||
template_dict['waifu2x_converter_cpp']['path'] = str(LOCALAPPDATA / 'video2x' / 'waifu2x-converter-cpp' / 'waifu2x-converter-cpp')
|
||||
template_dict['waifu2x_ncnn_vulkan']['path'] = str(LOCALAPPDATA / 'video2x' / 'waifu2x-ncnn-vulkan' / 'waifu2x-ncnn-vulkan')
|
||||
template_dict['srmd_ncnn_vulkan']['path'] = str(LOCALAPPDATA / 'video2x' / 'srmd-ncnn-vulkan' / 'srmd-ncnn-vulkan')
|
||||
template_dict['anime4kcpp']['path'] = str(LOCALAPPDATA / 'video2x' / 'anime4kcpp' / 'CLI' / 'Anime4KCPP_CLI' / 'Anime4KCPP_CLI')
|
||||
elif self.driver == 'waifu2x_caffe':
|
||||
template_dict['waifu2x_caffe']['path'] = str(LOCALAPPDATA / 'video2x' / 'waifu2x-caffe' / 'waifu2x-caffe-cui')
|
||||
elif self.driver == 'waifu2x_converter_cpp':
|
||||
template_dict['waifu2x_converter_cpp']['path'] = str(LOCALAPPDATA / 'video2x' / 'waifu2x-converter-cpp' / 'waifu2x-converter-cpp')
|
||||
elif self.driver == 'waifu2x_ncnn_vulkan':
|
||||
template_dict['waifu2x_ncnn_vulkan']['path'] = str(LOCALAPPDATA / 'video2x' / 'waifu2x-ncnn-vulkan' / 'waifu2x-ncnn-vulkan')
|
||||
elif self.driver == 'srmd_ncnn_vulkan':
|
||||
template_dict['srmd_ncnn_vulkan']['path'] = str(LOCALAPPDATA / 'video2x' / 'srmd-ncnn-vulkan' / 'srmd-ncnn-vulkan')
|
||||
elif self.driver == 'anime4kcpp':
|
||||
template_dict['anime4kcpp']['path'] = str(LOCALAPPDATA / 'video2x' / 'anime4kcpp' / 'CLI' / 'Anime4KCPP_CLI' / 'Anime4KCPP_CLI')
|
||||
|
||||
template_dict['ffmpeg']['ffmpeg_path'] = str(LOCALAPPDATA / 'video2x' / 'ffmpeg-latest-win64-static' / 'bin')
|
||||
template_dict['video2x']['video2x_cache_directory'] = None
|
||||
template_dict['video2x']['preserve_frames'] = False
|
||||
|
||||
# write configuration into file
|
||||
with open(VIDEO2X_CONFIG, 'w') as config:
|
||||
yaml.dump(template_dict, config)
|
||||
|
||||
|
||||
def download(url, save_path, chunk_size=4096):
|
||||
""" Download file to local with requests library
|
||||
"""
|
||||
from tqdm import tqdm
|
||||
import requests
|
||||
|
||||
save_path = pathlib.Path(save_path)
|
||||
|
||||
# create target folder if it doesn't exist
|
||||
save_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# create requests stream for steaming file
|
||||
stream = requests.get(url, stream=True, allow_redirects=True)
|
||||
|
||||
# get file name
|
||||
file_name = None
|
||||
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]
|
||||
else:
|
||||
output_file = save_path / file_name
|
||||
|
||||
# decode url encoding
|
||||
output_file = pathlib.Path(urllib.parse.unquote(str(output_file)))
|
||||
|
||||
# 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'])
|
||||
|
||||
# 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}')
|
||||
|
||||
# Write content into file
|
||||
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:
|
||||
output.write(chunk)
|
||||
progress_bar.update(len(chunk))
|
||||
|
||||
# return the full path of saved file
|
||||
return output_file
|
||||
|
||||
|
||||
def pip_install(file):
|
||||
""" 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
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
# set default exit code
|
||||
EXIT_CODE = 0
|
||||
|
||||
# get start time
|
||||
start_time = time.time()
|
||||
|
||||
# check platform
|
||||
if sys.platform != 'win32':
|
||||
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: {VERSION}')
|
||||
|
||||
# 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')
|
||||
download_python_modules = False
|
||||
|
||||
setup = Video2xSetup(args.driver, download_python_modules)
|
||||
setup.run()
|
||||
print('\nScript finished successfully')
|
||||
|
||||
except SystemExit:
|
||||
pass
|
||||
|
||||
# if PermissionError is raised
|
||||
# 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')
|
||||
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')
|
||||
|
||||
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))}')
|
||||
input('Press [ENTER] to exit script')
|
||||
sys.exit(EXIT_CODE)
|
||||
116
src/wrappers/anime4kcpp.py
Normal file
116
src/wrappers/anime4kcpp.py
Normal file
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Waifu2x Caffe Driver
|
||||
Author: K4YT3X
|
||||
Date Created: May 3, 2020
|
||||
Last Modified: May 11, 2020
|
||||
|
||||
Description: This class is a high-level wrapper
|
||||
for waifu2x-caffe.
|
||||
"""
|
||||
|
||||
# built-in imports
|
||||
import argparse
|
||||
import os
|
||||
import pathlib
|
||||
import platform
|
||||
import shlex
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
# third-party imports
|
||||
from avalon_framework import Avalon
|
||||
|
||||
|
||||
class WrapperMain:
|
||||
""" Anime4K CPP wrapper
|
||||
"""
|
||||
|
||||
def __init__(self, driver_settings):
|
||||
self.driver_settings = driver_settings
|
||||
self.print_lock = threading.Lock()
|
||||
|
||||
@staticmethod
|
||||
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')
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def parse_arguments(arguments):
|
||||
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('-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])')
|
||||
return parser.parse_args(arguments)
|
||||
|
||||
def load_configurations(self, upscaler):
|
||||
self.driver_settings['zoomFactor'] = upscaler.scale_ratio
|
||||
self.driver_settings['threads'] = upscaler.processes
|
||||
|
||||
def upscale(self, input_file, output_file):
|
||||
"""This is the core function for WAIFU2X class
|
||||
|
||||
Arguments:
|
||||
input_file {string} -- source directory path
|
||||
output_file {string} -- output directory path
|
||||
width {int} -- output video width
|
||||
height {int} -- output video height
|
||||
"""
|
||||
|
||||
# overwrite config file settings
|
||||
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)
|
||||
|
||||
# list to be executed
|
||||
# initialize the list with waifu2x binary path as the first element
|
||||
execute = [self.driver_settings.pop('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 value is None or value is False:
|
||||
continue
|
||||
else:
|
||||
if len(key) == 1:
|
||||
execute.append(f'-{key}')
|
||||
else:
|
||||
execute.append(f'--{key}')
|
||||
|
||||
# true means key is an option
|
||||
if value is not True:
|
||||
execute.append(str(value))
|
||||
|
||||
# return the Popen object of the new process created
|
||||
self.print_lock.acquire()
|
||||
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {shlex.join(execute)}')
|
||||
self.print_lock.release()
|
||||
return subprocess.Popen(execute)
|
||||
@@ -1,23 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: FFMPEG Class
|
||||
Name: Video2X FFmpeg Controller
|
||||
Author: K4YT3X
|
||||
Date Created: Feb 24, 2018
|
||||
Last Modified: May 4, 2019
|
||||
Last Modified: May 9, 2020
|
||||
|
||||
Description: This class handles all FFMPEG related
|
||||
operations.
|
||||
Description: This class handles all FFmpeg related operations.
|
||||
"""
|
||||
from avalon_framework import Avalon
|
||||
|
||||
# built-in imports
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
# third-party imports
|
||||
from avalon_framework import Avalon
|
||||
|
||||
|
||||
class Ffmpeg:
|
||||
"""This class communicates with ffmpeg
|
||||
"""This class communicates with FFmpeg
|
||||
|
||||
This class deals with ffmpeg. It handles extracitng
|
||||
This class deals with FFmpeg. It handles extracting
|
||||
frames, stripping audio, converting images into videos
|
||||
and inserting audio tracks to videos.
|
||||
"""
|
||||
@@ -25,21 +29,56 @@ class Ffmpeg:
|
||||
def __init__(self, ffmpeg_settings, image_format):
|
||||
self.ffmpeg_settings = ffmpeg_settings
|
||||
|
||||
self.ffmpeg_path = self.ffmpeg_settings['ffmpeg_path']
|
||||
# add a forward slash to directory if not present
|
||||
# otherwise there will be a format error
|
||||
if self.ffmpeg_path[-1] != '/' and self.ffmpeg_path[-1] != '\\':
|
||||
self.ffmpeg_path = f'{self.ffmpeg_path}\\'
|
||||
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_binary = f'{self.ffmpeg_path}ffmpeg.exe'
|
||||
self.ffmpeg_probe_binary = f'{self.ffmpeg_path}ffprobe.exe'
|
||||
# video metadata
|
||||
self.image_format = image_format
|
||||
self.intermediate_file_name = pathlib.Path(self.ffmpeg_settings['intermediate_file_name'])
|
||||
self.pixel_format = None
|
||||
|
||||
def get_pixel_formats(self):
|
||||
""" Get a dictionary of supported pixel formats
|
||||
|
||||
List all supported pixel formats and their
|
||||
corresponding bit depth.
|
||||
|
||||
Returns:
|
||||
dictionary -- JSON dict of all pixel formats to bit depth
|
||||
"""
|
||||
execute = [
|
||||
self.ffmpeg_probe_binary,
|
||||
'-v',
|
||||
'quiet',
|
||||
'-pix_fmts'
|
||||
]
|
||||
|
||||
# turn elements into str
|
||||
execute = [str(e) for e in execute]
|
||||
|
||||
Avalon.debug_info(f'Executing: {" ".join(execute)}')
|
||||
|
||||
# initialize dictionary to store pixel formats
|
||||
pixel_formats = {}
|
||||
|
||||
# record all pixel formats into dictionary
|
||||
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])
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
|
||||
# print pixel formats for debugging
|
||||
Avalon.debug_info(str(pixel_formats))
|
||||
|
||||
return pixel_formats
|
||||
|
||||
def get_video_info(self, input_video):
|
||||
""" Gets input video information
|
||||
|
||||
This method reads input video information
|
||||
using ffprobe in dictionary.
|
||||
using ffprobe in dictionary
|
||||
|
||||
Arguments:
|
||||
input_video {string} -- input video file path
|
||||
@@ -62,6 +101,9 @@ class Ffmpeg:
|
||||
input_video
|
||||
]
|
||||
|
||||
# turn elements into str
|
||||
execute = [str(e) for e in execute]
|
||||
|
||||
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'))
|
||||
@@ -69,8 +111,7 @@ class Ffmpeg:
|
||||
def extract_frames(self, input_video, extracted_frames):
|
||||
"""Extract every frame from original videos
|
||||
|
||||
This method extracts every frame from videoin
|
||||
using ffmpeg
|
||||
This method extracts every frame from input video using FFmpeg
|
||||
|
||||
Arguments:
|
||||
input_video {string} -- input video path
|
||||
@@ -84,17 +125,21 @@ class Ffmpeg:
|
||||
|
||||
execute.extend([
|
||||
'-i',
|
||||
input_video,
|
||||
f'{extracted_frames}\\extracted_%0d.{self.image_format}'
|
||||
input_video
|
||||
])
|
||||
|
||||
self._execute(execute)
|
||||
execute.extend(self._read_configuration(phase='video_to_frames', section='output_options'))
|
||||
|
||||
def convert_video(self, framerate, resolution, upscaled_frames):
|
||||
execute.extend([
|
||||
extracted_frames / f'extracted_%0d.{self.image_format}'
|
||||
])
|
||||
|
||||
return(self._execute(execute))
|
||||
|
||||
def assemble_video(self, framerate, resolution, upscaled_frames):
|
||||
"""Converts images into videos
|
||||
|
||||
This method converts a set of images into a
|
||||
video.
|
||||
This method converts a set of images into a video
|
||||
|
||||
Arguments:
|
||||
framerate {float} -- target video framerate
|
||||
@@ -109,29 +154,38 @@ class Ffmpeg:
|
||||
resolution
|
||||
]
|
||||
|
||||
# read other options
|
||||
execute.extend(self._read_configuration(phase='frames_to_video'))
|
||||
|
||||
# read FFmpeg input options
|
||||
execute.extend(self._read_configuration(phase='frames_to_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)
|
||||
for frame_name in upscaled_frames.iterdir():
|
||||
(upscaled_frames / frame_name).rename(upscaled_frames / regex.sub('.png', str(frame_name)))
|
||||
# END WORKAROUND
|
||||
|
||||
# append input frames path into command
|
||||
execute.extend([
|
||||
'-i',
|
||||
f'{upscaled_frames}\\extracted_%d.{self.image_format}'
|
||||
upscaled_frames / f'extracted_%d.{self.image_format}'
|
||||
])
|
||||
|
||||
# read FFmpeg output options
|
||||
execute.extend(self._read_configuration(phase='frames_to_video', section='output_options'))
|
||||
|
||||
# read other options
|
||||
execute.extend(self._read_configuration(phase='frames_to_video'))
|
||||
|
||||
# specify output file location
|
||||
execute.extend([
|
||||
f'{upscaled_frames}\\no_audio.mp4'
|
||||
upscaled_frames / self.intermediate_file_name
|
||||
])
|
||||
|
||||
self._execute(execute)
|
||||
return(self._execute(execute))
|
||||
|
||||
def migrate_audio_tracks_subtitles(self, input_video, output_video, upscaled_frames):
|
||||
def migrate_streams(self, input_video, output_video, upscaled_frames):
|
||||
""" Migrates audio tracks and subtitles from input video to output video
|
||||
|
||||
Arguments:
|
||||
@@ -140,22 +194,25 @@ class Ffmpeg:
|
||||
upscaled_frames {string} -- directory containing upscaled frames
|
||||
"""
|
||||
execute = [
|
||||
self.ffmpeg_binary,
|
||||
'-i',
|
||||
f'{upscaled_frames}\\no_audio.mp4',
|
||||
'-i',
|
||||
input_video
|
||||
self.ffmpeg_binary
|
||||
]
|
||||
|
||||
execute.extend(self._read_configuration(phase='frames_to_video', section='output_options'))
|
||||
execute.extend(self._read_configuration(phase='migrating_tracks'))
|
||||
|
||||
execute.extend([
|
||||
'-i',
|
||||
upscaled_frames / self.intermediate_file_name,
|
||||
'-i',
|
||||
input_video
|
||||
])
|
||||
|
||||
execute.extend(self._read_configuration(phase='migrating_tracks', section='output_options'))
|
||||
|
||||
execute.extend([
|
||||
output_video
|
||||
])
|
||||
|
||||
execute.extend(self._read_configuration(phase='migrating_tracks'))
|
||||
|
||||
self._execute(execute)
|
||||
return(self._execute(execute))
|
||||
|
||||
def _read_configuration(self, phase, section=None):
|
||||
""" read configuration from JSON
|
||||
@@ -175,6 +232,13 @@ class Ffmpeg:
|
||||
# from only that section
|
||||
if section:
|
||||
source = self.ffmpeg_settings[phase][section].keys()
|
||||
|
||||
# if pixel format is not specified, use the source pixel format
|
||||
try:
|
||||
if self.ffmpeg_settings[phase][section].get('-pix_fmt') is None:
|
||||
self.ffmpeg_settings[phase][section]['-pix_fmt'] = self.pixel_format
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
source = self.ffmpeg_settings[phase].keys()
|
||||
|
||||
@@ -186,8 +250,18 @@ 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, list) or isinstance(value, dict):
|
||||
if value is None or value is False or isinstance(value, dict):
|
||||
continue
|
||||
|
||||
# if the value is a list, append the same argument and all values
|
||||
elif isinstance(value, list):
|
||||
|
||||
for subvalue in value:
|
||||
configuration.append(key)
|
||||
if value is not True:
|
||||
configuration.append(str(subvalue))
|
||||
|
||||
# otherwise the value is typical
|
||||
else:
|
||||
configuration.append(key)
|
||||
|
||||
@@ -208,5 +282,9 @@ class Ffmpeg:
|
||||
Returns:
|
||||
int -- execution return code
|
||||
"""
|
||||
# turn all list elements into string to avoid errors
|
||||
execute = [str(e) for e in execute]
|
||||
|
||||
Avalon.debug_info(f'Executing: {execute}')
|
||||
return subprocess.run(execute, shell=True, check=True).returncode
|
||||
|
||||
return subprocess.Popen(execute)
|
||||
103
src/wrappers/srmd_ncnn_vulkan.py
Normal file
103
src/wrappers/srmd_ncnn_vulkan.py
Normal file
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: SRMD NCNN Vulkan Driver
|
||||
Creator: K4YT3X
|
||||
Date Created: April 26, 2020
|
||||
Last Modified: May 11, 2020
|
||||
|
||||
Description: This class is a high-level wrapper
|
||||
for srmd_ncnn_vulkan.
|
||||
"""
|
||||
|
||||
# built-in imports
|
||||
import argparse
|
||||
import os
|
||||
import pathlib
|
||||
import platform
|
||||
import shlex
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
# third-party imports
|
||||
from avalon_framework import Avalon
|
||||
|
||||
|
||||
class WrapperMain:
|
||||
"""This class communicates with SRMD NCNN Vulkan engine
|
||||
|
||||
An object will be created for this class, containing information
|
||||
about the binary address and the processing method. When being called
|
||||
by the main program, other detailed information will be passed to
|
||||
the upscale function.
|
||||
"""
|
||||
|
||||
def __init__(self, driver_settings):
|
||||
self.driver_settings = driver_settings
|
||||
self.print_lock = threading.Lock()
|
||||
|
||||
@staticmethod
|
||||
def parse_arguments(arguments):
|
||||
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, choices=range(2, 5), 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')
|
||||
return parser.parse_args(arguments)
|
||||
|
||||
def load_configurations(self, upscaler):
|
||||
self.driver_settings['s'] = int(upscaler.scale_ratio)
|
||||
self.driver_settings['j'] = '{}:{}:{}'.format(upscaler.processes, upscaler.processes, upscaler.processes)
|
||||
|
||||
def upscale(self, input_directory, output_directory):
|
||||
"""This is the core function for SRMD ncnn Vulkan class
|
||||
|
||||
Arguments:
|
||||
input_directory {string} -- source directory path
|
||||
output_directory {string} -- output directory path
|
||||
ratio {int} -- output video ratio
|
||||
"""
|
||||
|
||||
# overwrite config file settings
|
||||
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)
|
||||
|
||||
# list to be executed
|
||||
# initialize the list with the binary path as the first element
|
||||
execute = [self.driver_settings.pop('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 value is None or value is False:
|
||||
continue
|
||||
else:
|
||||
if len(key) == 1:
|
||||
execute.append(f'-{key}')
|
||||
else:
|
||||
execute.append(f'--{key}')
|
||||
|
||||
# true means key is an option
|
||||
if value is not True:
|
||||
execute.append(str(value))
|
||||
|
||||
# return the Popen object of the new process created
|
||||
self.print_lock.acquire()
|
||||
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {shlex.join(execute)}')
|
||||
self.print_lock.release()
|
||||
return subprocess.Popen(execute)
|
||||
105
src/wrappers/waifu2x_caffe.py
Normal file
105
src/wrappers/waifu2x_caffe.py
Normal file
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Waifu2x Caffe Driver
|
||||
Author: K4YT3X
|
||||
Date Created: Feb 24, 2018
|
||||
Last Modified: May 11, 2020
|
||||
|
||||
Description: This class is a high-level wrapper
|
||||
for waifu2x-caffe.
|
||||
"""
|
||||
|
||||
# built-in imports
|
||||
import argparse
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
# third-party imports
|
||||
from avalon_framework import Avalon
|
||||
|
||||
|
||||
class WrapperMain:
|
||||
"""This class communicates with waifu2x cui engine
|
||||
|
||||
An object will be created for this class, containing information
|
||||
about the binary address and the processing method. When being called
|
||||
by the main program, other detailed information will be passed to
|
||||
the upscale function.
|
||||
"""
|
||||
|
||||
def __init__(self, driver_settings):
|
||||
self.driver_settings = driver_settings
|
||||
self.print_lock = threading.Lock()
|
||||
|
||||
@staticmethod
|
||||
def parse_arguments(arguments):
|
||||
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', 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_file', type=str, help=argparse.SUPPRESS) # help='(required) path to input image file')
|
||||
return parser.parse_args(arguments)
|
||||
|
||||
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.image_format
|
||||
|
||||
# bit_depth will be 12 at this point
|
||||
# it will up updated later
|
||||
self.driver_settings['output_depth'] = 12
|
||||
|
||||
def upscale(self, input_directory, output_directory):
|
||||
""" start upscaling process
|
||||
"""
|
||||
|
||||
# overwrite config file settings
|
||||
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.pop('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 value is None or value is False:
|
||||
continue
|
||||
else:
|
||||
if len(key) == 1:
|
||||
execute.append(f'-{key}')
|
||||
else:
|
||||
execute.append(f'--{key}')
|
||||
|
||||
# true means key is an option
|
||||
if value is not True:
|
||||
execute.append(str(value))
|
||||
|
||||
# return the Popen object of the new process created
|
||||
self.print_lock.acquire()
|
||||
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {shlex.join(execute)}')
|
||||
self.print_lock.release()
|
||||
return subprocess.Popen(execute)
|
||||
119
src/wrappers/waifu2x_converter_cpp.py
Normal file
119
src/wrappers/waifu2x_converter_cpp.py
Normal file
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Waifu2x Converter CPP Driver
|
||||
Author: K4YT3X
|
||||
Date Created: February 8, 2019
|
||||
Last Modified: May 11, 2020
|
||||
|
||||
Description: This class is a high-level wrapper
|
||||
for waifu2x-converter-cpp.
|
||||
"""
|
||||
|
||||
# built-in imports
|
||||
import argparse
|
||||
import os
|
||||
import pathlib
|
||||
import shlex
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
# third-party imports
|
||||
from avalon_framework import Avalon
|
||||
|
||||
|
||||
class WrapperMain:
|
||||
"""This class communicates with waifu2x cui engine
|
||||
|
||||
An object will be created for this class, containing information
|
||||
about the binary address and the processing method. When being called
|
||||
by the main program, other detailed information will be passed to
|
||||
the upscale function.
|
||||
"""
|
||||
|
||||
def __init__(self, driver_settings):
|
||||
self.driver_settings = driver_settings
|
||||
self.print_lock = threading.Lock()
|
||||
|
||||
@staticmethod
|
||||
def parse_arguments(arguments):
|
||||
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.')
|
||||
return parser.parse_args(arguments)
|
||||
|
||||
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.image_format.lower()
|
||||
|
||||
def upscale(self, input_directory, output_directory):
|
||||
""" Waifu2x Converter Driver Upscaler
|
||||
This method executes the upscaling of extracted frames.
|
||||
|
||||
Arguments:
|
||||
input_directory {string} -- source directory path
|
||||
output_directory {string} -- output directory path
|
||||
scale_ratio {int} -- frames' scale ratio
|
||||
threads {int} -- number of threads
|
||||
"""
|
||||
|
||||
# overwrite config file settings
|
||||
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'
|
||||
|
||||
# list to be executed
|
||||
# initialize the list with waifu2x binary path as the first element
|
||||
execute = [self.driver_settings.pop('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 value is None or value is False:
|
||||
continue
|
||||
else:
|
||||
if len(key) == 1:
|
||||
execute.append(f'-{key}')
|
||||
else:
|
||||
execute.append(f'--{key}')
|
||||
|
||||
# true means key is an option
|
||||
if value is not True:
|
||||
execute.append(str(value))
|
||||
|
||||
# return the Popen object of the new process created
|
||||
self.print_lock.acquire()
|
||||
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {shlex.join(execute)}')
|
||||
self.print_lock.release()
|
||||
return subprocess.Popen(execute)
|
||||
106
src/wrappers/waifu2x_ncnn_vulkan.py
Normal file
106
src/wrappers/waifu2x_ncnn_vulkan.py
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name: Waifu2x NCNN Vulkan Driver
|
||||
Creator: SAT3LL
|
||||
Date Created: June 26, 2019
|
||||
Last Modified: May 11, 2020
|
||||
|
||||
Editor: K4YT3X
|
||||
Last Modified: February 22, 2020
|
||||
|
||||
Description: This class is a high-level wrapper
|
||||
for waifu2x_ncnn_vulkan.
|
||||
"""
|
||||
|
||||
# built-in imports
|
||||
import argparse
|
||||
import os
|
||||
import pathlib
|
||||
import platform
|
||||
import shlex
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
# third-party imports
|
||||
from avalon_framework import Avalon
|
||||
|
||||
|
||||
class WrapperMain:
|
||||
"""This class communicates with waifu2x ncnn vulkan engine
|
||||
|
||||
An object will be created for this class, containing information
|
||||
about the binary address and the processing method. When being called
|
||||
by the main program, other detailed information will be passed to
|
||||
the upscale function.
|
||||
"""
|
||||
|
||||
def __init__(self, driver_settings):
|
||||
self.driver_settings = driver_settings
|
||||
self.print_lock = threading.Lock()
|
||||
|
||||
@staticmethod
|
||||
def parse_arguments(arguments):
|
||||
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, choices=range(1, 3), 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')
|
||||
return parser.parse_args(arguments)
|
||||
|
||||
def load_configurations(self, upscaler):
|
||||
self.driver_settings['s'] = int(upscaler.scale_ratio)
|
||||
self.driver_settings['j'] = '{}:{}:{}'.format(upscaler.processes, upscaler.processes, upscaler.processes)
|
||||
|
||||
def upscale(self, input_directory, output_directory):
|
||||
"""This is the core function for WAIFU2X class
|
||||
|
||||
Arguments:
|
||||
input_directory {string} -- source directory path
|
||||
output_directory {string} -- output directory path
|
||||
ratio {int} -- output video ratio
|
||||
"""
|
||||
|
||||
# overwrite config file settings
|
||||
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)
|
||||
|
||||
# list to be executed
|
||||
# initialize the list with waifu2x binary path as the first element
|
||||
execute = [self.driver_settings.pop('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 value is None or value is False:
|
||||
continue
|
||||
else:
|
||||
if len(key) == 1:
|
||||
execute.append(f'-{key}')
|
||||
else:
|
||||
execute.append(f'--{key}')
|
||||
|
||||
# true means key is an option
|
||||
if value is not True:
|
||||
execute.append(str(value))
|
||||
|
||||
# return the Popen object of the new process created
|
||||
self.print_lock.acquire()
|
||||
Avalon.debug_info(f'[upscaler] Subprocess {os.getpid()} executing: {shlex.join(execute)}')
|
||||
self.print_lock.release()
|
||||
return subprocess.Popen(execute)
|
||||
Reference in New Issue
Block a user