├── .gitignore
├── .gitmodules
├── DAINVulkanCLI-Colab.ipynb
├── LICENSE
├── README.md
├── requirements-gui.txt
├── requirements-optional.txt
├── requirements.txt
├── res
├── colab-64x.png
├── linux-64x.png
└── windows-64x.png
└── src
├── DAINVulkanCLI.py
├── DAINVulkanGUI.py
├── cain_ncnn_vulkan.py
├── dain_ncnn_vulkan.py
├── definitions.py
├── ffmpeg.py
├── ffprobe.py
├── gui_layout.ui
├── image_similarity.py
├── interpolator.py
├── rife_ncnn_vulkan.py
├── rife_pytorch.py
└── video_extract.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | # IntelliJ IDE
132 | .idea/
133 |
134 | # Dolphin fm metadata
135 | .directory
136 |
137 | # Don't store large binaries in git repo
138 | dependencies/
139 | src/dependencies/
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "src/RIFE"]
2 | path = src/RIFE
3 | url = https://github.com/Mar2ck/arXiv2020-RIFE
4 |
--------------------------------------------------------------------------------
/DAINVulkanCLI-Colab.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "name": "DAINVulkanCLI-Colab.ipynb",
7 | "provenance": [],
8 | "private_outputs": true,
9 | "collapsed_sections": [],
10 | "toc_visible": true
11 | },
12 | "kernelspec": {
13 | "name": "python3",
14 | "display_name": "Python 3"
15 | },
16 | "accelerator": "GPU"
17 | },
18 | "cells": [
19 | {
20 | "cell_type": "markdown",
21 | "metadata": {
22 | "id": "F78H7JkR5c49"
23 | },
24 | "source": [
25 | "# DAIN-Vulkan-GUI Colab\n",
26 | "[Mar2ck/DAIN-Vulkan-GUI](https://github.com/Mar2ck/DAIN-Vulkan-GUI/)"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "metadata": {
32 | "id": "-OapminG4kJV"
33 | },
34 | "source": [
35 | "# Connect Google Drive\n",
36 | "from google.colab import drive\n",
37 | "drive.mount('/content/drive')\n",
38 | "print('Google Drive connected.')"
39 | ],
40 | "execution_count": null,
41 | "outputs": []
42 | },
43 | {
44 | "cell_type": "code",
45 | "metadata": {
46 | "id": "O0fPt2JG4014"
47 | },
48 | "source": [
49 | "# Check GPU\n",
50 | "!nvidia-smi"
51 | ],
52 | "execution_count": null,
53 | "outputs": []
54 | },
55 | {
56 | "cell_type": "code",
57 | "metadata": {
58 | "id": "U94yuBubvpZo"
59 | },
60 | "source": [
61 | "# Install Vulkan libraries\n",
62 | "!apt install -y libvulkan1"
63 | ],
64 | "execution_count": null,
65 | "outputs": []
66 | },
67 | {
68 | "cell_type": "code",
69 | "metadata": {
70 | "id": "TUU4As0Mv9TK"
71 | },
72 | "source": [
73 | "# Download DAIN-Vulkan-GUI\n",
74 | "!git clone https://github.com/Mar2ck/DAIN-Vulkan-GUI"
75 | ],
76 | "execution_count": null,
77 | "outputs": []
78 | },
79 | {
80 | "cell_type": "code",
81 | "metadata": {
82 | "id": "heZk2eVricsn"
83 | },
84 | "source": [
85 | "# Download dependencies\n",
86 | "!wget \"https://github.com/Mar2ck/DAIN-Vulkan-GUI/releases/download/0.0.2/dependencies-linux.tar.xz\"\n",
87 | "!tar -xvf dependencies-linux.tar.xz -C ./DAIN-Vulkan-GUI/src/\n",
88 | "!python3 -m pip install -r /content/DAIN-Vulkan-GUI/requirements.txt\n",
89 | "!python3 -m pip install -r /content/DAIN-Vulkan-GUI/requirements-optional.txt"
90 | ],
91 | "execution_count": null,
92 | "outputs": []
93 | },
94 | {
95 | "cell_type": "code",
96 | "metadata": {
97 | "id": "YV2Pz_VLlYw2"
98 | },
99 | "source": [
100 | "# Check help page\n",
101 | "!python3 /content/DAIN-Vulkan-GUI/src/DAINVulkanCLI.py --help"
102 | ],
103 | "execution_count": null,
104 | "outputs": []
105 | },
106 | {
107 | "cell_type": "code",
108 | "metadata": {
109 | "id": "Y7CJ2apU44Vc"
110 | },
111 | "source": [
112 | "# Run DAINVulkanCLI\n",
113 | "!python3 /content/DAIN-Vulkan-GUI/src/DAINVulkanCLI.py -i \"/content/drive/My Drive/Videos/example.mp4\" -O \"/content/\" -t 2048 --interpolator \"cain-ncnn\""
114 | ],
115 | "execution_count": null,
116 | "outputs": []
117 | }
118 | ]
119 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DAIN-Vulkan-GUI
2 | AI-Powered video interpolater (eg. 30fps -> 60fps) for Vulkan devices. Based on dain-ncnn-vulkan and ffmpeg
3 |
4 | WIP Software so expect bugs, GUI soon™
5 |
6 | ## Download
7 | Windows | Linux | Google Colab
8 | :-: | :-: | :-:
9 | [](https://github.com/Mar2ck/DAIN-Vulkan-GUI/releases) | [](https://github.com/Mar2ck/DAIN-Vulkan-GUI/releases) | [](https://colab.research.google.com/github/Mar2ck/DAIN-Vulkan-GUI/blob/master/DAINVulkanCLI-Colab.ipynb)
10 |
11 |
12 | ## Usage
13 | Windows: `.\DAINVulkanCLI.exe -i "C:\Users\example\Videos\test.mp4" --output-folder "C:\Users\example\Videos\DainFolder"`
14 |
15 | Linux: `./DAINVulkanCLI -i "/home/example/Videos/test.mp4" --output-folder "/home/example/Videos/DainFolder"`
16 |
17 | ## Features
18 | * Static frame interpolation
19 | * Dain-ncnn: 2x, 3x, 4x, 5x, etc. Multiplier-target
20 | * Cain-ncnn, Rife-ncnn: 2x, 4x, 8x, etc. Multiplier-target
21 | * Multi-threading (-j)
22 | * Multi-gpu (-g)
23 | * Dynamic interpolation (dain-ncnn) (duplicate frames are interpolated)
24 | * Dynamic 1x mode (framerate stays the same, duplicate frames are replaced with interpolations)
25 |
26 | ### Todo
27 | * Dynamic interpolation (cain-ncnn, RIFE)
28 | * Perfect loop (Last frame leads into the first)
29 | * Framerate-target
30 | * Slow-mo mode (framerate stays the same, video is slowed down via interpolation)
31 |
32 | ### Needs to be fixed by Dain-ncnn author
33 | * Tiles don't overlap (artifacting when using tiles)
34 | * Transparency (glitchy output currently)
35 | * "vkWaitForFences failed" error when using large tilesizes on Windows
36 |
37 | ## Tips
38 | The program can be set to process two frames at once (`-j 1:2:2`). This allows for the GPU to be used almost 100% of the time instead of pausing everytime a frame needs to be saved/loaded which gives a very slight speed increase. The downside however is that two frames will be in memory at once so a lower tile size will be needed if there isn't enough VRAM.
39 |
40 | Tiles are used by default which can slow down processing. Using a tilesize that's equal to or bigger then the video's resolution will disable tiles and process the frame all at once. Eg. 720p = 1280x720 so use `-t 1280`
41 |
42 | ## Errors
43 | "vkQueueSubmit failed" and "vkAllocateMemory failed" happens when there isn't enough VRAM for the current frame. Use a lower tile size or downscale the video.
44 |
45 | ## Help message
46 | ```
47 | usage: DAINVulkanCLI.py [-h] -i INPUT_FILE -O OUTPUT_FOLDER [-o OUTPUT_FILE]
48 | [--delete-output-folder] [-m INTERPOLATION_MODE]
49 | [-x FRAME_MULTIPLIER] [--target-fps TARGET_FPS]
50 | [-e INTERPOLATOR_ENGINE] [--loop-video]
51 | [--duplicate-auto-delete DUPLICATE_AUTO_DELETE]
52 | [-g GPU_ID] [-t TILE_SIZE] [-j THREADS]
53 | [--steps STEPS] [--video-type VIDEO_TYPE]
54 | [--copy-mtime] [--input-fps INPUT_FPS] [--verbose]
55 | [--debug]
56 |
57 | optional arguments:
58 | -h, --help show this help message and exit
59 | -i INPUT_FILE, --input-file INPUT_FILE
60 | Path to input video
61 | -O OUTPUT_FOLDER, --output-folder OUTPUT_FOLDER
62 | Folder to output work to
63 | -o OUTPUT_FILE, --output-file OUTPUT_FILE
64 | Path to copy final video to (can be directory or file
65 | path)
66 | --delete-output-folder
67 | Delete output folder at the end, intended to be used
68 | with --output-file
69 | -m INTERPOLATION_MODE, --interpolation-mode INTERPOLATION_MODE
70 | Interpolation type (static/dynamic, default=static)
71 | -x FRAME_MULTIPLIER, --frame-multiplier FRAME_MULTIPLIER
72 | Frame multiplier 2x,3x,etc (default=2)
73 | --target-fps TARGET_FPS
74 | Calculates frame multiplier based on a target
75 | framerate
76 | -e INTERPOLATOR_ENGINE, --interpolator-engine INTERPOLATOR_ENGINE
77 | Pick interpolator: dain-ncnn, cain-ncnn, rife-ncnn
78 | (default=dain-ncnn)
79 | --loop-video [Unimplemented] Interpolates video as a loop (last
80 | frame leads into the first)
81 | --duplicate-auto-delete DUPLICATE_AUTO_DELETE
82 | Based on a percentage (Eg. 0.95) will delete any
83 | frames found to be more similar
84 | -g GPU_ID, --gpu-id GPU_ID
85 | GPU to use (default=auto) can be 0,1,2 for multi-gpu
86 | -t TILE_SIZE, --tile-size TILE_SIZE
87 | Tile size (>=128, default=256) must be multiple of 32,
88 | can be 256,256,128 for multi-gpu
89 | -j THREADS, --threads THREADS
90 | Thread count for load/process/save (default=1:2:2) can
91 | be 1:2,2,2:2 for multi-gpu
92 | --steps STEPS If specified only run certain steps 1,2,3 (eg. 1,2 for
93 | 1 & 2 only)
94 | --video-type VIDEO_TYPE
95 | Video type for output video eg. mp4, webm, mkv
96 | (default=mp4)
97 | --copy-mtime Copy the modified timestamp to output
98 | --input-fps INPUT_FPS
99 | Manually specify framerate of input video
100 | --verbose Print additional info to the commandline
101 | --debug Print debug messages to the commandline
102 | ```
103 |
104 | ## Credits
105 | Interpolation programs that this project is a wrapper for:
106 | * https://github.com/nihui/dain-ncnn-vulkan
107 | * https://github.com/nihui/cain-ncnn-vulkan
108 | * https://github.com/nihui/rife-ncnn-vulkan
109 | * https://github.com/hzwer/arXiv2020-RIFE
110 |
111 | All in one program for video decoding/encoding:
112 | * https://ffmpeg.org/
113 |
--------------------------------------------------------------------------------
/requirements-gui.txt:
--------------------------------------------------------------------------------
1 | PyQt5>=5.15.1
--------------------------------------------------------------------------------
/requirements-optional.txt:
--------------------------------------------------------------------------------
1 | # Used to accelerate duplicate frame detection with OpenCL, will fallback to cpu if not installed
2 | pyopencl>=2020.2.2
3 |
4 | # Used for RIFE (can use CPU-only or CUDA versions)
5 | #torch>=1.7.0
6 | #torchvision>=0.8.1
7 | #torch==1.7.0+cpu
8 | #torchvision==0.8.1+cpu
9 | #opencv-python-headless>=4.4.0.46
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | Pillow>=8.0.1
2 | alive-progress>=1.6.1
3 | SSIM-PIL>=1.0.10
--------------------------------------------------------------------------------
/res/colab-64x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mar2ck/DAIN-Vulkan-GUI/7f8d61764d5edba33a1078c16b7ee9c151cc6cdf/res/colab-64x.png
--------------------------------------------------------------------------------
/res/linux-64x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mar2ck/DAIN-Vulkan-GUI/7f8d61764d5edba33a1078c16b7ee9c151cc6cdf/res/linux-64x.png
--------------------------------------------------------------------------------
/res/windows-64x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mar2ck/DAIN-Vulkan-GUI/7f8d61764d5edba33a1078c16b7ee9c151cc6cdf/res/windows-64x.png
--------------------------------------------------------------------------------
/src/DAINVulkanCLI.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | DAIN-Vulkan-GUI: CLI Frontend
4 | AI-Powered video interpolater (eg. 30fps -> 60fps) for Vulkan devices. Based on dain-ncnn-vulkan and ffmpeg
5 | """
6 | # Built-in modules
7 | import argparse
8 | import json
9 | import logging
10 | import math
11 | import os
12 | import pathlib
13 | from platform import system
14 | import shutil
15 |
16 | # Local modules
17 | import definitions
18 | import dain_ncnn_vulkan
19 | # import cain_ncnn_vulkan
20 | import ffmpeg
21 | import ffprobe
22 | # import video_extract
23 | import interpolator
24 | import image_similarity
25 |
26 |
27 | def main(input_file, output_folder, **kwargs):
28 | # System Info
29 | print("Platform:", system())
30 |
31 | # Set defaults for kwargs (argparse adds unused arguements to the dict even if unused)
32 | interpolator_engine = definitions.DEFAULT_INTERPOLATOR_ENGINE
33 | if ("interpolator_engine" in kwargs) and (kwargs["interpolator_engine"] is not None):
34 | interpolator_engine = kwargs["interpolator_engine"]
35 | video_type = definitions.DEFAULT_VIDEO_TYPE
36 | if ("video_type" in kwargs) and (kwargs["video_type"] is not None):
37 | video_type = kwargs["video_type"]
38 | loop_frames = definitions.DEFAULT_LOOP
39 | if ("loop_video" in kwargs) and (kwargs["loop_video"] is not None):
40 | loop_frames = kwargs["loop_video"]
41 |
42 | # Optional arguments for interpolators
43 | interpolatorOptions = {}
44 | if ("tile_size" in kwargs) and (kwargs["tile_size"] is not None):
45 | interpolatorOptions["tile_size"] = kwargs["tile_size"]
46 | if ("gpu_id" in kwargs) and (kwargs["gpu_id"] is not None):
47 | interpolatorOptions["gpu_id"] = kwargs["gpu_id"]
48 | if ("threads" in kwargs) and (kwargs["threads"] is not None):
49 | interpolatorOptions["threads"] = kwargs["threads"]
50 | print("Interpolator Options:", interpolatorOptions)
51 |
52 | # Parse step selection
53 | stepsSelection = None
54 | if ("steps" in kwargs) and (kwargs["steps"] is not None):
55 | stepsSelection = kwargs["steps"].split(",")
56 | print("Steps selected:", stepsSelection)
57 |
58 | # Input/Output Videos
59 | inputFile = os.path.abspath(input_file)
60 | inputFileName = pathlib.Path(inputFile).stem # Filename of input file without extension
61 | outputFolder = os.path.abspath(output_folder)
62 | print("Input file:", inputFile)
63 |
64 | # Input FPS, prioritize specified over detected
65 | if ("input_fps" in kwargs) and (kwargs["input_fps"] is not None):
66 | inputFileFps = kwargs["input_fps"]
67 | else:
68 | print("FFprobe: Scanning video metadata for framerate...")
69 | inputFileProperties = ffprobe.analyze_video_stream_metadata(inputFile)
70 | print(inputFileProperties)
71 | fracNum, fracDenom = inputFileProperties["fpsReal"].split("/")
72 | inputFileFps = int(fracNum) / int(fracDenom)
73 | print("Video fps:", inputFileFps)
74 |
75 | # Calculate multiplier if not specified
76 | frame_multiplier = definitions.DEFAULT_FRAME_MULTIPLIER
77 | if ("frame_multiplier" in kwargs) and (kwargs["frame_multiplier"] is not None):
78 | # Frame mutiplier is defined
79 | frame_multiplier = kwargs["frame_multiplier"]
80 | elif ("target_fps" in kwargs) and (kwargs["target_fps"] is not None):
81 | # Frame mutiplier is calculated from target_fps
82 | frame_multiplier_precise = int(kwargs["target_fps"])/inputFileFps
83 | if interpolator_engine.startswith("dain-ncnn"):
84 | # Round up
85 | frame_multiplier = math.ceil(frame_multiplier_precise)
86 | elif interpolator_engine.startswith(("cain-ncnn", "rife")):
87 | if (frame_multiplier_precise % 1) == 0 and (int(frame_multiplier_precise) & (int(frame_multiplier_precise) - 1) == 0):
88 | # If number is decimal and is a power of 2
89 | frame_multiplier = int(frame_multiplier_precise)
90 | else:
91 | # Else round up to next power of 2
92 | frame_multiplier = 2 ** (int(float(frame_multiplier_precise).hex().split('p+')[1]) + 1)
93 | print("Multiplier:", frame_multiplier)
94 |
95 | # Setup working folder and predefined output folders
96 | folderBase = os.path.join(outputFolder, inputFileName)
97 | pathlib.Path(folderBase).mkdir(parents=True, exist_ok=True) # Create base folder at start
98 | print("Working Directory:", folderBase)
99 | folderOriginalFrames = os.path.join(folderBase, "original_frames")
100 | folderInterpolatedFrames = os.path.join(folderBase, "interpolated_frames")
101 | folderOutputVideos = os.path.join(folderBase, "output_videos")
102 | infoJsonFilePath = os.path.join(folderBase, "info.json")
103 |
104 | # Read info from json
105 | infoJsonFile = {}
106 | if os.path.isfile(infoJsonFilePath):
107 | try:
108 | infoJsonFile = json.load(open(infoJsonFilePath, 'r'))
109 | print("info.json read:", infoJsonFile)
110 | except ValueError:
111 | print("info.json not read")
112 | else:
113 | print("Creating info.json")
114 | pathlib.Path(infoJsonFilePath).touch()
115 |
116 | # Step 1: Original Video -> Original Frames
117 | if (stepsSelection is None) or ("1" in stepsSelection):
118 | print("\nStep 1: Extracting frames to original_frames")
119 | ffmpeg.extract_frames(inputFile, folderOriginalFrames)
120 | folderOriginalFramesExtractedCount = len(os.listdir(folderOriginalFrames))
121 | infoJsonFile["extracted_frames"] = folderOriginalFramesExtractedCount
122 | print("Extracted frame count:", folderOriginalFramesExtractedCount)
123 |
124 | if ("duplicate_auto_delete" in kwargs) and (kwargs["duplicate_auto_delete"] is not None):
125 | print("Auto-deleting original_frames over {} similarity...".format(kwargs["duplicate_auto_delete"]))
126 | image_similarity.delete_similar_images(folderOriginalFrames, kwargs["duplicate_auto_delete"])
127 |
128 | # print("Removing alpha layer from original_frames...")
129 | # video_extract.png_directory_remove_alpha_channel(folderOriginalFrames)
130 |
131 | print("original_frames count:", len(os.listdir(folderOriginalFrames)))
132 |
133 | # Step 2: Original Frames -> Interpolated Frames
134 | if (stepsSelection is None) or ("2" in stepsSelection):
135 | print("\nStep 2: Processing frames to interpolated_frames using", interpolator_engine)
136 | print("Interpolating to: {}x".format(frame_multiplier))
137 |
138 | infoJsonFile["outputSuffixes"] = [] # Overwrite suffixes since step 2 is ran
139 | currentInterpolatorFolder = folderOriginalFrames
140 |
141 | # Dynamic interpolation
142 | if ("interpolation_mode" in kwargs) and (kwargs["interpolation_mode"] == "dynamic"):
143 | if interpolator_engine.startswith("dain-ncnn"): # Timestep-based dynamic
144 | folderDynamic = os.path.join(folderBase, "dynamic-1x")
145 | interpolator.interpolate_dynamic(currentInterpolatorFolder, folderDynamic,
146 | infoJsonFile["extracted_frames"], loop=loop_frames,
147 | **interpolatorOptions)
148 |
149 | currentInterpolatorFolder = folderDynamic
150 | infoJsonFile["outputSuffixes"].append("-Dynamic1x".format(frame_multiplier))
151 | else: # Non-timestep dynamic
152 | # TODO Add dynamic interpolation for engines without time-step
153 | print("ERROR: Dynamic interpolation not currently supported by", interpolator_engine)
154 |
155 | # Static interpolation
156 | if frame_multiplier >= 2:
157 | folderInterpolatedFramesCount = len(os.listdir(folderOriginalFrames)) * frame_multiplier
158 | print("interpolated_frames count", folderInterpolatedFramesCount)
159 | if interpolator_engine.startswith("dain-ncnn"):
160 | dain_ncnn_vulkan.interpolate_folder_mode(currentInterpolatorFolder, folderInterpolatedFrames,
161 | frame_multiplier, **interpolatorOptions)
162 | currentInterpolatorFolder = folderInterpolatedFrames
163 | infoJsonFile["outputSuffixes"].append("-Dain{}x".format(frame_multiplier))
164 | elif interpolator_engine.startswith("cain-ncnn"):
165 | interpolator.folder_multiplier_handler(currentInterpolatorFolder, folderInterpolatedFrames,
166 | frame_multiplier, engine="cain-ncnn",
167 | **interpolatorOptions)
168 | currentInterpolatorFolder = folderInterpolatedFrames
169 | infoJsonFile["outputSuffixes"].append("-Cain{}x".format(frame_multiplier))
170 | elif interpolator_engine.startswith("rife-ncnn"):
171 | interpolator.folder_multiplier_handler(currentInterpolatorFolder, folderInterpolatedFrames,
172 | frame_multiplier, engine="rife-ncnn",
173 | **interpolatorOptions)
174 | currentInterpolatorFolder = folderInterpolatedFrames
175 | infoJsonFile["outputSuffixes"].append("-Rife{}x".format(frame_multiplier))
176 | # elif interpolator_engine.startswith("rife"):
177 | # import rife_pytorch
178 | # rife_pytorch.interpolate_folder_mode(currentInterpolatorFolder, folderInterpolatedFrames,
179 | # frame_multiplier)
180 | # currentInterpolatorFolder = folderInterpolatedFrames
181 | # infoJsonFile["outputSuffixes"].append("-Rife{}x".format(frame_multiplier))
182 | else:
183 | print("Invalid interpolator option")
184 | exit(1)
185 |
186 | # Rename last folder to interpolated_frames if not already
187 | if currentInterpolatorFolder is not folderInterpolatedFrames:
188 | if os.path.isdir(folderInterpolatedFrames) is True:
189 | print("\"{}\" already exists, deleting".format(folderInterpolatedFrames))
190 | shutil.rmtree(folderInterpolatedFrames)
191 | os.rename(currentInterpolatorFolder, folderInterpolatedFrames)
192 |
193 | # Step 3: Interpolated Frames -> Output Video
194 | if (stepsSelection is None) or ("3" in stepsSelection):
195 | print("\nStep 3: Extracting frames to output_videos")
196 | outputFile = os.path.join(folderOutputVideos, inputFileName + "".join(infoJsonFile["outputSuffixes"]) +
197 | "." + video_type)
198 | ffmpeg.encode_frames(folderInterpolatedFrames,
199 | outputFile,
200 | str(inputFileFps * frame_multiplier))
201 |
202 | if ("copy_audio" in kwargs) and (kwargs["copy_audio"] is True):
203 | print("Copying audio to output...")
204 | infoJsonFile["outputSuffixes"].append("-audio")
205 | last_output_file = outputFile
206 | outputFile = os.path.join(folderOutputVideos, inputFileName + "".join(infoJsonFile["outputSuffixes"]) +
207 | "." + video_type)
208 | ffmpeg.combine_video_audio(last_output_file, inputFile, outputFile)
209 |
210 | if ("copy_mtime" in kwargs) and (kwargs["copy_mtime"] is True): # Copy mtime to output
211 | print("Copying mtime to output...")
212 | inputFileModifiedTime = os.path.getmtime(inputFile)
213 | os.utime(outputFile, (inputFileModifiedTime, inputFileModifiedTime))
214 |
215 | if ("output_file" in kwargs) and (kwargs["output_file"] is not None): # Copy output file to destination
216 | print("Copying output file to --output-file...")
217 | shutil.copy2(outputFile, os.path.dirname(inputFile))
218 |
219 | # Write info to json at the end
220 | json.dump(infoJsonFile, open(infoJsonFilePath, "w"))
221 |
222 | if ("delete_output_folder" in kwargs) and (kwargs["delete_output_folder"] is True):
223 | print("Deleting working directory...")
224 | shutil.rmtree(folderBase)
225 |
226 |
227 | if __name__ == "__main__":
228 | # Console arguments
229 | parser = argparse.ArgumentParser()
230 | # Path options
231 | parser.add_argument("-i", "--input-file", required=True, help="Path to input video")
232 | parser.add_argument("-O", "--output-folder", required=True, help="Folder to output work to")
233 | parser.add_argument("-o", "--output-file", help="Path to copy final video to (can be directory or file path)")
234 | parser.add_argument("--delete-output-folder", action="store_true",
235 | help="Delete output folder at the end, intended to be used with --output-file")
236 | # Interpolation options
237 | parser.add_argument("-m", "--interpolation-mode", default=definitions.DEFAULT_INTERPOLATOR_MODE,
238 | help="Interpolation type (static/dynamic, default=static)")
239 | parser.add_argument("-x", "--frame-multiplier", type=int,
240 | help="Frame multiplier 2x,3x,etc (default=2)")
241 | parser.add_argument("--target-fps", help="Calculates frame multiplier based on a target framerate")
242 | parser.add_argument("-e", "--interpolator-engine", default=definitions.DEFAULT_INTERPOLATOR_ENGINE,
243 | help="Pick interpolator: dain-ncnn, cain-ncnn, rife-ncnn (default=dain-ncnn)")
244 | parser.add_argument("--loop-video", action="store_true",
245 | help="[Unimplemented] Interpolates video as a loop (last frame leads into the first)")
246 | parser.add_argument("--duplicate-auto-delete", type=float,
247 | help="Based on a percentage (Eg. 0.95) will delete any frames found to be more similar")
248 | # Dain-ncnn/Cain-ncnn pass-through options
249 | parser.add_argument("-g", "--gpu-id", help="GPU to use (default=auto) can be 0,1,2 for multi-gpu")
250 | parser.add_argument("-t", "--tile-size",
251 | help="Tile size (>=128, default=256) must be multiple of 32, can be 256,256,128 for multi-gpu")
252 | parser.add_argument("-j", "--threads",
253 | help="Thread count for load/process/save (default=1:2:2) can be 1:2,2,2:2 for multi-gpu")
254 | # Step options
255 | parser.add_argument("--steps", help="If specified only run certain steps 1,2,3 (eg. 1,2 for 1 & 2 only)")
256 | # Output file options
257 | parser.add_argument("--video-type", default=definitions.DEFAULT_VIDEO_TYPE,
258 | help="Video type for output video eg. mp4, webm, mkv (default=mp4)")
259 | parser.add_argument("--copy-mtime", action="store_true", help="Copy the modified timestamp to output")
260 | parser.add_argument("--copy-audio", action="store_true", help="Copy the input audio to output")
261 | # Debug options
262 | parser.add_argument("--input-fps", type=float, help="Manually specify framerate of input video")
263 | parser.add_argument("--verbose", action="store_true", help="Print additional info to the commandline")
264 | parser.add_argument("--debug", action="store_true", help="Print debug messages to the commandline")
265 | arguments = vars(parser.parse_args())
266 |
267 | # Logging
268 | if arguments["verbose"] is True:
269 | logging.basicConfig(level=logging.INFO)
270 | if arguments["debug"] is True:
271 | logging.basicConfig(level=logging.DEBUG)
272 |
273 | main(**arguments)
274 |
--------------------------------------------------------------------------------
/src/DAINVulkanGUI.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # Built-in modules
4 | import os
5 | import sys
6 |
7 | # Local modules
8 | import dain_ncnn_vulkan
9 | import cain_ncnn_vulkan
10 | import DAINVulkanCLI
11 |
12 | # External modules
13 | from PyQt5 import uic
14 | from PyQt5.QtWidgets import *
15 | from PyQt5.QtCore import *
16 |
17 |
18 | def error_popup(message):
19 | msg = QMessageBox()
20 | msg.setWindowTitle("Error")
21 | print(message)
22 | msg.setText(message)
23 | msg.exec_()
24 |
25 |
26 | class Worker(QRunnable):
27 | def __init__(self, *args, **kwargs):
28 | super(Worker, self).__init__()
29 | self.args = args
30 | self.kwargs = kwargs
31 |
32 | @pyqtSlot()
33 | def run(self):
34 | print(self.kwargs)
35 | DAINVulkanCLI.main(**self.kwargs)
36 | print("Done!")
37 |
38 |
39 | class MainWindow(QMainWindow):
40 | def input_file_dialog_box(self):
41 | self.input_file = QFileDialog.getOpenFileName(None, 'Open input file', os.getenv('HOME'),
42 | 'Videos (*.mp4 *.mkv *.webm);;'
43 | 'Animated images (*.gif *.apng *.png);;'
44 | 'All Files (*)')[0]
45 |
46 | print("Selected input file: {}".format(self.input_file))
47 | if not self.input_file:
48 | self.input_label.setText('Input Path')
49 | else:
50 | self.input_label.setText(self.input_file)
51 |
52 | def output_file_dialog_box(self):
53 | self.output_dir = QFileDialog.getExistingDirectory(None, 'Choose output folder', os.getenv('HOME'))
54 | print("Selected output folder: {}".format(self.output_dir))
55 | if not self.output_dir:
56 | self.output_label.setText('Output Path')
57 | else:
58 | self.output_label.setText(self.output_dir)
59 |
60 | def interpolator_engine_combo_box_changed(self):
61 | print("combobox changed to", self.engine_combo_box.currentText())
62 | if self.engine_combo_box.currentText().lower().startswith("dain-ncnn"):
63 | self.tile_size_line_edit.setPlaceholderText(str(dain_ncnn_vulkan.DEFAULT_TILE_SIZE))
64 | elif self.engine_combo_box.currentText().lower().startswith("cain-ncnn"):
65 | self.tile_size_line_edit.setPlaceholderText(str(cain_ncnn_vulkan.DEFAULT_TILE_SIZE))
66 |
67 | def worker_execute(self):
68 | # Required arguments
69 | if not self.input_file:
70 | error_popup("Please specify an input file")
71 | return -1
72 | if not self.output_dir:
73 | error_popup("Please specify an output folder")
74 | return -1
75 |
76 | kwargs = {
77 | "input_file": self.input_file,
78 | "output_folder": self.output_dir,
79 | "interpolator_engine": self.engine_combo_box.currentText(),
80 | }
81 |
82 | # Add optional arguments to kwargs only if specified
83 | if self.tile_size_line_edit.text():
84 | kwargs["tile_size"] = self.tile_size_line_edit.text()
85 | if self.gpu_id_line_edit.text():
86 | kwargs["gpu_id"] = self.gpu_id_line_edit.text()
87 | if self.threads_line_edit.text():
88 | kwargs["threads"] = self.threads_line_edit.text()
89 |
90 | # Execute
91 | worker = Worker(**kwargs)
92 | self.threadpool.start(worker)
93 |
94 | def __init__(self):
95 | super(MainWindow, self).__init__()
96 |
97 | # Create thread pool and limit to one thread
98 | self.threadpool = QThreadPool()
99 | self.threadpool.setMaxThreadCount(1)
100 | print("Multithreading with maximum {} threads".format(self.threadpool.maxThreadCount()))
101 |
102 | # Load layout from xml file
103 | uic.loadUi("gui_layout.ui", self)
104 |
105 | self.setWindowTitle("DAIN-Vulkan-GUI")
106 |
107 | # Input/Output
108 | self.input_file_button = self.findChild(QPushButton, 'inputFileButton')
109 | self.input_file_button.clicked.connect(self.input_file_dialog_box)
110 | self.input_file = None
111 | self.input_label = self.findChild(QLabel, 'inputFileLabel')
112 |
113 | self.output_file_button = self.findChild(QPushButton, 'outputFileButton')
114 | self.output_file_button.clicked.connect(self.output_file_dialog_box)
115 | self.output_dir = None
116 | self.output_label = self.findChild(QLabel, 'outputFileLabel')
117 |
118 | # Interpolator Engine Options
119 | self.engine_combo_box = self.findChild(QComboBox, "engineComboBox")
120 | self.engine_combo_box.currentTextChanged.connect(self.interpolator_engine_combo_box_changed)
121 | self.tile_size_line_edit = self.findChild(QLineEdit, 'tileSizeLineEdit')
122 | self.tile_size_line_edit.setPlaceholderText(str(dain_ncnn_vulkan.DEFAULT_TILE_SIZE))
123 | self.gpu_id_line_edit = self.findChild(QLineEdit, 'gpuIdLineEdit')
124 | self.gpu_id_line_edit.setPlaceholderText(dain_ncnn_vulkan.DEFAULT_GPU_ID)
125 | self.threads_line_edit = self.findChild(QLineEdit, 'threadsLineEdit')
126 | self.threads_line_edit.setPlaceholderText(dain_ncnn_vulkan.DEFAULT_THREADS)
127 |
128 | # Execute button
129 | self.execute_button = self.findChild(QPushButton, 'executeButton')
130 | self.execute_button.clicked.connect(self.worker_execute)
131 |
132 | self.show()
133 |
134 |
135 | if __name__ == "__main__":
136 | app = QApplication(sys.argv)
137 | window = MainWindow()
138 | # app.setStyle("Fusion")
139 | window.show()
140 | app.exec_()
141 |
--------------------------------------------------------------------------------
/src/cain_ncnn_vulkan.py:
--------------------------------------------------------------------------------
1 | """
2 | cain-ncnn-vulkan process wrapper
3 |
4 | Cain does not support time-step (aka: always set to "0.5")
5 | Neither does it support target-frames for the same reason
6 | """
7 | # Built-in modules
8 | import os
9 | import pathlib
10 | import shutil
11 | import subprocess
12 | # Local modules
13 | import definitions
14 | # External modules
15 | from alive_progress import alive_bar
16 |
17 | # Interpolation Defaults
18 | DEFAULT_GPU_ID = "auto"
19 | DEFAULT_THREADS = "1:1:1"
20 |
21 |
22 | def interpolate_file_mode(input0_file, input1_file, output_file,
23 | gpu_id=DEFAULT_GPU_ID, threads=DEFAULT_THREADS, **kwargs):
24 | """File-mode Interpolation"""
25 | # Make sure parent folder of output_file exists
26 | pathlib.Path(os.path.dirname(output_file)).mkdir(parents=True, exist_ok=True)
27 | cmd = [definitions.CAIN_NCNN_VULKAN_BIN,
28 | "-0", os.path.abspath(input0_file),
29 | "-1", os.path.abspath(input1_file),
30 | "-o", os.path.abspath(output_file),
31 | "-g", str(gpu_id),
32 | "-j", threads]
33 | print(" ".join(cmd))
34 | subprocess.run(cmd, cwd=definitions.CAIN_NCNN_VULKAN_LOCATION)
35 |
36 |
37 | def interpolate_folder_mode(input_folder, output_folder,
38 | gpu_id=DEFAULT_GPU_ID, threads=DEFAULT_THREADS,
39 | verbose=False, **kwargs):
40 | """Folder-mode Interpolation"""
41 | target_frames = len(os.listdir(input_folder)) * 2
42 |
43 | if os.path.isdir(output_folder): # Delete output_folder if it exists to avoid conflicts
44 | shutil.rmtree(output_folder)
45 | pathlib.Path(output_folder).mkdir(parents=True, exist_ok=True) # Create output_folder
46 |
47 | cmd = [definitions.CAIN_NCNN_VULKAN_BIN,
48 | "-i", os.path.abspath(input_folder),
49 | "-o", os.path.abspath(output_folder),
50 | "-g", str(gpu_id),
51 | "-j", threads,
52 | "-v"]
53 | if verbose is True:
54 | print(" ".join(cmd))
55 | # subprocess.run(cmd, cwd=definitions.CAIN_NCNN_VULKAN_LOCATION)
56 | with alive_bar(target_frames, enrich_print=False) as bar:
57 | with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
58 | cwd=definitions.CAIN_NCNN_VULKAN_LOCATION, bufsize=1, universal_newlines=True) as process:
59 | for line in process.stderr:
60 | if line.startswith("["): # Starting GPU info
61 | print(line, end="")
62 | elif line.endswith("done\n"): # Verbose progress output
63 | bar()
64 | elif line.startswith(("find_blob_index_by_name", "fopen")): # Model not found error
65 | raise OSError("Model not found: {}".format(line.replace("\n", "")))
66 | elif line.startswith("vkAllocateMemory failed"): # VRAM memory error
67 | raise RuntimeError("VRAM memory error: {}".format(line.replace("\n", "")))
68 | elif line.startswith(("vkWaitForFences failed", "vkQueueSubmit failed")): # General vulkan error
69 | raise RuntimeError("Vulkan error: {}".format(line.replace("\n", "")))
70 | else:
71 | print(line, end="")
72 |
--------------------------------------------------------------------------------
/src/dain_ncnn_vulkan.py:
--------------------------------------------------------------------------------
1 | """
2 | dain-ncnn-vulkan process wrapper
3 | """
4 | # Built-in modules
5 | # import logging
6 | import os
7 | import pathlib
8 | import shutil
9 | import subprocess
10 | # Local modules
11 | import definitions
12 | # External modules
13 | from alive_progress import alive_bar
14 |
15 | # Interpolation Defaults
16 | DEFAULT_TIME_STEP = 0.5
17 | DEFAULT_MULTIPLIER = 2
18 | DEFAULT_TILE_SIZE = 256
19 | DEFAULT_GPU_ID = "auto"
20 | DEFAULT_THREADS = "1:1:1"
21 |
22 |
23 | def interpolate_file_mode(input0_file, input1_file, output_file, time_step=DEFAULT_TIME_STEP,
24 | tile_size=DEFAULT_TILE_SIZE, gpu_id=DEFAULT_GPU_ID, threads=DEFAULT_THREADS):
25 | """File-mode Interpolation"""
26 | # Make sure parent folder of output_file exists
27 | pathlib.Path(os.path.dirname(output_file)).mkdir(parents=True, exist_ok=True)
28 | cmd = [definitions.DAIN_NCNN_VULKAN_BIN,
29 | "-0", os.path.abspath(input0_file),
30 | "-1", os.path.abspath(input1_file),
31 | "-o", os.path.abspath(output_file),
32 | "-s", str(time_step),
33 | "-t", str(tile_size),
34 | "-g", str(gpu_id),
35 | "-j", threads]
36 | print(" ".join(cmd))
37 | subprocess.run(cmd, cwd=definitions.DAIN_NCNN_VULKAN_LOCATION)
38 |
39 |
40 | def interpolate_folder_mode(input_folder, output_folder, multiplier=DEFAULT_MULTIPLIER,
41 | tile_size=DEFAULT_TILE_SIZE, gpu_id=DEFAULT_GPU_ID, threads=DEFAULT_THREADS,
42 | verbose=False):
43 | """Folder-mode Interpolation"""
44 | # Calculate double input frames as default
45 | target_frames = len(os.listdir(input_folder)) * int(multiplier)
46 |
47 | if os.path.isdir(output_folder): # Delete output_folder if it exists to avoid conflicts
48 | shutil.rmtree(output_folder)
49 | pathlib.Path(output_folder).mkdir(parents=True, exist_ok=True) # Create output_folder
50 |
51 | cmd = [definitions.DAIN_NCNN_VULKAN_BIN,
52 | "-i", os.path.abspath(input_folder),
53 | "-o", os.path.abspath(output_folder),
54 | "-n", str(target_frames),
55 | "-t", str(tile_size),
56 | "-g", str(gpu_id),
57 | "-j", threads,
58 | "-v"]
59 | if verbose is True:
60 | print(" ".join(cmd))
61 | # subprocess.run(cmd, cwd=definitions.DAIN_NCNN_VULKAN_LOCATION)
62 | with alive_bar(target_frames, enrich_print=False) as bar:
63 | with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
64 | cwd=definitions.DAIN_NCNN_VULKAN_LOCATION, bufsize=1, universal_newlines=True) as process:
65 | for line in process.stderr:
66 | if line.startswith("["): # Starting GPU info
67 | print(line, end="")
68 | elif line.endswith("done\n"): # Verbose progress output
69 | bar()
70 | elif line.startswith("invalid tilesize argument"): # Tilesize error
71 | raise ValueError(line.replace("\n", ""))
72 | elif line.startswith(("find_blob_index_by_name", "fopen")): # Model not found error
73 | raise OSError("Model not found: {}".format(line.replace("\n", "")))
74 | elif line.startswith("vkAllocateMemory failed"): # VRAM memory error
75 | raise RuntimeError("VRAM memory error: {}".format(line.replace("\n", "")))
76 | elif line.startswith(("vkWaitForFences failed", "vkQueueSubmit failed")): # General vulkan error
77 | raise RuntimeError("Vulkan error: {}".format(line.replace("\n", "")))
78 | else:
79 | print(line, end="")
80 |
--------------------------------------------------------------------------------
/src/definitions.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | from pathlib import Path
4 | from platform import system
5 | from shutil import which
6 |
7 | # Project root folder
8 | ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
9 |
10 | # Default parameters
11 | DEFAULT_FRAME_MULTIPLIER = 2
12 | DEFAULT_INTERPOLATOR_MODE = "static"
13 | DEFAULT_INTERPOLATOR_ENGINE = "dain-ncnn"
14 | DEFAULT_LOOP = False
15 | DEFAULT_VIDEO_TYPE = "mp4"
16 |
17 | # Dain-ncnn-vulkan binary locations
18 | DAIN_NCNN_VULKAN = {
19 | "Windows": os.path.join(ROOT_DIR, "dependencies", "dain-ncnn-vulkan", "dain-ncnn-vulkan.exe"),
20 | "Darwin": os.path.join(ROOT_DIR, "dependencies", "dain-ncnn-vulkan", "dain-ncnn-vulkan-macos"),
21 | "Linux": os.path.join(ROOT_DIR, "dependencies", "dain-ncnn-vulkan", "dain-ncnn-vulkan-ubuntu")
22 | }
23 | DAIN_NCNN_VULKAN_BIN = DAIN_NCNN_VULKAN[system()]
24 | DAIN_NCNN_VULKAN_LOCATION = os.path.dirname(DAIN_NCNN_VULKAN_BIN)
25 |
26 | # Cain-ncnn-vulkan binary locations
27 | CAIN_NCNN_VULKAN = {
28 | "Windows": os.path.join(ROOT_DIR, "dependencies", "cain-ncnn-vulkan", "cain-ncnn-vulkan.exe"),
29 | "Darwin": os.path.join(ROOT_DIR, "dependencies", "cain-ncnn-vulkan", "cain-ncnn-vulkan-macos"),
30 | "Linux": os.path.join(ROOT_DIR, "dependencies", "cain-ncnn-vulkan", "cain-ncnn-vulkan-ubuntu")
31 | }
32 | CAIN_NCNN_VULKAN_BIN = CAIN_NCNN_VULKAN[system()]
33 | CAIN_NCNN_VULKAN_LOCATION = Path(CAIN_NCNN_VULKAN_BIN).parent
34 |
35 | # Rife-ncnn-vulkan binary locations
36 | RIFE_NCNN_VULKAN = {
37 | "Windows": os.path.join(ROOT_DIR, "dependencies", "rife-ncnn-vulkan", "rife-ncnn-vulkan.exe"),
38 | "Darwin": os.path.join(ROOT_DIR, "dependencies", "rife-ncnn-vulkan", "rife-ncnn-vulkan-macos"),
39 | "Linux": os.path.join(ROOT_DIR, "dependencies", "rife-ncnn-vulkan", "rife-ncnn-vulkan-ubuntu")
40 | }
41 | RIFE_NCNN_VULKAN_BIN = RIFE_NCNN_VULKAN[system()]
42 | RIFE_NCNN_VULKAN_LOCATION = Path(RIFE_NCNN_VULKAN_BIN).parent
43 |
44 | # FFmpeg binary locations
45 | FFMPEG = {
46 | "Windows": os.path.join(ROOT_DIR, "dependencies", "ffmpeg", "windows", "ffmpeg.exe"),
47 | "Darwin": os.path.join(ROOT_DIR, "dependencies", "ffmpeg", "macos", "ffmpeg"),
48 | "Linux": os.path.join(ROOT_DIR, "dependencies", "ffmpeg", "linux", "ffmpeg")
49 | }
50 | FFMPEG_BIN = None
51 | if os.path.isfile(FFMPEG[system()]) is True: # Use bundled version first
52 | logging.debug("FFmpeg version: bundled")
53 | FFMPEG_BIN = FFMPEG[system()]
54 | elif os.path.isfile(which("ffmpeg")) is True: # Else use the system version
55 | logging.debug("FFmpeg version: system")
56 | FFMPEG_BIN = os.path.normpath(which("ffmpeg"))
57 | else:
58 | logging.warning("ffmpeg not found")
59 |
60 | # FFprobe binary locations
61 | FFPROBE = {
62 | "Windows": os.path.join(ROOT_DIR, "dependencies", "ffmpeg", "windows", "ffprobe.exe"),
63 | "Darwin": os.path.join(ROOT_DIR, "dependencies", "ffmpeg", "macos", "ffprobe"),
64 | "Linux": os.path.join(ROOT_DIR, "dependencies", "ffmpeg", "linux", "ffprobe")
65 | }
66 | FFPROBE_BIN = None
67 | if os.path.isfile(FFPROBE[system()]) is True: # Use bundled version first
68 | logging.debug("FFprobe version: bundled")
69 | FFPROBE_BIN = FFPROBE[system()]
70 | elif os.path.isfile(which("ffprobe")) is True: # Else use the system version
71 | logging.debug("FFprobe version: system")
72 | FFPROBE_BIN = os.path.normpath(which("ffprobe"))
73 | else:
74 | logging.warning("ffprobe not found")
75 |
76 | # RIFE Model location
77 | RIFE_MODEL = os.path.join(ROOT_DIR, "RIFE", "train_log")
78 |
--------------------------------------------------------------------------------
/src/ffmpeg.py:
--------------------------------------------------------------------------------
1 | """
2 | FFmpeg process wrapper
3 | """
4 | # Built-in modules
5 | # import logging
6 | import os
7 | import pathlib
8 | import re
9 | import subprocess
10 | # Local modules
11 | import definitions
12 | import ffprobe
13 | # External modules
14 | from alive_progress import alive_bar
15 |
16 |
17 | def extract_frames(input_file, output_folder, verbose=False):
18 | """Extract video frames to a folder
19 | for -vsync: "crf" will use "r_frame_rate", "vfr" will use "avg_frame_rate"
20 | `ffmpeg -i "$i" original_frames/%06d.png`
21 | """
22 | # TODO add downscaling option
23 | stream_metadata = ffprobe.analyze_video_stream_metadata(input_file)
24 | frame_count = int(stream_metadata["packetCount"])
25 | vfrBool = (stream_metadata["fpsReal"] != stream_metadata["fpsAverage"]) # Video is cfr when average fps = real fps
26 |
27 | pathlib.Path(output_folder).mkdir(parents=True, exist_ok=True) # Create outputFolder
28 | cmd = [definitions.FFMPEG_BIN,
29 | "-i", input_file,
30 | "-vsync", "cfr",
31 | "-pix_fmt", "rgb24", # Usually defaults to rgba which causes alpha problems
32 | os.path.join(output_folder, "%08d.png")]
33 | if verbose is True:
34 | print(" ".join(cmd))
35 | # subprocess.run(cmd)
36 | if vfrBool is True:
37 | with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
38 | bufsize=1, universal_newlines=True) as process:
39 | for line in process.stderr:
40 | if line.startswith("frame="):
41 | print(line, end="")
42 | else:
43 | with alive_bar(frame_count, enrich_print=False) as bar:
44 | frame_count_processed_last = 0
45 | with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
46 | bufsize=1, universal_newlines=True) as process:
47 | for line in process.stderr:
48 | if line.startswith("frame="):
49 | # Parses inbetween "frame=" and "fps="
50 | frame_count_processed = int(re.findall(r"frame=(.+?)fps=", line)[0])
51 | bar(incr=(frame_count_processed - frame_count_processed_last))
52 | frame_count_processed_last = frame_count_processed
53 | elif verbose is True:
54 | print(line, end="")
55 |
56 |
57 | def encode_frames(input_folder, output_file, framerate, verbose=False):
58 | """Encode a folder of sequentially named frames into a video
59 | `ffmpeg -framerate 48 -i interpolated_frames/%06d.png -crf 18 output.mp4`
60 | """
61 | # TODO add an option for changing quality
62 | frame_count = len(os.listdir(input_folder))
63 | pathlib.Path(os.path.dirname(output_file)).mkdir(parents=True, exist_ok=True) # Create parent folder of outputFile
64 | cmd = [definitions.FFMPEG_BIN,
65 | "-framerate", str(framerate),
66 | "-i", os.path.join(input_folder, "%08d.png"),
67 | "-crf", "18",
68 | "-y", # Always write file
69 | output_file]
70 | if verbose is True:
71 | print(" ".join(cmd))
72 | # subprocess.run(cmd)
73 | with alive_bar(frame_count, enrich_print=False) as bar:
74 | frame_count_processed_last = 0
75 | with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
76 | bufsize=1, universal_newlines=True) as process:
77 | for line in process.stderr:
78 | if line.startswith("frame="):
79 | # Parses inbetween "frame=" and "fps="
80 | frame_count_processed = int(re.findall(r"frame=(.+?)fps=", line)[0])
81 | bar(incr=(frame_count_processed - frame_count_processed_last))
82 | frame_count_processed_last = frame_count_processed
83 | elif verbose is True:
84 | print(line, end="")
85 |
86 |
87 | def combine_video_audio(video_file, audio_file, output_file):
88 | # ffmpeg -i video.mp4 -i audio.webm -c:v copy -map 0:v:0 -map 1:a:0 output.mp4
89 | cmd = [definitions.FFMPEG_BIN,
90 | "-i", video_file,
91 | "-i", audio_file,
92 | "-c:v", "copy", # Don't reencode video stream
93 | "-map", "0:v:0",
94 | "-map", "1:a:0",
95 | output_file]
96 | subprocess.run(cmd)
97 |
--------------------------------------------------------------------------------
/src/ffprobe.py:
--------------------------------------------------------------------------------
1 | """
2 | FFprobe process wrapper
3 |
4 | - Some videos don't return "duration" and "nb_frames" such as apng
5 | - "nb_read_frames" won't be accurate if the input video is vfr
6 |
7 | http://svn.ffmpeg.org/doxygen/trunk/structAVStream.html
8 | "avg_frame_rate" is "Average framerate" aka: duration/framecount
9 | "r_frame_rate" is "Real base framerate" which is the lowest common framerate of all frames in the video
10 | """
11 | # Built-in modules
12 | import json
13 | import logging
14 | import subprocess
15 | # Local modules
16 | import definitions
17 |
18 |
19 | def analyze_video_stream_metadata(input_file):
20 | """Analyzes a video's stream and returns it's properties
21 | `ffprobe -show_streams -select_streams v:0 -count_packets -print_format json -loglevel quiet input.mp4`
22 | """
23 | cmd = [definitions.FFPROBE_BIN,
24 | "-show_streams",
25 | "-select_streams", "v:0",
26 | "-count_packets",
27 | "-print_format", "json",
28 | "-loglevel", "quiet",
29 | input_file]
30 | logging.info(" ".join(cmd))
31 | output = subprocess.check_output(cmd, universal_newlines=True)
32 | parsed_output = json.loads(output)["streams"][0]
33 | return({
34 | "fpsReal": parsed_output["r_frame_rate"],
35 | "fpsAverage": parsed_output["avg_frame_rate"],
36 | "packetCount": parsed_output["nb_read_packets"] # Unreliable if video is vfr
37 | })
38 |
39 |
40 | def analyze_video_frame_metadata(input_file):
41 | """Analyzes a video's frames and returns an array with their individual properities
42 | `ffprobe -show_frames -select_streams v:0 -print_format json -loglevel quiet input.mp4`
43 | """
44 | cmd = [definitions.FFPROBE_BIN,
45 | "-show_frames",
46 | "-select_streams", "v:0",
47 | "-print_format", "json",
48 | "-loglevel", "quiet",
49 | input_file]
50 | logging.info(" ".join(cmd))
51 | output = subprocess.check_output(cmd, universal_newlines=True)
52 | parsedOutput = json.loads(output)["frames"]
53 | return parsedOutput
54 |
--------------------------------------------------------------------------------
/src/gui_layout.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 | DAINVulkanGUI
4 |
5 |
6 |
7 | 0
8 | 0
9 | 600
10 | 720
11 |
12 |
13 |
14 | DAIN-Vulkan-GUI
15 |
16 |
17 |
18 | -
19 |
20 |
21 | 0
22 |
23 |
24 |
25 | Main
26 |
27 |
28 |
-
29 |
30 |
-
31 |
32 |
33 | Input/Output
34 |
35 |
36 |
-
37 |
38 |
39 |
40 | 0
41 | 0
42 |
43 |
44 |
45 | Output Folder
46 |
47 |
48 |
49 | -
50 |
51 |
52 | Input Path
53 |
54 |
55 | true
56 |
57 |
58 |
59 | -
60 |
61 |
62 |
63 | 0
64 | 0
65 |
66 |
67 |
68 |
69 | 16777215
70 | 16777215
71 |
72 |
73 |
74 | Input File
75 |
76 |
77 |
78 | -
79 |
80 |
81 | Output Path
82 |
83 |
84 | true
85 |
86 |
87 |
88 | -
89 |
90 |
91 | Qt::Vertical
92 |
93 |
94 |
95 | 20
96 | 40
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 | -
105 |
106 |
107 | Frame Handling
108 |
109 |
110 |
-
111 |
112 |
-
113 |
114 |
115 |
116 | 0
117 | 0
118 |
119 |
120 |
121 | Multiplier
122 |
123 |
124 |
125 | -
126 |
127 |
-
128 |
129 | 2x
130 |
131 |
132 | -
133 |
134 | 4x
135 |
136 |
137 |
138 |
139 |
140 |
141 | -
142 |
143 |
-
144 |
145 |
146 | FPS
147 |
148 |
149 |
150 | -
151 |
152 |
153 | true
154 |
155 |
156 |
157 | -
158 |
159 |
160 | ->
161 |
162 |
163 |
164 | -
165 |
166 |
167 | true
168 |
169 |
170 | true
171 |
172 |
173 |
174 |
175 |
176 | -
177 |
178 |
-
179 |
180 |
181 |
182 | 0
183 | 0
184 |
185 |
186 |
187 | Interpolation Mode
188 |
189 |
190 |
191 | -
192 |
193 |
194 |
195 | 0
196 | 0
197 |
198 |
199 |
-
200 |
201 | Static
202 |
203 |
204 | -
205 |
206 | Dynamic
207 |
208 |
209 |
210 |
211 |
212 |
213 | -
214 |
215 |
216 | Qt::Vertical
217 |
218 |
219 |
220 | 20
221 | 40
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 | -
230 |
231 |
232 |
233 | 0
234 | 0
235 |
236 |
237 |
238 | Interpolator Engine Options
239 |
240 |
241 |
-
242 |
243 |
244 | Engine
245 |
246 |
247 |
248 | -
249 |
250 |
251 | GPU ID
252 |
253 |
254 |
255 | -
256 |
257 |
258 | Tile-Size
259 |
260 |
261 |
262 | -
263 |
264 |
-
265 |
266 | dain-ncnn-vulkan
267 |
268 |
269 | -
270 |
271 | cain-ncnn-vulkan
272 |
273 |
274 |
275 |
276 | -
277 |
278 |
279 | Threads
280 |
281 |
282 |
283 | -
284 |
285 |
286 | 256
287 |
288 |
289 |
290 | -
291 |
292 |
293 | 1:1:1
294 |
295 |
296 |
297 | -
298 |
299 |
300 | auto
301 |
302 |
303 |
304 | -
305 |
306 |
307 | Qt::Vertical
308 |
309 |
310 |
311 | 20
312 | 40
313 |
314 |
315 |
316 |
317 |
318 |
319 |
320 |
321 |
322 | -
323 |
324 |
-
325 |
326 |
327 | Input Video Options
328 |
329 |
330 |
-
331 |
332 |
-
333 |
334 |
335 | Height
336 |
337 |
338 |
339 | -
340 |
341 |
342 |
343 |
344 | -
345 |
346 |
347 | Downscale Video
348 |
349 |
350 |
351 | -
352 |
353 |
354 | Qt::Vertical
355 |
356 |
357 |
358 | 20
359 | 40
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 | -
368 |
369 |
370 | Output Video Options
371 |
372 |
373 |
-
374 |
375 |
-
376 |
377 |
378 | Format
379 |
380 |
381 |
382 | -
383 |
384 |
385 |
386 | 0
387 | 0
388 |
389 |
390 |
-
391 |
392 | mp4
393 |
394 |
395 | -
396 |
397 | webm
398 |
399 |
400 | -
401 |
402 | mkv
403 |
404 |
405 |
406 |
407 |
408 |
409 | -
410 |
411 |
-
412 |
413 |
414 | Quality (-crf)
415 |
416 |
417 |
418 | -
419 |
420 |
421 | Lower value = better quality
422 |
423 |
424 |
425 |
426 |
427 | 18
428 |
429 |
430 |
431 |
432 |
433 | -
434 |
435 |
436 | Qt::Vertical
437 |
438 |
439 |
440 | 20
441 | 40
442 |
443 |
444 |
445 |
446 | -
447 |
448 |
449 | Audio passthrough
450 |
451 |
452 |
453 |
454 |
455 |
456 |
457 |
458 |
459 |
460 |
461 |
462 | Misc
463 |
464 |
465 |
466 |
467 | -
468 |
469 |
470 |
471 | 0
472 | 0
473 |
474 |
475 |
476 | Execute
477 |
478 |
479 |
480 | -
481 |
482 |
-
483 |
484 |
485 | Qt::Horizontal
486 |
487 |
488 | QSizePolicy::MinimumExpanding
489 |
490 |
491 |
492 | 8
493 | 20
494 |
495 |
496 |
497 |
498 | -
499 |
500 |
501 | Step 1: Decode video
502 |
503 |
504 | true
505 |
506 |
507 |
508 | -
509 |
510 |
511 | Qt::Horizontal
512 |
513 |
514 |
515 | 8
516 | 20
517 |
518 |
519 |
520 |
521 | -
522 |
523 |
524 | Step 2: Interpolate frames
525 |
526 |
527 | true
528 |
529 |
530 |
531 | -
532 |
533 |
534 | Qt::Horizontal
535 |
536 |
537 |
538 | 8
539 | 20
540 |
541 |
542 |
543 |
544 | -
545 |
546 |
547 | Step 3: Encode video
548 |
549 |
550 | true
551 |
552 |
553 |
554 | -
555 |
556 |
557 | Qt::Horizontal
558 |
559 |
560 | QSizePolicy::MinimumExpanding
561 |
562 |
563 |
564 | 8
565 | 20
566 |
567 |
568 |
569 |
570 |
571 |
572 | -
573 |
574 |
575 | Qt::Vertical
576 |
577 |
578 | QSizePolicy::Fixed
579 |
580 |
581 |
582 | 20
583 | 8
584 |
585 |
586 |
587 |
588 |
589 |
590 |
614 |
615 |
616 | About
617 |
618 |
619 |
620 |
621 | Exit
622 |
623 |
624 |
625 |
626 |
627 |
628 |
--------------------------------------------------------------------------------
/src/image_similarity.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Module for calculating the visual difference
4 | between images via SSIM. This can be used to
5 | detect whether video frames are duplicates.
6 |
7 | Requires: pillow, SSIM-PIL, progress
8 | Optional: pyopencl
9 | """
10 | # Built-in modules
11 | import logging
12 | import os
13 | import pathlib
14 | # External modules
15 | from PIL import Image
16 | from SSIM_PIL import compare_ssim
17 | from alive_progress import alive_bar
18 |
19 | DEFAULT_USE_GPU = True
20 | DEFAULT_SHOW_PROGRESS = False
21 |
22 |
23 | def calculate_ssim(image0_path, image1_path, use_gpu=True, resize_before_comparison=False):
24 | """Calculates SSIM based on two images"""
25 | # print("Processing:", image0path)
26 | image0 = Image.open(image0_path)
27 | image1 = Image.open(image1_path)
28 | if resize_before_comparison is True:
29 | image0 = image0.resize((512, 512))
30 | image1 = image1.resize((512, 512))
31 | return compare_ssim(image0, image1, GPU=use_gpu)
32 |
33 |
34 | def calculate_directory_ssim(directory_path, **kwargs):
35 | """Calculates the SSIM for every image in a directory
36 | based on it and the image that precedes it
37 | """
38 | # print(os.path.abspath(directoryPath))
39 | directory_files = []
40 | for filePath in pathlib.Path(directory_path).glob('**/*'): # List all files in the directory as their absolute path
41 | file_path_absolute = os.path.normpath(filePath.absolute())
42 | if file_path_absolute.endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp')):
43 | # Only adds files that have image extensions, fixes problems caused by "Thumbs.db"
44 | directory_files.append(file_path_absolute)
45 | directory_files.sort()
46 | # print(directory_files)
47 | directory_files_ssim = {}
48 | with alive_bar(len(directory_files) - 1, enrich_print=False) as bar:
49 | for i in range(1, len(directory_files)):
50 | file_ssim = calculate_ssim(directory_files[i], directory_files[i - 1], **kwargs)
51 | # print(file_ssim)
52 | directory_files_ssim[directory_files[i]] = file_ssim
53 | bar()
54 | return directory_files_ssim
55 |
56 |
57 | def delete_similar_images(directory_path, threshold, **kwargs):
58 | """Deletes any image that has an SSIM higher then the specified threshold"""
59 | ssimResults = calculate_directory_ssim(directory_path, **kwargs)
60 | for ssimResultsFile in sorted(ssimResults.keys()):
61 | if ssimResults[ssimResultsFile] > float(threshold):
62 | logging.info("Removing: {}".format(ssimResultsFile))
63 | os.remove(ssimResultsFile)
64 |
65 |
66 | if __name__ == "__main__":
67 | import argparse
68 | parser = argparse.ArgumentParser()
69 | parser.add_argument("-0", "--image0", help="Path of first image")
70 | parser.add_argument("-1", "--image1", help="Path of second image")
71 | parser.add_argument("-f", "--folder", help="Path of directory containing images")
72 | parser.add_argument("--delete-threshold", type=float, help="If specified, deletes duplicate images automatically"
73 | " based on a similarity percentage (Eg. 0.95)")
74 | parser.add_argument("--disable-gpu", action="store_true", help="Force SSIM calculation to use CPU instead of GPU")
75 | args = vars(parser.parse_args())
76 | useGpu = not args["disable_gpu"]
77 | if not ((args["image0"] and args["image1"]) or args["folder"]):
78 | parser.error('Requires either both --image0 and --image1 or --folder')
79 |
80 | if (args["image0"] is not None) and (args["image1"] is not None): # -image0 and -image1
81 | SSIM = calculate_ssim(args["image0"], args["image1"], use_gpu=useGpu)
82 | print("SSIM: {}".format(SSIM)) # -folder delete mode
83 | elif (args["folder"] is not None) and (args["delete_threshold"] is not None):
84 | delete_similar_images(args["folder"], args["delete_threshold"], use_gpu=useGpu)
85 | elif args["folder"] is not None: # -folder
86 | directorySSIM = calculate_directory_ssim(args["folder"], use_gpu=useGpu)
87 | for file in sorted(directorySSIM.keys()):
88 | print("{}: {}".format(file, directorySSIM[file]))
89 |
--------------------------------------------------------------------------------
/src/interpolator.py:
--------------------------------------------------------------------------------
1 | """
2 | Module for handling interpolation (aka: "step 2")
3 | """
4 | # Built-in Modules
5 | import os
6 | import pathlib
7 | import shutil
8 | # Local Modules
9 | import dain_ncnn_vulkan
10 | import cain_ncnn_vulkan
11 | import rife_ncnn_vulkan
12 |
13 | DEFAULT_MULTIPLIER = 2
14 | DEFAULT_MULTIPLIER_DYNAMIC = 1
15 | DEFAULT_INTERPOLATOR = "dain-ncnn"
16 |
17 |
18 | def _make_duplicate_frames(input_file, output_folder, output_count):
19 | """
20 | Copies the input_file a number of time
21 | Useful for creating duplicate frames before a scene change or at the end of a non-looping video
22 | """
23 | inputFileNumber = int(pathlib.Path(input_file).stem) # Get Filename (without extension) from path
24 | for i in range(output_count):
25 | outputFile = "{:06d}.png".format(inputFileNumber + i + 1)
26 | args = [os.path.join(output_folder, input_file), os.path.join(output_folder, outputFile)]
27 | print("Duplicating:", " -> ".join(args))
28 | shutil.copyfile(*args)
29 |
30 |
31 | def folder_multiplier_handler(input_folder, output_folder, multiplier, engine, **kwargs):
32 | """
33 | Achieve interpolation past 2x without using target_frames (which cain/rife lacks)
34 | by interpolating from one folder to the next Eg. First (1x -> 2x) then (2x -> 4x)
35 | Multiplies to a power of 2
36 | """
37 | folderParent = pathlib.Path(output_folder).parent
38 | multiplierInternal = 1
39 | interpolateFolderFrom = input_folder
40 | interpolateFolderTo = None
41 | if not (multiplier > 1):
42 | raise ValueError("Multiplier must be higher than 1")
43 | else:
44 | if not ((multiplier & (multiplier - 1) == 0) and multiplier != 0): # Check if not a power of 2
45 | raise ValueError("Multiplier must be a power of 2 (2, 4, 8, etc.)")
46 | else:
47 | interpolateOutputFolders = []
48 | while multiplierInternal < multiplier:
49 | multiplierInternal = multiplierInternal * 2
50 | print("From: \"{}\"".format(interpolateFolderFrom))
51 | interpolateFolderTo = os.path.join(folderParent, ("interpolate-" + str(multiplierInternal) + "x"))
52 | interpolateOutputFolders.append(interpolateFolderTo)
53 | print("To: \"{}\"".format(interpolateFolderTo))
54 | if engine == "cain-ncnn":
55 | cain_ncnn_vulkan.interpolate_folder_mode(interpolateFolderFrom, interpolateFolderTo, **kwargs)
56 | elif engine == "rife-ncnn":
57 | rife_ncnn_vulkan.interpolate_folder_mode(interpolateFolderFrom, interpolateFolderTo, **kwargs)
58 | else:
59 | raise ValueError("Invalid Engine")
60 | interpolateFolderFrom = interpolateFolderTo # Set last output folder to input folder for the next loop
61 | print("Renaming \"{}\" to \"{}\"".format(interpolateFolderTo, output_folder))
62 | if os.path.isdir(output_folder) is True:
63 | print("\"{}\" already exists, deleting".format(output_folder))
64 | shutil.rmtree(output_folder)
65 | os.rename(interpolateFolderTo, output_folder)
66 | if interpolateOutputFolders[:-1]:
67 | print("Deleting leftover folders:", interpolateOutputFolders[:-1])
68 | for folder in interpolateOutputFolders[:-1]:
69 | shutil.rmtree(folder)
70 |
71 |
72 | def interpolate_static(input_folder, output_folder,
73 | mulitplier=DEFAULT_MULTIPLIER, interpolator=None, loop=False, **kwargs):
74 | """
75 | Creates a static number of new frames between the original frames
76 | Eg: 2x = 1 original, 1 interpolated; 3x = 1 original, 2 interpolated
77 | """
78 | pass
79 |
80 |
81 | def interpolate_dynamic(input_folder, output_folder, original_frame_count, loop=False, **kwargs):
82 | """
83 | Creates a dynamic number of new frames that depends on the length of time between each original frame
84 | Reads frame position from original file names so removed frames are replaced
85 | Example at 2x: 1.png -> 2.png, 1 interpolated frame inbetween; 1.png -> 3.png, 3 interpolated frames inbetween
86 | ((gap_frames + 1) * multiplier) - 1 = interpolated_frames
87 | """
88 | def dynamic_internal(image0_filename, image1_filename, custom_frame_difference=None):
89 | shutil.copyfile(os.path.join(input_folder, image0_filename),os.path.join(output_folder, image0_filename))
90 | image0Number = int(image0_filename.split(".")[0])
91 | image1Number = int(image1_filename.split(".")[0])
92 | print("Image0: {}".format(image0_filename))
93 | print("Image1: {}".format(image1_filename))
94 | frameDifference = (image1Number - image0Number) if custom_frame_difference is None else custom_frame_difference
95 | inbetweenFrames = frameDifference - 1
96 | print("Inbetween frames: {}".format(inbetweenFrames))
97 | if inbetweenFrames >= 1:
98 | for n in range(inbetweenFrames):
99 | interpolatedFrameNumber = image0Number + n + 1
100 | interpolatedFrameName = "{:06d}.png".format(interpolatedFrameNumber)
101 | interpolatedFrameTimeStep = (n + 1) / frameDifference
102 | print("Interpolated frame: {} at time-step {}".format(interpolatedFrameName, interpolatedFrameTimeStep))
103 | dain_ncnn_vulkan.interpolate_file_mode(os.path.join(input_folder, image0_filename),
104 | os.path.join(input_folder, image1_filename),
105 | os.path.join(output_folder, interpolatedFrameName),
106 | time_step=interpolatedFrameTimeStep,
107 | **kwargs)
108 | print("")
109 |
110 | # Create output_folder if it doesn't exist
111 | pathlib.Path(output_folder).mkdir(parents=True, exist_ok=True)
112 |
113 | # Run against all frames except last
114 | inputFolderFiles = sorted(os.listdir(input_folder))
115 | for i in range(len(inputFolderFiles)-1):
116 | dynamic_internal(inputFolderFiles[i], inputFolderFiles[i+1])
117 |
118 | # Last frame handling
119 | frameDifferenceToEnd = (original_frame_count - int(inputFolderFiles[-1].split(".")[0]) + 1)
120 | if loop is True: # image1 is first frame
121 | dynamic_internal(inputFolderFiles[-1], inputFolderFiles[0],
122 | custom_frame_difference=frameDifferenceToEnd)
123 | else: # create duplicates til original frame count met
124 | shutil.copyfile(os.path.join(input_folder, inputFolderFiles[-1]),
125 | os.path.join(output_folder, inputFolderFiles[-1]))
126 | _make_duplicate_frames(os.path.join(input_folder, inputFolderFiles[-1]), output_folder,
127 | (frameDifferenceToEnd - 1))
128 |
--------------------------------------------------------------------------------
/src/rife_ncnn_vulkan.py:
--------------------------------------------------------------------------------
1 | """
2 | rife-ncnn-vulkan process wrapper
3 |
4 | Rife does not support time-step (aka: always set to "0.5")
5 | Neither does it support target-frames for the same reason
6 | """
7 | # Built-in modules
8 | import os
9 | import pathlib
10 | import shutil
11 | import subprocess
12 | # Local modules
13 | import definitions
14 | # External modules
15 | from alive_progress import alive_bar
16 |
17 | # Interpolation Defaults
18 | DEFAULT_GPU_ID = "auto"
19 | DEFAULT_THREADS = "1:1:1"
20 |
21 |
22 | def interpolate_file_mode(input0_file, input1_file, output_file,
23 | gpu_id=DEFAULT_GPU_ID, threads=DEFAULT_THREADS, **kwargs):
24 | """File-mode Interpolation"""
25 | # Make sure parent folder of output_file exists
26 | pathlib.Path(os.path.dirname(output_file)).mkdir(parents=True, exist_ok=True)
27 | cmd = [definitions.RIFE_NCNN_VULKAN_BIN,
28 | "-0", os.path.abspath(input0_file),
29 | "-1", os.path.abspath(input1_file),
30 | "-o", os.path.abspath(output_file),
31 | "-g", str(gpu_id),
32 | "-j", threads]
33 | print(" ".join(cmd))
34 | subprocess.run(cmd, cwd=definitions.RIFE_NCNN_VULKAN_LOCATION)
35 |
36 |
37 | def interpolate_folder_mode(input_folder, output_folder,
38 | gpu_id=DEFAULT_GPU_ID, threads=DEFAULT_THREADS,
39 | verbose=False, **kwargs):
40 | """Folder-mode Interpolation"""
41 | target_frames = len(os.listdir(input_folder)) * 2
42 |
43 | if os.path.isdir(output_folder): # Delete output_folder if it exists to avoid conflicts
44 | shutil.rmtree(output_folder)
45 | pathlib.Path(output_folder).mkdir(parents=True, exist_ok=True) # Create output_folder
46 |
47 | cmd = [definitions.RIFE_NCNN_VULKAN_BIN,
48 | "-i", os.path.abspath(input_folder),
49 | "-o", os.path.abspath(output_folder),
50 | "-g", str(gpu_id),
51 | "-j", threads,
52 | "-v"]
53 | if verbose is True:
54 | print(" ".join(cmd))
55 | # subprocess.run(cmd, cwd=definitions.RIFE_NCNN_VULKAN_LOCATION)
56 | with alive_bar(target_frames, enrich_print=False) as bar:
57 | with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
58 | cwd=definitions.RIFE_NCNN_VULKAN_LOCATION, bufsize=1, universal_newlines=True) as process:
59 | for line in process.stderr:
60 | if line.startswith("["): # Starting GPU info
61 | print(line, end="")
62 | elif line.endswith("done\n"): # Verbose progress output
63 | bar()
64 | elif line.startswith(("find_blob_index_by_name", "fopen")): # Model not found error
65 | raise OSError("Model not found: {}".format(line.replace("\n", "")))
66 | elif line.startswith("vkAllocateMemory failed"): # VRAM memory error
67 | raise RuntimeError("VRAM memory error: {}".format(line.replace("\n", "")))
68 | elif line.startswith(("vkWaitForFences failed", "vkQueueSubmit failed")): # General vulkan error
69 | raise RuntimeError("Vulkan error: {}".format(line.replace("\n", "")))
70 | else:
71 | print(line, end="")
72 |
--------------------------------------------------------------------------------
/src/rife_pytorch.py:
--------------------------------------------------------------------------------
1 | """
2 | RIFE PyTorch implementation
3 | """
4 | # Built-in modules
5 | # import numpy
6 | import os
7 | import pathlib
8 | import shutil
9 | import warnings
10 | # Local modules
11 | import definitions
12 | import RIFE.model.RIFE as RIFE # import from submodule
13 | # External modules
14 | from alive_progress import alive_bar
15 | import cv2
16 | import torch
17 | from torch.nn import functional
18 |
19 | DEFAULT_MULTIPLIER = 2
20 |
21 | # Init device and model on import
22 | if torch.cuda.is_available():
23 | print("RIFE: Using PyTorch CUDA backend")
24 | pytorch_device = torch.device("cuda")
25 | torch.set_grad_enabled(False)
26 | torch.backends.cudnn.enabled = True
27 | torch.backends.cudnn.benchmark = True
28 | else:
29 | print("RIFE: Using PyTorch CPU backend")
30 | pytorch_device = torch.device("cpu")
31 |
32 | rife_model = RIFE.Model()
33 | rife_model.load_model(definitions.RIFE_MODEL)
34 | rife_model.eval()
35 | rife_model.device()
36 |
37 | warnings.filterwarnings("ignore") # Supress console warnings
38 |
39 |
40 | def _read_image_dimensions(image_path):
41 | image = cv2.imread(image_path)
42 | image = (torch.tensor(image.transpose(2, 0, 1)).to(pytorch_device) / 255.).unsqueeze(0)
43 | n, c, height, width = image.shape
44 | return [height, width]
45 |
46 |
47 | def _read_image(image_path):
48 | image = cv2.imread(image_path)
49 | image = (torch.tensor(image.transpose(2, 0, 1)).to(pytorch_device) / 255.).unsqueeze(0)
50 | n, c, height, width = image.shape
51 | padding_height = ((height - 1) // 32 + 1) * 32
52 | padding_width = ((width - 1) // 32 + 1) * 32
53 | padding = (0, padding_width - width, 0, padding_height - height)
54 | image = functional.pad(image, padding)
55 | return image
56 |
57 |
58 | # def _write_image():
59 | # pass
60 |
61 |
62 | def interpolate_file_mode(input0_file, input1_file, output_file):
63 | height, width = _read_image_dimensions(input0_file)
64 | image0 = _read_image(input0_file)
65 | image1 = _read_image(input1_file)
66 |
67 | output = rife_model.inference(image0, image1) # Interpolation
68 |
69 | pathlib.Path(os.path.dirname(output_file)).mkdir(parents=True, exist_ok=True) # Create output_folder
70 |
71 | cv2.imwrite(output_file,
72 | (output[0] * 255).byte().cpu().numpy().transpose(1, 2, 0)[:height, :width]) # Write to output
73 |
74 |
75 | def interpolate_folder_mode(input_folder, output_folder, multiplier=DEFAULT_MULTIPLIER):
76 | # TODO srite images during interpolation to avoid disk write bottleneck at end
77 | # List images in folder
78 | input_files_path = []
79 | for filePath in pathlib.Path(input_folder).glob('**/*'): # List all files in the directory as their absolute path
80 | file_path_absolute = os.path.normpath(filePath.absolute())
81 | if file_path_absolute.endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp')):
82 | # Only adds files that have image extensions, fixes problems caused by "Thumbs.db"
83 | input_files_path.append(file_path_absolute)
84 | input_files_path.sort()
85 |
86 | # Read frame dimensions from first frame
87 | height, width = _read_image_dimensions(input_files_path[0])
88 |
89 | # Read files
90 | input_files = []
91 | for i in range(len(input_files_path)):
92 | # print(i)
93 | input_files.append(_read_image(input_files_path[i]))
94 |
95 | # Interpolate
96 | multiplier_internal = 1
97 | while multiplier_internal < multiplier:
98 | multiplier_internal = multiplier_internal * 2
99 | print("Interpolating to {}x:".format(multiplier_internal))
100 | with alive_bar(len(input_files) * 2, enrich_print=False) as bar:
101 | output_files = []
102 | for j in range(len(input_files) - 1):
103 | # print(input_files_path[j], input_files_path[j + 1])
104 | mid = rife_model.inference(input_files[j], input_files[j + 1])
105 | output_files.append(input_files[j])
106 | bar()
107 | output_files.append(mid)
108 | bar()
109 | for _ in range(2): # Duplicate last frame twice
110 | output_files.append(input_files[-1])
111 | bar()
112 | if multiplier_internal < multiplier:
113 | input_files = output_files
114 |
115 | if os.path.isdir(output_folder): # Delete output_folder if it exists to avoid conflicts
116 | shutil.rmtree(output_folder)
117 | pathlib.Path(output_folder).mkdir(parents=True, exist_ok=True) # Create output_folder
118 | for i in range(len(output_files)):
119 | cv2.imwrite(os.path.join(output_folder, "{:06d}.png".format(i + 1)),
120 | (output_files[i][0] * 255).byte().cpu().numpy().transpose(1, 2, 0)[:height, :width])
121 |
--------------------------------------------------------------------------------
/src/video_extract.py:
--------------------------------------------------------------------------------
1 | """
2 | Module for handling video frame extraction (aka: "step 1")
3 | """
4 | # Built-in modules
5 | import pathlib
6 | # External modules
7 | from PIL import Image
8 |
9 |
10 | def png_remove_alpha_channel(file_path):
11 | png = Image.open(file_path).convert("RGBA")
12 | background = Image.new("RGBA", png.size, (255, 255, 255)) # White background created
13 | alpha_composite = Image.alpha_composite(background, png) # Transparent png put on background
14 | alpha_composite.convert("RGB").save(file_path)
15 |
16 |
17 | def png_directory_remove_alpha_channel(directory_path):
18 | """Converts all .png files in a folder to be alpha-less"""
19 | for i in pathlib.Path(directory_path).glob('**/*.png'):
20 | png_remove_alpha_channel(i.absolute())
21 |
--------------------------------------------------------------------------------