Add files via upload

add code
This commit is contained in:
YangJX
2025-01-06 14:25:42 +08:00
committed by GitHub
parent a3165cdc41
commit 0e210d298b
67 changed files with 10910 additions and 203 deletions
+674 -201
View File
@@ -1,201 +1,674 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+72 -2
View File
@@ -1,2 +1,72 @@
# ComfyUI_RopeWrapper
face swap Rope, wrap for ComfyUI
![image](https://github.com/Hillobar/Rope/assets/63615199/40f7397f-713c-4813-ac86-bab36f6bd5ba)
Rope implements the insightface inswapper_128 model with a helpful GUI.
### [Discord](https://discord.gg/EcdVAFJzqp)
### [Donate](https://www.paypal.com/donate/?hosted_button_id=Y5SB9LSXFGRF2)
### [Wiki with install instructions and usage](https://github.com/Hillobar/Rope/wiki)
### [Demo Video (Rope-Ruby)](https://www.youtube.com/watch?v=4Y4U0TZ8cWY)
### ${{\color{Goldenrod}{\textsf{Last Updated 2024-05-27}}}}$ ###
### ${{\color{Goldenrod}{\textsf{Welcome to Rope-Pearl!}}}}$ ###
![Screenshot 2024-02-10 104718](https://github.com/Hillobar/Rope/assets/63615199/4b2ee574-c91e-4db2-ad66-5b775a049a6b)
### Updates for Rope-Pearl-00: ###
### To update from Opal-03a, just need to replace the rope folder.
* (feature) Selectable model swapping output resolution - 128, 256, 512
* (feature) Better selection of input images (ctrl and shift modifiers work mostly like windows behavior)
* (feature) Toggle between mean and median merging withou having to save to compare
* (feature) Added back keyboard controls (q, w, a, s, d, space)
* (feature) Gamma slider
*
![image](https://github.com/Hillobar/Rope/assets/63615199/9d89fded-addb-46fe-b2d7-bfe6f1a88188)
### Performance: ###
Machine: 3090Ti (24GB), i5-13600K
<img src="https://github.com/Hillobar/Rope/assets/63615199/3e3505db-bc76-48df-b8ac-1e7e86c8d751" width="200">
File: benchmark/target-1080p.mp4, 2048x1080, 269 frames, 25 fps, 10s
Rendering time in seconds (5 threads):
| Option | Crystal | Sapphire | Ruby | Opal | Pearl |
| --- | --- | --- | --- | --- | --- |
| Only Swap (128) | 7.3 | 7.5 | 4.4 | 4.3 | 4.4 |
| Swap (256) | --- | --- | --- | --- | 8.6 |
| Swap (512) | --- | --- | --- | --- | 28.6 |
| Swap+GFPGAN | 10.7 | 11.0 | 9.0 | 9.8 | 9.3 |
| Swap+Codeformer | 12.4 | 13.5 | 11.1 | 11.1 | 11.3 |
| Swap+one word CLIP | 10.4 | 11.2 | 9.1 | 9.3 | 9.3 |
| Swap+Occluder | 7.8 | 7.8 | 4.4 | 4.7 | 4.7 |
| Swap+MouthParser | 13.9 | 12.1 | 5.0 | 4.9 | 5.1 |
### Disclaimer: ###
Rope is a personal project that I'm making available to the community as a thank you for all of the contributors ahead of me.
I've copied the disclaimer from [Swap-Mukham](https://github.com/harisreedhar/Swap-Mukham) here since it is well-written and applies 100% to this repo.
I would like to emphasize that our swapping software is intended for responsible and ethical use only. I must stress that users are solely responsible for their actions when using our software.
Intended Usage: This software is designed to assist users in creating realistic and entertaining content, such as movies, visual effects, virtual reality experiences, and other creative applications. I encourage users to explore these possibilities within the boundaries of legality, ethical considerations, and respect for others' privacy.
Ethical Guidelines: Users are expected to adhere to a set of ethical guidelines when using our software. These guidelines include, but are not limited to:
Not creating or sharing content that could harm, defame, or harass individuals. Obtaining proper consent and permissions from individuals featured in the content before using their likeness. Avoiding the use of this technology for deceptive purposes, including misinformation or malicious intent. Respecting and abiding by applicable laws, regulations, and copyright restrictions.
Privacy and Consent: Users are responsible for ensuring that they have the necessary permissions and consents from individuals whose likeness they intend to use in their creations. We strongly discourage the creation of content without explicit consent, particularly if it involves non-consensual or private content. It is essential to respect the privacy and dignity of all individuals involved.
Legal Considerations: Users must understand and comply with all relevant local, regional, and international laws pertaining to this technology. This includes laws related to privacy, defamation, intellectual property rights, and other relevant legislation. Users should consult legal professionals if they have any doubts regarding the legal implications of their creations.
Liability and Responsibility: We, as the creators and providers of the deep fake software, cannot be held responsible for the actions or consequences resulting from the usage of our software. Users assume full liability and responsibility for any misuse, unintended effects, or abusive behavior associated with the content they create.
By using this software, users acknowledge that they have read, understood, and agreed to abide by the above guidelines and disclaimers. We strongly encourage users to approach this technology with caution, integrity, and respect for the well-being and rights of others.
Remember, technology should be used to empower and inspire, not to harm or deceive. Let's strive for ethical and responsible use of deep fake technology for the betterment of society.
+3
View File
@@ -0,0 +1,3 @@
call venv\Scripts\activate.bat
python Rope.py
pause
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env python3
from rope import Coordinator
if __name__ == "__main__":
Coordinator.run()
+958
View File
@@ -0,0 +1,958 @@
from .rope import Models as Models
from .rope import VideoManager as VM
import json
import torch
import numpy as np
import os
import folder_paths
from comfy.utils import ProgressBar
import pickle
import subprocess
#from .videoCombine import RopeVideoCombine
from .videoCombine import ffmpeg_process
import torchaudio
from .utils import ffmpeg_path
import mimetypes
import random
from tqdm import tqdm
#####WEB_DIRECTORY = "./web"
def combine_audio_video(audio_path, video_path, output_path):
command = [
ffmpeg_path,
'-i', video_path,
'-i', audio_path,
'-c:v', 'copy',
'-c:a', 'aac',
'-shortest',
output_path
]
subprocess.run(command, check=True)
return output_path
def get_mime_type(file_path):
# 获取文件的 MIME 类型
mime_type, _ = mimetypes.guess_type(file_path)
# 如果无法猜测类型,返回默认类型
if mime_type is None:
return 'application/octet-stream'
return mime_type
class RopeWrapper_DetectNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"models": ("ROPE_MODEL", ),
#"vm": ("ROPE_VM", ),
"input_image": ("IMAGE", ),
#"source_face": ("IMAGE", ),
"SimilarityThreshold":("FLOAT", {"default": 70, "min": 0.0, "max": 100, "step": 1}),
"detection_threshold":("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
}
}
RETURN_TYPES = ("INT","DETECTRESULT","IMAGE",)
RETURN_NAMES = ("humanCount","DETECTRESULT","foundFaces",)
FUNCTION = "run"
CATEGORY = "RopeWrapper"
def findCosineDistance(self, vector1, vector2):
cos_dist = 1.0 - np.dot(vector1, vector2)/(np.linalg.norm(vector1)*np.linalg.norm(vector2)) # 2..0
return 100.0-cos_dist*50.0
def getEmbedding(self, img, models):
pad_scale = 0.2
padded_width = int(img.size()[1]*(1.+pad_scale))
padded_height = int(img.size()[0]*(1.+pad_scale))
padding = torch.zeros((padded_height, padded_width, 3), dtype=torch.uint8, device='cuda:0')
width_start = int(img.size()[1]*pad_scale/2)
width_end = width_start+int(img.size()[1])
height_start = int(img.size()[0]*pad_scale/2)
height_end = height_start+int(img.size()[0])
padding[height_start:height_end, width_start:width_end, :] = img
img = padding
img = img.permute(2,0,1)
try:
kpss = models.run_detect(img, max_num=1)[0] # Just one face here
except IndexError:
return None
else:
face_emb, cropped = models.run_recognize(img, kpss)
return face_emb, img ,cropped
def run(self, models,input_image,SimilarityThreshold,detection_threshold):
# #print("Comfy UI Image shape:", input_image.shape)
# try:
# load_file = open("custom_nodes/Rope/saved_parameters.json", "r")
# except FileNotFoundError:
# print('No save file created yet!')
# else:
# # Load the file and save it to parameters
# vm.parameters = json.load(load_file)
# load_file.close()
# output_Padding=[]
# output_cropped=[]
# source_face_emb=None
# source_faces=[]
# for face_img in source_face:
# tempImg = torch.round(face_img * 255)
# tempImg = tempImg.to(torch.uint8).to('cuda')
# source_face_emb, PaddingImg,_ = self.getEmbedding(tempImg, models)
# if source_face_emb is not None:
# source_faces.append(source_face_emb)
# print('source_face_emb got!!!')
# PaddingImg = PaddingImg.permute(1,2,0)
# PaddingImg = PaddingImg.to(torch.float32)/255
# output_Padding.append(PaddingImg)
# crop = cv2.cvtColor(croppedImg.cpu().numpy(), cv2.COLOR_BGR2RGB)
# crop = cv2.resize(crop, (85, 85))
# crop = crop.permute(1,2,0)
# crop = crop.to(torch.float32)/255
# output_cropped.append(crop)
videoSwapInfo=[]
currentFrame=0
found_faces = []
#output = []
pbar = ProgressBar(len(input_image))
for img in input_image:
img = img.permute(2,0,1)
img = torch.round(img * 255)
img = img.to(torch.uint8).to('cuda')
kpss = models.run_detect(img, 'Retinaface',max_num=50,score=detection_threshold)
kps_emb_list = []
for face_kps in kpss:
face_emb,cropped = models.run_recognize( img, face_kps)
kps_emb_list.append([face_kps, face_emb,cropped])
# print(f'frame: {currentFrame}, faces in this frame: {len(kpss)}, length of found_faces: {len(found_faces)}')
FrameSwapInfo=[]
faceIndexInThisFrame=0
if kps_emb_list:
for fface in kps_emb_list:
found = False
for found_face in found_faces:
sim = self.findCosineDistance(fface[1], found_face["Embedding"])
# print((f'sim: {sim}'))
if sim > SimilarityThreshold:
found = True
FrameSwapInfo.append([found_face["index"], fface[0]])
# print(f"swap face, index: {found_face['index']}, faceIndexInThisFrame:{faceIndexInThisFrame}")
break
if not found:
index=len(found_faces)
found_faces.append({"Face": fface[0], "Embedding": fface[1],"index":index,"Cropped":fface[2]})
FrameSwapInfo.append([index,fface[0]])
# print(f"add new face, index: {index}, faceIndexInThisFrame:{faceIndexInThisFrame}")
faceIndexInThisFrame+=1
videoSwapInfo.append(FrameSwapInfo )
# for swapInfo in FrameSwapInfo:
# if swapInfo[0] < len(source_faces):
# source_emb = source_faces[swapInfo[0]]
# ## temp ## img = vm.swap_core(img, swapInfo[1], source_emb, vm.parameters, vm.control)
# print(f'use source[{swapInfo[0]}] swap in frame {currentFrame}')
#img = vm.swap_core(img, kps_emb_list[0][0], source_face_emb, vm.parameters, vm.control)
#print("shape after swap_core:",img.shape)
##shape after swap_core: torch.Size([3, 1706, 1279])
# img = img.permute(1,2,0)
#print("shape after permute:",img.shape)
##shape after permute: torch.Size([1706, 1279, 3])
# img = img.to(torch.uint8)
# img = img.to(torch.float32)/255
# output.append(img)
currentFrame+=1
pbar.update(1)
outputFoundFaces=[]
for face in found_faces:
#print(f'face index: {face["index"]}, face: {face["Face"]}')
faceImg = face["Cropped"].to(torch.float32)/255
#print(f'faceImg shape: {faceImg.shape}')
outputFoundFaces.append(faceImg)
#tensor_stacked = torch.stack(output)
#print("tensor_stacked shape:",tensor_stacked.shape)
##tensor_stacked shape: torch.Size([1, 1706, 1279, 3])
currentHumanCount = len(found_faces)
detectResult={"faceCount":currentHumanCount,"swapInfo":videoSwapInfo}
# with open('detectResult.pkl', 'wb') as f:
# pickle.dump(detectResult, f)
#print('found_faces count:',currentHumanCount)
return ( currentHumanCount, detectResult, torch.stack(outputFoundFaces), )
#torch.stack(output_cropped),torch.stack(output_Padding),)
class RopeWrapper_LoadModels:
@classmethod
def INPUT_TYPES(s):
return {
"hidden": {
"unique_id": "UNIQUE_ID"
},
}
RETURN_TYPES = ("ROPE_MODEL","ROPE_VM")
RETURN_NAMES = ("ROPE_MODEL","ROPE_VM")
FUNCTION = "run"
CATEGORY = "RopeWrapper"
model=None
vm=None
def run(self, unique_id):
if self.model is None:
self.model = Models.Models()
self.model.setModelPath(os.path.dirname(os.path.realpath(__file__))+"/")
self.vm = VM.VideoManager(self.model)
return ( self.model, self.vm )
class RopeWrapper_SwapNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"models": ("ROPE_MODEL", ),
"vm": ("ROPE_VM", ),
"input_image": ("IMAGE", ),
"source_face": ("IMAGE", ),
"detectResult": ("DETECTRESULT", ),
"combineVideo":("BOOLEAN", {"default": False}),
"frame_rate":("FLOAT", {"default": 30.0}),
"filenamePrefix": ("STRING", {"default": 'Rope_', "multiline": False}),
"saveOutput":("BOOLEAN", {"default": False}),
"outputFrameIndex":("INT", {"default": 0}),
},
"optional": {
"audio": ("AUDIO",),
"ROPE_Options":("ROPE_OPTION",),
"source_target_matching": ("STRING", {"default": ' ', "multiline": True}),
},
}
RETURN_TYPES = ("IMAGE","STRING","STRING",)
RETURN_NAMES = ("SwappedImage","fileName","fileNameAndPath",)
FUNCTION = "run"
OUTPUT_NODE = True
CATEGORY = "RopeWrapper"
def getEmbedding(self, img, models):
pad_scale = 0.2
padded_width = int(img.size()[1]*(1.+pad_scale))
padded_height = int(img.size()[0]*(1.+pad_scale))
padding = torch.zeros((padded_height, padded_width, 3), dtype=torch.uint8, device='cuda:0')
width_start = int(img.size()[1]*pad_scale/2)
width_end = width_start+int(img.size()[1])
height_start = int(img.size()[0]*pad_scale/2)
height_end = height_start+int(img.size()[0])
padding[height_start:height_end, width_start:width_end, :] = img
img = padding
img = img.permute(2,0,1)
try:
kpss = models.run_detect(img, max_num=1)[0] # Just one face here
except IndexError:
return None,None,None
else:
face_emb, cropped = models.run_recognize(img, kpss)
return face_emb, img ,cropped
def parseString(self,str):
try:
if str is None:
return None
else:
if str == ' ':
return None
else:
lines = str.split(';')
return [ [int(x) for x in line.split(',')] for line in lines]
except:
return None
def run(self, models,vm,input_image,source_face,detectResult,combineVideo,frame_rate,filenamePrefix,saveOutput,outputFrameIndex,audio=None,ROPE_Options=None,source_target_matching=None):
#tempFile =os.path.join( folder_paths.output_directory, "temp.mp4")
if saveOutput:
output_dir = folder_paths.get_output_directory()
else:
output_dir = folder_paths.get_temp_directory()
(
full_output_folder,
filename,
_,
subfolder,
_,
) = folder_paths.get_save_image_path(filenamePrefix, output_dir)
filename = filename + ''.join(random.choice("abcdefghijklmnopqrstupvxyz0123456789") for x in range(5))
tempFile = os.path.join(full_output_folder, filename)
if ROPE_Options is None:
try:
load_file = open("custom_nodes/Rope/saved_parameters.json", "r")
except FileNotFoundError:
print('No save file created yet!')
else:
# Load the file and save it to parameters
vm.parameters = json.load(load_file)
load_file.close()
else:
vm.parameters=ROPE_Options
#print('vm.parameters:',vm.parameters)
videoSwapInfo = detectResult["swapInfo"]
targetFaceCount=detectResult["faceCount"]
if(source_target_matching is not None):
source2target=self.parseString(source_target_matching)
else:
source2target=None
#print('source_target_matching is NONE')
if source2target is None:
#print('source2target is NONE')
source2target=[]
for i in range(len(source_face)):
source2target.append([i])
#print('source2target:',source2target)
source_face_emb=None
source_faces=[]
print("begin get embedding from source images")
sourceFaceID=0
for face_img in source_face:
tempImg = torch.round(face_img * 255)
tempImg = tempImg.to(torch.uint8).to('cuda')
source_face_emb, _,_ = self.getEmbedding(tempImg, models)
if source_face_emb is not None:
source_faces.append(source_face_emb)
print('source_face_emb got:', sourceFaceID)
else:
source_faces.append(None)
print('source_face_emb got None', sourceFaceID)
sourceFaceID+=1
target2source=[]
for i in range(targetFaceCount):
found=False
for j in range(len(source2target)):
for index in source2target[j]:
if index==i:
target2source.append(j)
found=True
break
if not found:
target2source.append(-1)
#width = input_image.shape[2]
#height = input_image.shape[1]
num_frames = len(input_image)
pbar = ProgressBar(num_frames)
first_image = input_image[0]
#input_image = iter(input_image)
NeedPad=False
if combineVideo:
if (first_image.shape[1] % 8) or (first_image.shape[0] % 8):
#output frames must be padded
to_pad = (-first_image.shape[1] % 8,
-first_image.shape[0] % 8)
padding = (to_pad[0]//2, to_pad[0] - to_pad[0]//2,
to_pad[1]//2, to_pad[1] - to_pad[1]//2)
padfunc = torch.nn.ReplicationPad2d(padding)
def pad(image):
#image = image.permute((2,0,1))#HWC to CHW
padded = padfunc(image.to(dtype=torch.float32))
return padded
#return padded.permute((1,2,0))
#images = map(pad, images)
new_dims = (-first_image.shape[1] % 8 + first_image.shape[1],
-first_image.shape[0] % 8 + first_image.shape[0])
dimensions = f"{new_dims[0]}x{new_dims[1]}"
print("Output images were not of valid resolution and have had padding applied:",dimensions)
NeedPad=True
else:
dimensions = f"{first_image.shape[1]}x{first_image.shape[0]}"
args=[ffmpeg_path, '-v', 'error', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', dimensions, '-r', str(frame_rate), '-i', '-', '-n', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '19']
video_format= {'main_pass': ['-n', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '19'], 'audio_pass': ['-c:a', 'aac'], 'save_metadata': 'False', 'extension': 'mp4'}
env=os.environ.copy()
sp = ffmpeg_process(args,video_format,None,tempFile+".mp4",env)
sp.send(None)
currentFrame=0
output = []
for img in tqdm(input_image,"Swapping faces"):
#for img in input_image:
img = img.permute(2,0,1)
img = torch.round(img * 255)
img = img.to(torch.uint8).to('cuda')
#print("procedding frame:",currentFrame)
#print("shape before swap_core:",img.shape)
if currentFrame < len(videoSwapInfo):
FrameSwapInfo = videoSwapInfo[currentFrame]
for swapInfo in FrameSwapInfo:
targetIndex = swapInfo[0]
if target2source[targetIndex] != -1 and target2source[targetIndex] < len(source_faces):
source_emb = source_faces[target2source[targetIndex]]
if source_emb is not None:
img = vm.swap_core(img, swapInfo[1], source_emb, vm.parameters, vm.control)
#print("shape after swap_core:",img.shape)
if combineVideo:
if currentFrame == outputFrameIndex:
outFrame = img.permute(1,2,0)
outFrame = outFrame.to(torch.float32)/255
outFrame=outFrame.cpu()
output.append(outFrame)
if NeedPad:
img=pad(img)
img = img.permute(1,2,0)
img = img.to(torch.uint8)
img=img.cpu().numpy()
sp.send(np.ascontiguousarray(img))
else:
img = img.permute(1,2,0)
img = img.to(torch.float32)/255
img=img.cpu()
#print("to png, img dim:",img.shape)
output.append(img)
currentFrame+=1
pbar.update(1)
if combineVideo:
try:
sp.send(None) #第一次send None是告诉sp,图片已经全部输入完成
sp.send(None) #第二次send None是结束进程。直到报StopIteration为止
except StopIteration:
pass
##生成视频后,用ffmpeg转成h264的例子
##https://discuss.streamlit.io/t/processing-video-with-opencv-and-write-it-to-disk-to-display-in-st-video/28891/2
output_file_full_path=tempFile+".mp4"
if audio is not None :
## 合并音频的代码,来自 comfyui-mix-labnodes
output_dir = folder_paths.get_output_directory()
# 判断是否是 Tensor 类型
is_tensor = not isinstance(audio, dict)
# print('#判断是否是 Tensor 类型',is_tensor,audio)
if not is_tensor and 'waveform' in audio and 'sample_rate' in audio:
# {'waveform': tensor([], size=(1, 1, 0)), 'sample_rate': 44100}
is_tensor=True
if "audio_path" in audio:
is_tensor=False
audio_file_path=audio["audio_path"]
if is_tensor:
filename_prefix="audio_tmp"
audio_full_output_folder, audio_filename, counter, _, filename_prefix = folder_paths.get_save_image_path(
filename_prefix,
folder_paths.get_temp_directory())
filename_with_batch_num = audio_filename.replace("%batch_num%", str(1))
audioFileName = f"{filename_with_batch_num}_{counter:05}_.wav"
audio_file_path=os.path.join(audio_full_output_folder, audioFileName)
torchaudio.save(audio_file_path, audio['waveform'].squeeze(0), audio["sample_rate"])
output_file_with_audio_path = tempFile+"audio.mp4"
filename=filename+"audio.mp4"
print("audio file :", audio_file_path)
print("video file :", output_file_full_path)
print("output file with audio :", output_file_with_audio_path)
combine_audio_video(audio_file_path,output_file_full_path,output_file_with_audio_path)
# # # # # # # Create audio file if input was provided
# # # # # # output_file_with_audio_path = tempFile+"audio.mp4"
# # # # # # filename=filename+"audio.mp4"
# # # # # # video_format["audio_pass"] = ["-c:a", "aac"]
# # # # # # # # FFmpeg command with audio re-encoding
# # # # # # # #TODO: expose audio quality options if format widgets makes it in
# # # # # # # #Reconsider forcing apad/shortest
# # # # # # # min_audio_dur = currentFrame / frame_rate + 1
# # # # # # # mux_args = [ffmpeg_path, "-v", "error", "-n", "-i", tempFile+".mp4",
# # # # # # # "-i", "-", "-c:v", "copy"] \
# # # # # # # + video_format["audio_pass"] \
# # # # # # # + ["-af", "apad=whole_dur="+str(min_audio_dur),
# # # # # # # "-shortest", output_file_with_audio_path]
# # # # # # # try:
# # # # # # # res = subprocess.run(mux_args, input=audio(), env=env,
# # # # # # # capture_output=True, check=True)
# # # # # # # except subprocess.CalledProcessError as e:
# # # # # # # raise Exception("An error occured in the ffmpeg subprocess:\n" \
# # # # # # # + e.stderr.decode("utf-8"))
# # # # # # # if res.stderr:
# # # # # # # print(res.stderr.decode("utf-8"), end="", file=sys.stderr)
output_file_full_path = output_file_with_audio_path
else:
filename=filename+".mp4"
if saveOutput:
previewOutputType="output"
else:
previewOutputType="temp"
previews = [
{
"filename": filename,
"subfolder": subfolder,
"type": previewOutputType,
"format": get_mime_type(filename),
"frame_rate": frame_rate,
}
]
#[{'filename': 'AdvancedLivePortrait_00001.mp4', 'subfolder': '', 'type': 'temp', 'format': 'video/h264-mp4', 'frame_rate': 30.0}]
print("previews:",previews)
return {"ui":{"gifs": previews}, "result": (torch.stack(output), filename,output_file_full_path,)}
else:
return (torch.stack(output), "","",)
class RopeWrapper_FaceRestore:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"models": ("ROPE_MODEL", ),
"vm": ("ROPE_VM", ),
"input_image": ("IMAGE", ),
"detection_threshold":("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
"combineVideo":("BOOLEAN", {"default": False}),
"frame_rate":("FLOAT", {"default": 30.0}),
"filenamePrefix": ("STRING", {"default": 'RopeFaceRestore', "multiline": False}),
"saveOutput":("BOOLEAN", {"default": False}),
},
"optional": {
"audio": ("AUDIO",),
"ROPE_Options":("ROPE_OPTION",),
},
}
RETURN_TYPES = ("IMAGE","STRING","STRING",)
RETURN_NAMES = ("SwappedImage","fileName","fileNameAndPath",)
FUNCTION = "run"
OUTPUT_NODE = True
CATEGORY = "RopeWrapper"
def parseString(self,str):
try:
if str is None:
return None
else:
if str == ' ':
return None
else:
lines = str.split(';')
return [ [int(x) for x in line.split(',')] for line in lines]
except:
return None
def run(self, models,vm,input_image,detection_threshold,combineVideo,frame_rate,filenamePrefix,saveOutput,audio=None,ROPE_Options=None):
#tempFile =os.path.join( folder_paths.output_directory, "temp.mp4")
if saveOutput:
output_dir = folder_paths.get_output_directory()
else:
output_dir = folder_paths.get_temp_directory()
(
full_output_folder,
filename,
_,
subfolder,
_,
) = folder_paths.get_save_image_path(filenamePrefix, output_dir)
filename = filename + ''.join(random.choice("abcdefghijklmnopqrstupvxyz0123456789") for x in range(5))
tempFile = os.path.join(full_output_folder, filename)
if ROPE_Options is None:
try:
load_file = open("custom_nodes/Rope/saved_parameters.json", "r")
except FileNotFoundError:
print('No save file created yet!')
else:
# Load the file and save it to parameters
vm.parameters = json.load(load_file)
load_file.close()
else:
vm.parameters=ROPE_Options
vm.parameters['RestorerSwitch'] = True
num_frames = len(input_image)
pbar = ProgressBar(num_frames)
first_image = input_image[0]
input_image = iter(input_image)
NeedPad=False
if combineVideo:
if (first_image.shape[1] % 8) or (first_image.shape[0] % 8):
#output frames must be padded
to_pad = (-first_image.shape[1] % 8,
-first_image.shape[0] % 8)
padding = (to_pad[0]//2, to_pad[0] - to_pad[0]//2,
to_pad[1]//2, to_pad[1] - to_pad[1]//2)
padfunc = torch.nn.ReplicationPad2d(padding)
def pad(image):
#image = image.permute((2,0,1))#HWC to CHW
padded = padfunc(image.to(dtype=torch.float32))
return padded
#return padded.permute((1,2,0))
#images = map(pad, images)
new_dims = (-first_image.shape[1] % 8 + first_image.shape[1],
-first_image.shape[0] % 8 + first_image.shape[0])
dimensions = f"{new_dims[0]}x{new_dims[1]}"
print("Output images were not of valid resolution and have had padding applied:",dimensions)
NeedPad=True
else:
dimensions = f"{first_image.shape[1]}x{first_image.shape[0]}"
args=[ffmpeg_path, '-v', 'error', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', dimensions, '-r', str(frame_rate), '-i', '-', '-n', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '19']
video_format= {'main_pass': ['-n', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '19'], 'audio_pass': ['-c:a', 'aac'], 'save_metadata': 'False', 'extension': 'mp4'}
env=os.environ.copy()
sp = ffmpeg_process(args,video_format,None,tempFile+".mp4",env)
sp.send(None)
currentFrame=0
output = []
for img in tqdm( input_image, desc="faceRestore", total=num_frames):
#for img in input_image:
img = img.permute(2,0,1)
img = torch.round(img * 255)
img = img.to(torch.uint8).to('cuda')
#print("procedding frame:",currentFrame)
kpss = models.run_detect(img, 'Retinaface',max_num=50,score=detection_threshold)
for kps in kpss:
img = vm.core_withoutSwap(img, kps, vm.parameters, vm.control)
if combineVideo:
if NeedPad:
img=pad(img)
img = img.permute(1,2,0)
img = img.to(torch.uint8)
img=img.cpu().numpy()
sp.send(np.ascontiguousarray(img))
else:
img = img.permute(1,2,0)
img = img.to(torch.float32)/255
img=img.cpu()
output.append(img)
currentFrame+=1
pbar.update(1)
if combineVideo:
try:
print("exporting mp4...")
sp.send(None) #第一次send None是告诉sp,图片已经全部输入完成
sp.send(None) #第二次send None是结束进程。直到报StopIteration为止
except StopIteration:
pass
##生成视频后,用ffmpeg转成h264的例子
##https://discuss.streamlit.io/t/processing-video-with-opencv-and-write-it-to-disk-to-display-in-st-video/28891/2
output_file_full_path=tempFile+".mp4"
if audio is not None :
print("combine audio...")
## 合并音频的代码,来自 comfyui-mix-labnodes
output_dir = folder_paths.get_output_directory()
# 判断是否是 Tensor 类型
is_tensor = not isinstance(audio, dict)
# print('#判断是否是 Tensor 类型',is_tensor,audio)
if not is_tensor and 'waveform' in audio and 'sample_rate' in audio:
# {'waveform': tensor([], size=(1, 1, 0)), 'sample_rate': 44100}
is_tensor=True
if "audio_path" in audio:
is_tensor=False
audio_file_path=audio["audio_path"]
if is_tensor:
filename_prefix="audio_tmp"
audio_full_output_folder, audio_filename, counter, _, filename_prefix = folder_paths.get_save_image_path(
filename_prefix,
folder_paths.get_temp_directory())
filename_with_batch_num = audio_filename.replace("%batch_num%", str(1))
audioFileName = f"{filename_with_batch_num}_{counter:05}_.wav"
audio_file_path=os.path.join(audio_full_output_folder, audioFileName)
torchaudio.save(audio_file_path, audio['waveform'].squeeze(0), audio["sample_rate"])
output_file_with_audio_path = tempFile+"audio.mp4"
filename=filename+"audio.mp4"
#print("audio file :", audio_file_path)
#print("video file :", output_file_full_path)
#print("output file with audio :", output_file_with_audio_path)
combine_audio_video(audio_file_path,output_file_full_path,output_file_with_audio_path)
output_file_full_path = output_file_with_audio_path
else:
filename=filename+".mp4"
if saveOutput:
previewOutputType="output"
else:
previewOutputType="temp"
previews = [
{
"filename": filename,
"subfolder": subfolder,
"type": "output" if saveOutput else "temp",
"format": "video/h264-mp4",
"frame_rate": frame_rate,
}
]
#[{'filename': 'AdvancedLivePortrait_00001.mp4', 'subfolder': '', 'type': 'temp', 'format': 'video/h264-mp4', 'frame_rate': 30.0}]
print("previews:",previews)
return {"ui":{"video": previews}, "result": (None, filename,output_file_full_path,)}
else:
return (torch.stack(output), "","",)
class RopeWrapper_OptionNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"RestorerSwitch": ("BOOLEAN",{"default":False} ),
"RestorerTypeTextSel": (['CF','GFPGAN', 'GPEN256', 'GPEN512'],),
"RestorerDetTypeTextSel": (['Blend','Original','Reference'],),
"RestorerSlider":("INT", {"default": 100, "min": 0, "max": 100, "step": 1}),
#ThresholdSlider
"OrientSwitch": ("BOOLEAN",{"default":False} ),
"OrientSlider":("INT", {"default": 180, "min": 0, "max": 270, "step": 90}),
"StrengthSwitch": ("BOOLEAN",{"default":False} ),
"StrengthSlider":("INT", {"default": 200, "min": 0, "max": 500, "step": 1}),
"BorderTopSlider":("INT", {"default": 10, "min": 0, "max": 64, "step": 1}),
"BorderSidesSlider":("INT", {"default": 10, "min": 0, "max": 64, "step": 1}),
"BorderBottomSlider":("INT", {"default": 10, "min": 0, "max": 64, "step": 1}),
"BorderBlurSlider":("INT", {"default": 10, "min": 0, "max": 64, "step": 1}),
"DiffSwitch": ("BOOLEAN",{"default":False} ),
"DiffSlider":("INT", {"default": 4, "min": 0.0, "max": 100, "step": 1}),
"OccluderSwitch": ("BOOLEAN",{"default":False} ),
"OccluderSlider":("INT", {"default": 0, "min": -100, "max": 100, "step": 1}),
"FaceParserSwitch": ("BOOLEAN",{"default":False} ),
"FaceParserSlider":("INT", {"default": 0, "min": -50, "max": 50, "step": 1}),
"MouthParserSlider":("INT", {"default": 0, "min": -50, "max": 50, "step": 1}),
"CLIPSwitch": ("BOOLEAN",{"default":False} ),
"CLIPTextEntry": ("STRING", {"default": " "}),
"CLIPSlider":("INT", {"default": 50, "min": 0, "max": 100, "step": 1}),
"BlendSlider":("INT", {"default": 5, "min": 0, "max": 100, "step": 1}),
"ColorSwitch": ("BOOLEAN",{"default":False} ),
"ColorRedSlider":("INT", {"default": 0, "min": -100, "max": 100, "step": 1}),
"ColorGreenSlider":("INT", {"default": 0, "min": -100, "max": 100, "step": 1}),
"ColorBlueSlider":("INT", {"default": 0, "min": -100, "max": 100, "step": 1}),
"ColorGammaSlider":("FLOAT", {"default": 0, "min": 0.0, "max": 2.0, "step": 0.02}),
"FaceAdjSwitch": ("BOOLEAN",{"default":False} ),
"KPSXSlider":("INT", {"default": 0, "min": -100, "max": 100, "step": 1}),
"KPSYSlider":("INT", {"default": 0, "min": -100, "max": 100, "step": 1}),
"KPSScaleSlider":("INT", {"default": 0, "min": -100, "max": 100, "step": 1}),
"SwapperTypeTextSel": (['128','256', '512'],),
},
}
RETURN_TYPES = ("ROPE_OPTION",)
FUNCTION = "run"
CATEGORY = "RopeWrapper"
def run(self, RestorerSwitch ,RestorerTypeTextSel ,RestorerDetTypeTextSel ,RestorerSlider ,OrientSwitch ,OrientSlider ,StrengthSwitch ,StrengthSlider ,BorderTopSlider ,BorderSidesSlider ,BorderBottomSlider ,BorderBlurSlider ,DiffSwitch ,DiffSlider ,OccluderSwitch ,OccluderSlider ,FaceParserSwitch ,FaceParserSlider ,MouthParserSlider ,CLIPSwitch ,CLIPTextEntry ,CLIPSlider ,BlendSlider ,ColorSwitch ,ColorRedSlider ,ColorGreenSlider ,ColorBlueSlider ,ColorGammaSlider ,FaceAdjSwitch ,KPSXSlider ,KPSYSlider ,KPSScaleSlider ,SwapperTypeTextSel):
option={
"RestorerSwitch": False,
"RestorerTypeTextSel": "CF",
"RestorerDetTypeTextSel": "Blend",
"RestorerSlider": 100,
"ThresholdSlider": 50,
"OrientSwitch": False,
"OrientSlider": 180,
"StrengthSwitch": False,
"StrengthSlider": 200,
"BorderTopSlider": 10,
"BorderSidesSlider": 10,
"BorderBottomSlider": 10,
"BorderBlurSlider": 10,
"DiffSwitch": False,
"DiffSlider": 4,
"OccluderSwitch": False,
"OccluderSlider": 0,
"FaceParserSwitch": False,
"FaceParserSlider": 0,
"MouthParserSlider": 0,
"CLIPSwitch": False,
"CLIPTextEntry": "",
"CLIPSlider": 50,
"BlendSlider": 5,
"ColorSwitch": False,
"ColorRedSlider": 0,
"ColorGreenSlider": -4,
"ColorBlueSlider": 0,
"ColorGammaSlider": 1,
"FaceAdjSwitch": False,
"KPSXSlider": 0,
"KPSYSlider": 0,
"KPSScaleSlider": 0,
"FaceScaleSlider": 0,
"ThreadsSlider": 5,
"DetectTypeTextSel": "Retinaface",
"DetectScoreSlider": 50,
"RecordTypeTextSel": "FFMPEG",
"VideoQualSlider": 18,
"SwapperTypeTextSel": "128"
}
option["RestorerSwitch"]=RestorerSwitch
option["RestorerTypeTextSel"]=RestorerTypeTextSel
option["RestorerDetTypeTextSel"]=RestorerDetTypeTextSel
option["RestorerSlider"]=RestorerSlider
option["OrientSwitch"]=OrientSwitch
option["OrientSlider"]=OrientSlider
option["StrengthSwitch"]=StrengthSwitch
option["StrengthSlider"]=StrengthSlider
option["BorderTopSlider"]=BorderTopSlider
option["BorderSidesSlider"]=BorderSidesSlider
option["BorderBottomSlider"]=BorderBottomSlider
option["BorderBlurSlider"]=BorderBlurSlider
option["DiffSwitch"]=DiffSwitch
option["DiffSlider"]=DiffSlider
option["OccluderSwitch"]=OccluderSwitch
option["OccluderSlider"]=OccluderSlider
option["FaceParserSwitch"]=FaceParserSwitch
option["FaceParserSlider"]=FaceParserSlider
option["MouthParserSlider"]=MouthParserSlider
option["CLIPSwitch"]=CLIPSwitch
option["CLIPTextEntry"]=CLIPTextEntry
option["CLIPSlider"]=CLIPSlider
option["BlendSlider"]=BlendSlider
option["ColorSwitch"]=ColorSwitch
option["ColorRedSlider"]=ColorRedSlider
option["ColorGreenSlider"]=ColorGreenSlider
option["ColorBlueSlider"]=ColorBlueSlider
option["ColorGammaSlider"]=ColorGammaSlider
option["FaceAdjSwitch"]=FaceAdjSwitch
option["KPSXSlider"]=KPSXSlider
option["KPSYSlider"]=KPSYSlider
option["KPSScaleSlider"]=KPSScaleSlider
option["SwapperTypeTextSel"]=SwapperTypeTextSel
return (option,)
class RopeWrapper_SaveSwapInfo:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"fileName": ("STRING", {"default": 'TEMP_PKL', "multiline": False}),
"detectResult": ("DETECTRESULT", ),
},
}
RETURN_TYPES = ()
FUNCTION = "run"
OUTPUT_NODE = True
CATEGORY = "RopeWrapper"
def run(self, fileName, detectResult):
#print("os.path.realpath(__file__):",os.path.realpath(__file__))
#base_path = os.path.dirname(os.path.realpath(__file__))
models_dir = folder_paths.models_dir
ROPE_MODELS_PATH = os.path.join(models_dir, "rope")
if not os.path.exists(ROPE_MODELS_PATH):
os.makedirs(ROPE_MODELS_PATH)
counter = 1
saveFile = os.path.join(ROPE_MODELS_PATH, fileName)
while os.path.exists(saveFile):
saveFile = os.path.join(ROPE_MODELS_PATH, fileName + '_' + str(counter))
counter += 1
print("Saving SwapInfo to file: ", saveFile)
#print(detectResult)
with open(saveFile, 'wb') as f:
pickle.dump(detectResult, f)
return fileName
class RopeWrapper_LoadSwapInfo:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"fileName": ("STRING", {"default": 'TEMP_PKL', "multiline": False}),
},
}
RETURN_TYPES = ("DETECTRESULT",)
RETURN_NAMES = ("DETECTRESULT",)
FUNCTION = "run"
CATEGORY = "RopeWrapper"
def run(self, fileName):
models_dir = folder_paths.models_dir
ROPE_MODELS_PATH = os.path.join(models_dir, "rope")
saveFile = os.path.join(ROPE_MODELS_PATH, fileName)
#print("Loading SwapInfo from file: ", saveFile)
detectResult=None
try:
with open(saveFile, 'rb') as f:
detectResult = pickle.load(f)
#print("Loaded SwapInfo from file: ", detectResult)
return (detectResult,)
except Exception as e:
print("Error loading SwapInfo from file: ", e)
return (None,)
# A dictionary that contains all nodes you want to export with their names
# NOTE: names should be globally unique
NODE_CLASS_MAPPINGS = {
#"RopeVideoCombine":RopeVideoCombine,
"RopeWrapper_DetectNode":RopeWrapper_DetectNode,
"RopeWrapper_LoadModels":RopeWrapper_LoadModels,
"RopeWrapper_SwapNode":RopeWrapper_SwapNode,
#"RopeWrapper_SwapNodeTEST":RopeWrapper_SwapNodeTEST,
"RopeWrapper_OptionNode":RopeWrapper_OptionNode,
"RopeWrapper_SaveSwapInfo":RopeWrapper_SaveSwapInfo,
"RopeWrapper_LoadSwapInfo":RopeWrapper_LoadSwapInfo,
"RopeWrapper_FaceRestore":RopeWrapper_FaceRestore,
}
# A dictionary that contains the friendly/humanly readable titles for the nodes
NODE_DISPLAY_NAME_MAPPINGS = {
#"RopeVideoCombine":"RopeVideoCombine",
"RopeWrapper_DetectNode":"RopeWrapper_DetectNode",
"RopeWrapper_LoadModels":"RopeWrapper_LoadModels",
"RopeWrapper_SwapNode":"RopeWrapper_SwapNode",
#"RopeWrapper_SwapNodeTEST":"RopeWrapper_SwapNodeTEST",
"RopeWrapper_OptionNode":"RopeWrapper_OptionNode",
"RopeWrapper_SaveSwapInfo":"RopeWrapper_SaveSwapInfo",
"RopeWrapper_LoadSwapInfo":"RopeWrapper_LoadSwapInfo",
"RopeWrapper_FaceRestore":"RopeWrapper_FaceRestore",
}
+1
View File
@@ -0,0 +1 @@
{"source videos": "D:/RopeCrystal/InputV", "source faces": "D:/RopeCrystal/sourceFaces", "saved videos": "D:/RopeCrystal/output", "dock_win_geom": [1920, 1009, -8, -8]}
+36
View File
@@ -0,0 +1,36 @@
import sys
import copy
import logging
class ColoredFormatter(logging.Formatter):
COLORS = {
"DEBUG": "\033[0;36m", # CYAN
"INFO": "\033[0;32m", # GREEN
"WARNING": "\033[0;33m", # YELLOW
"ERROR": "\033[0;31m", # RED
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
"RESET": "\033[0m", # RESET COLOR
}
def format(self, record):
colored_record = copy.copy(record)
levelname = colored_record.levelname
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
return super().format(colored_record)
# Create a new logger
logger = logging.getLogger("VideoHelperSuite")
logger.propagate = False
# Add handler if we don't have one.
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(ColoredFormatter("[%(name)s] - %(levelname)s - %(message)s"))
logger.addHandler(handler)
# Configure logger
loglevel = logging.INFO
logger.setLevel(loglevel)
View File
+175
View File
@@ -0,0 +1,175 @@
# #!/usr/bin/env python3
import time
import torch
from torchvision import transforms
import rope.GUI as GUI
import rope.VideoManager as VM
import rope.Models as Models
from rope.external.clipseg import CLIPDensePredT
resize_delay = 1
mem_delay = 1
# @profile
def coordinator():
global gui, vm, action, frame, r_frame, load_notice, resize_delay, mem_delay
# start = time.time()
if gui.get_action_length() > 0:
action.append(gui.get_action())
if vm.get_action_length() > 0:
action.append(vm.get_action())
##################
if vm.get_frame_length() > 0:
frame.append(vm.get_frame())
if len(frame) > 0:
gui.set_image(frame[0], False)
frame.pop(0)
####################
if vm.get_requested_frame_length() > 0:
r_frame.append(vm.get_requested_frame())
if len(r_frame) > 0:
gui.set_image(r_frame[0], True)
r_frame=[]
####################
if len(action) > 0:
# print('Action:', action[0][0])
# print('Value:', action[0][1])
if action[0][0] == "load_target_video":
vm.load_target_video(action[0][1])
action.pop(0)
elif action[0][0] == "load_target_image":
vm.load_target_image(action[0][1])
action.pop(0)
elif action[0][0] == "play_video":
vm.play_video(action[0][1])
action.pop(0)
elif action[0][0] == "get_requested_video_frame":
vm.get_requested_video_frame(action[0][1], marker=True)
action.pop(0)
elif action[0][0] == "get_requested_video_frame_without_markers":
vm.get_requested_video_frame(action[0][1], marker=False)
action.pop(0)
elif action[0][0] == "get_requested_image":
vm.get_requested_image()
action.pop(0)
# elif action[0][0] == "swap":
# vm.swap = action[0][1]
# action.pop(0)
elif action[0][0] == "target_faces":
vm.assign_found_faces(action[0][1])
action.pop(0)
elif action [0][0] == "saved_video_path":
vm.saved_video_path = action[0][1]
action.pop(0)
elif action [0][0] == "vid_qual":
vm.vid_qual = int(action[0][1])
action.pop(0)
elif action [0][0] == "set_stop":
vm.stop_marker = action[0][1]
action.pop(0)
elif action [0][0] == "perf_test":
vm.perf_test = action[0][1]
action.pop(0)
elif action [0][0] == 'ui_vars':
vm.ui_data = action[0][1]
action.pop(0)
elif action [0][0] == 'control':
vm.control = action[0][1]
action.pop(0)
elif action [0][0] == "parameters":
if action[0][1]["CLIPSwitch"]:
if not vm.clip_session:
vm.clip_session = load_clip_model()
vm.parameters = action[0][1]
action.pop(0)
elif action [0][0] == "markers":
vm.markers = action[0][1]
action.pop(0)
elif action[0][0] == "function":
eval(action[0][1])
action.pop(0)
elif action [0][0] == "clear_mem":
vm.clear_mem()
action.pop(0)
# From VM
elif action[0][0] == "stop_play":
gui.set_player_buttons_to_inactive()
action.pop(0)
elif action[0][0] == "set_slider_length":
gui.set_video_slider_length(action[0][1])
action.pop(0)
else:
print("Action not found: "+action[0][0]+" "+str(action[0][1]))
action.pop(0)
if resize_delay > 100:
gui.check_for_video_resize()
resize_delay = 0
else:
resize_delay +=1
if mem_delay > 1000:
gui.update_vram_indicator()
mem_delay = 0
else:
mem_delay +=1
vm.process()
gui.after(1, coordinator)
# print(time.time() - start)
def load_clip_model():
# https://github.com/timojl/clipseg
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
clip_session = CLIPDensePredT(version='ViT-B/16', reduce_dim=64, complex_trans_conv=True)
# clip_session = CLIPDensePredTMasked(version='ViT-B/16', reduce_dim=64)
clip_session.eval();
clip_session.load_state_dict(torch.load('./models/rd64-uni-refined.pth'), strict=False)
clip_session.to(device)
return clip_session
def run():
global gui, vm, action, frame, r_frame, resize_delay, mem_delay
models = Models.Models()
models.setModelPath("./")
gui = GUI.GUI(models)
vm = VM.VideoManager(models)
action = []
frame = []
r_frame = []
gui.initialize_gui()
coordinator()
gui.mainloop()
+413
View File
@@ -0,0 +1,413 @@
DEFAULT_DATA = {
# Buttons
'AddMarkerButtonDisplay': 'icon',
'AddMarkerButtonIconHover': './rope/media/add_marker_hover.png',
'AddMarkerButtonIconOff': './rope/media/add_marker_off.png',
'AddMarkerButtonIconOn': './rope/media/add_marker_off.png',
'AddMarkerButtonInfoText': 'ADD MARKER:\nAttaches a parameter marker to the current frame. Markers copy all parameter settings and apply them to all future frames, or until another marker is encountered.',
'AddMarkerButtonState': False,
'AudioDisplay': 'text',
'AudioInfoText': 'ENABLE REAL-TIME AUDIO:\nAdds audio from the input video during preview playback. If you are unable to maintain the input video frame rate, the audio will lag.',
'AudioState': False,
'AudioText': 'Enable Audio',
'AutoSwapState': False,
'ClearFacesDisplay': 'text',
'ClearFacesIcon': './rope/media/tarfacedel.png',
'ClearFacesIconHover': './rope/media/rec.png',
'ClearFacesIconOff': './rope/media/rec.png',
'ClearFacesIconOn': './rope/media/rec.png',
'ClearFacesInfoText': 'REMOVE FACES:\nRemove all currently found faces.',
'ClearFacesState': False,
'ClearFacesText': 'Clear Faces',
'ClearmemState': False,
'DefaultParamsButtonDisplay': 'text',
'DefaultParamsButtonInfoText': 'LOAD DEFAULT PARAMETERS:\nLoad the Rope default parameters for this column.',
'DefaultParamsButtonState': False,
'DefaultParamsButtonText': 'Load Defaults',
'DelEmbedDisplay': 'text',
'DelEmbedIconHover': './rope/media/rec.png',
'DelEmbedIconOff': './rope/media/rec.png',
'DelEmbedIconOn': './rope/media/rec.png',
'DelEmbedInfoText': 'DELETE EMBEDDING:\nDelete the currently selected embedding',
'DelEmbedState': False,
'DelEmbedText': 'Delete Emb',
'DelMarkerButtonDisplay': 'icon',
'DelMarkerButtonIconHover': './rope/media/remove_marker_hover.png',
'DelMarkerButtonIconOff': './rope/media/remove_marker_off.png',
'DelMarkerButtonIconOn': './rope/media/remove_marker_off.png',
'DelMarkerButtonInfoText': 'REMOVE MARKER:\nRemoves the parameter marker from the current frame.',
'DelMarkerButtonState': False,
'FindFacesDisplay': 'text',
'FindFacesIcon': './rope/media/tarface.png',
'FindFacesIconHover': './rope/media/rec.png',
'FindFacesIconOff': './rope/media/rec.png',
'FindFacesIconOn': './rope/media/rec.png',
'FindFacesInfoText': 'FIND FACES:\nFinds all new faces in the current frame.',
'FindFacesState': False,
'FindFacesText': 'Find Faces',
'ImgDockState': False,
'ImgVidMode': 'Videos',
'ImgVidState': False,
'LoadParamsButtonDisplay': 'text',
'LoadParamsButtonInfoText': 'LOAD SAVED PARAMETERS:\nLoads all parameters from this column if they have been previously saved. ',
'LoadParamsButtonState': False,
'LoadParamsButtonText': 'Load Params',
'LoadSFacesDisplay': 'both',
'LoadSFacesIcon': './rope/media/save.png',
'LoadSFacesIconHover': './rope/media/save.png',
'LoadSFacesIconOff': './rope/media/save.png',
'LoadSFacesIconOn': './rope/media/save.png',
'LoadSFacesInfoText': 'SELECT SOURCE FACES FOLDER:\nSelects and loads Source Faces from Folder. Make sure the folder only contains <good> images.',
'LoadSFacesState': False,
'LoadSFacesText': 'Select Faces Folder',
'LoadTVideosDisplay': 'both',
'LoadTVideosIconHover': './rope/media/save.png',
'LoadTVideosIconOff': './rope/media/save.png',
'LoadTVideosIconOn': './rope/media/save.png',
'LoadTVideosInfoText': 'SELECT INPUT VIDEOS/IMAGES FOLDER:\nSelect and load media from folder.',
'LoadTVideosState': False,
'LoadTVideosText': 'Select Videos Folder',
'MaskViewDisplay': 'text',
'MaskViewInfoText': 'SHOW MASKS:\nDisplays the mask for a face side-by-side with the face. Useful for understanding the masking behaviors and results.',
'MaskViewState': False,
'MaskViewText': 'Show Mask',
'NextMarkerButtonDisplay': 'icon',
'NextMarkerButtonIconHover': './rope/media/next_marker_hover.png',
'NextMarkerButtonIconOff': './rope/media/next_marker_off.png',
'NextMarkerButtonIconOn': './rope/media/next_marker_off.png',
'NextMarkerButtonInfoText': 'NEXT MARKER:\nMove to the next marker.',
'NextMarkerButtonState': False,
'OutputFolderDisplay': 'both',
'OutputFolderIconHover': './rope/media/save.png',
'OutputFolderIconOff': './rope/media/save.png',
'OutputFolderIconOn': './rope/media/save.png',
'OutputFolderInfoText': 'SELECT SAVE FOLDER:\nSelect folder for saved videos and images.',
'OutputFolderState': False,
'OutputFolderText': 'Select Output Folder',
'PerfTestState': False,
'PlayDisplay': 'icon',
'PlayIconHover': './rope/media/play_hover.png',
'PlayIconOff': './rope/media/play_off.png',
'PlayIconOn': './rope/media/play_on.png',
'PlayInfoText': 'PLAY:\nPlays the video. Press again to stop playing',
'PlayState': False,
'PrevMarkerButtonDisplay': 'icon',
'PrevMarkerButtonIconHover': './rope/media/previous_marker_hover.png',
'PrevMarkerButtonIconOff': './rope/media/previous_marker_off.png',
'PrevMarkerButtonIconOn': './rope/media/previous_marker_off.png',
'PrevMarkerButtonInfoText': 'PREVIOUS MARKER:\nMove to the previous marker.',
'PrevMarkerButtonState': False,
'RecordDisplay': 'icon',
'RecordIconHover': './rope/media/rec_hover.png',
'RecordIconOff': './rope/media/rec_off.png',
'RecordIconOn': './rope/media/rec_on.png',
'RecordInfoText': 'RECORD:\nArms the PLAY button for recording. Press RECORD, then PLAY to record. Press PLAY again to stop recording.',
'RecordState': False,
'SaveImageState': False,
'SaveParamsButtonDisplay': 'text',
'SaveParamsButtonInfoText': 'SAVE PARAMETERS:\nSaves all parameters in this column.',
'SaveParamsButtonState': False,
'SaveParamsButtonText': 'Save Params',
'StartRopeDisplay': 'both',
'StartRopeIconHover': './rope/media/rope.png',
'StartRopeIconOff': './rope/media/rope.png',
'StartRopeIconOn': './rope/media/rope.png',
'StartRopeInfoText': 'STARTS ROPE:\nStarts up the Rope application.',
'StartRopeState': False,
'StartRopeText': 'Start Rope',
'SwapFacesDisplay': 'text',
'SwapFacesInfoText': 'SWAP:\nSwap assigned Source Faces and Target Faces.',
'SwapFacesState': False,
'SwapFacesText': 'Swap Faces',
'TLBeginningDisplay': 'icon',
'TLBeginningIconHover': './rope/media/tl_beg_hover.png',
'TLBeginningIconOff': './rope/media/tl_beg_off.png',
'TLBeginningIconOn': './rope/media/tl_beg_on.png',
'TLBeginningInfoText': 'TIMELINE START:\nMove the timeline handle to the first frame.',
'TLBeginningState': False,
'TLLeftDisplay': 'icon',
'TLLeftIconHover': './rope/media/tl_left_hover.png',
'TLLeftIconOff': './rope/media/tl_left_off.png',
'TLLeftIconOn': './rope/media/tl_left_on.png',
'TLLeftInfoText': 'TIMELEFT NUDGE LEFT:\nMove the timeline handle to the left 30 frames.',
'TLLeftState': False,
'TLRightDisplay': 'icon',
'TLRightIconHover': './rope/media/tl_right_hover.png',
'TLRightIconOff': './rope/media/tl_right_off.png',
'TLRightIconOn': './rope/media/tl_right_on.png',
'TLRightInfoText': 'TIMELEFT NUDGE RIGHT:\nMove the timeline handle to the RIGHT 30 frames.',
'TLRightState': False,
'SaveImageButtonDisplay': 'text',
'SaveImageButtonInfoText': 'SAVE IMAGE:\nSaves the current image to your Output Folder.',
'SaveImageButtonState': False,
'SaveImageButtonText': 'Save Image',
'AutoSwapButtonDisplay': 'text',
'AutoSwapButtonInfoText': 'AUTOSWAP:\nAutomatcially applies your currently selected Input Face to new images.',
'AutoSwapButtonState': False,
'AutoSwapButtonText': 'Auto Swap',
'ClearVramButtonDisplay': 'text',
'ClearVramButtonInfoText': 'CLEAR VRAM:\nClears models from your VRAM.',
'ClearVramButtonState': False,
'ClearVramButtonText': 'Clear VRAM',
'GetNewEmbButtonDisplay': 'text',
'GetNewEmbButtonInfoText': 'CLEAR VRAM:\nClears models from your VRAM.',
'GetNewEmbButtonState': False,
'GetNewEmbButtonText': 'Clear VRAM',
'StopMarkerButtonnDisplay': 'icon',
'StopMarkerButtonIconHover': './rope/media/previous_marker_hover.png',
'StopMarkerButtonIconOff': './rope/media/previous_marker_off.png',
'StopMarkerButtonIconOn': './rope/media/previous_marker_off.png',
'StopMarkerButtonInfoText': 'CLEAR VRAM:\nClears models from your VRAM.',
'StopMarkerButtonState': False,
'StopMarkerButtonText': 'Clear VRAM',
#Switches
'ColorSwitchInfoText': 'RGB ADJUSTMENT:\nFine-tune the RGB color values of the swap.',
'ColorSwitchState': False,
'DiffSwitchInfoText': 'DIFFERENCER:\nAllow some of the original face to show in the swapped result when the difference between the two images is small. Can help bring back some texture to the swapped face',
'DiffSwitchState': False,
'FaceAdjSwitchInfoText': 'KPS and SCALE ADJUSTMENT:\nThis is an experimental feature to perform direct adjustments to the face landmarks found by the detector. There is also an option to adjust the scale of the swapped face.',
'FaceAdjSwitchState': False,
'FaceParserSwitchInfoText': 'BACKGROUND MASK:\nAllow the unprocessed background from the orginal image to show in the final swap.',
'FaceParserSwitchState': False,
'MouthParserSwitchInfoText': 'MOUTH MASK:\nAllow the mouth from the original face to show on the swapped face.',
'MouthParserSwitchState': False,
'OccluderSwitchInfoText': 'OCCLUSION MASK:\nAllow objects occluding the face to show up in the swapped image.',
'OccluderSwitchState': False,
'OrientSwitchInfoText': 'ORIENTATION:\nRotate the face detector to better detect faces at different angles',
'OrientSwitchState': False,
'RestorerSwitchInfoText': 'FACE RESTORER:\nRestore the swapped image by upscaling.',
'RestorerSwitchState': False,
'StrengthSwitchInfoText': 'SWAPPER STRENGTH:\nApply additional swapping iterations to increase the strength of the result, which may increase likeness',
'StrengthSwitchState': False,
'CLIPSwitchInfoText': 'TEXT MASKING:\nUse descriptions to identify objects that will be present in the final swapped image.',
'CLIPSwitchState': False,
# Sliders
'BlendSliderAmount': 5,
'BlendSliderInc': 1,
'BlendSliderInfoText': 'BLEND:\nCombined masks blending distance. Is not applied to the border masks.',
'BlendSliderMax': 100,
'BlendSliderMin': 0,
'BorderBlurSliderAmount': 10,
'BorderBlurSliderInc': 1,
'BorderBlurSliderInfoText': 'BORDER MASK BLEND:\nBorder mask blending distance.',
'BorderBlurSliderMax': 64,
'BorderBlurSliderMin': 0,
'BorderBottomSliderAmount': 10,
'BorderBottomSliderInc': 1,
'BorderBottomSliderInfoText': 'BOTTOM BORDER DISTANCE:\nA rectangle with adjustable top, bottom, and sides that blends the swapped face rseult back into the original image.',
'BorderBottomSliderMax': 64,
'BorderBottomSliderMin': 0,
'BorderSidesSliderAmount': 10,
'BorderSidesSliderInc': 1,
'BorderSidesSliderInfoText': 'SIDES BORDER DISTANCE:\nA rectangle with adjustable top, bottom, and sides that blends the swapped face result back into the original image.',
'BorderSidesSliderMax': 64,
'BorderSidesSliderMin': 0,
'BorderTopSliderAmount': 10,
'BorderTopSliderInc': 1,
'BorderTopSliderInfoText': 'TOP BORDER DISTANCE:\nA rectangle with adjustable top, bottom, and sides that blends the swapped face result back into the original image.',
'BorderTopSliderMax': 64,
'BorderTopSliderMin': 0,
'ColorBlueSliderAmount': 0,
'ColorBlueSliderInc': 1,
'ColorBlueSliderInfoText': 'RGB BLUE ADJUSTMENT',
'ColorBlueSliderMax': 100,
'ColorBlueSliderMin': -100,
'ColorGreenSliderAmount': 0,
'ColorGreenSliderInc': 1,
'ColorGreenSliderInfoText': 'RGB GREEN ADJUSTMENT',
'ColorGreenSliderMax': 100,
'ColorGreenSliderMin': -100,
'ColorRedSliderAmount': 0,
'ColorRedSliderInc': 1,
'ColorRedSliderInfoText': 'RGB RED ADJUSTMENT',
'ColorRedSliderMax': 100,
'ColorRedSliderMin': -100,
'DetectScoreSliderAmount': 50,
'DetectScoreSliderInc': 1,
'DetectScoreSliderInfoText': 'DETECTION SCORE LIMIT:\nDetermines the minimum score required for a face to be detected. Higher values require higher quality faces. E.g., if faces are flickering when at extreme angles, raising this will limit swapping attempts.',
'DetectScoreSliderMax': 100,
'DetectScoreSliderMin': 1,
'DiffSliderAmount': 4,
'DiffSliderInc': 1,
'DiffSliderInfoText': 'DIFFERENCING AMOUNT:\nHigher values relaxes the similarity constraint.',
'DiffSliderMax': 100,
'DiffSliderMin': 0,
'FaceParserSliderAmount': 0,
'FaceParserSliderInc': 1,
'FaceParserSliderInfoText': 'BACKGROUND MASK AMOUNT:\nNegative/Positive values shrink and grow the mask.',
'FaceParserSliderMax': 50,
'FaceParserSliderMin': -50,
'FaceScaleSliderAmount': 0,
'FaceScaleSliderInc': 1,
'FaceScaleSliderInfoText': 'FACE SCALE AMOUNT',
'FaceScaleSliderMax': 20,
'FaceScaleSliderMin': -20,
'KPSScaleSliderAmount': 0,
'KPSScaleSliderInc': 1,
'KPSScaleSliderInfoText': 'KPS SCALE AMOUNT:\nGrows and shrinks the detection point distances.',
'KPSScaleSliderMax': 100,
'KPSScaleSliderMin': -100,
'KPSXSliderAmount': 0,
'KPSXSliderInc': 1,
'KPSXSliderInfoText': 'KPS X-DIRECTION AMOUNT:\nShifts the detection points left and right',
'KPSXSliderMax': 100,
'KPSXSliderMin': -100,
'KPSYSliderAmount': 0,
'KPSYSliderInc': 1,
'KPSYSliderInfoText': 'KPS Y-DIRECTION AMOUNT:\nShifts the detection points lup and down',
'KPSYSliderMax': 100,
'KPSYSliderMin': -100,
'MouthParserSliderAmount': 0,
'MouthParserSliderInc': 1,
'MouthParserSliderInfoText': 'MOUTH MASK AMOUNT:\nAdjust the size of the mask. Negative values only mask the inside of the mouth, including the tongue. Positive values also include lips',
'MouthParserSliderMax': 50,
'MouthParserSliderMin': -50,
'OccluderSliderAmount': 0,
'OccluderSliderInc': 1,
'OccluderSliderInfoText': 'OCCLUDER AMOUNT:\nGrows or shrinks the occluded region',
'OccluderSliderMax': 100,
'OccluderSliderMin': -100,
'OrientSliderAmount': 0,
'OrientSliderInc': 90,
'OrientSliderInfoText': 'ORIENTATION ANGLE:\nSet this to the angle of the input face angle to help with laying down/upside down/etc. Angles are read clockwise.',
'OrientSliderMax': 270,
'OrientSliderMin': 0,
'RestorerSliderAmount': 100,
'RestorerSliderInc': 5,
'RestorerSliderInfoText': 'RESTORER AMOUNT:\nBlends the Restored results back into the original swap.',
'RestorerSliderMax': 100,
'RestorerSliderMin': 0,
'StrengthSliderAmount': 100,
'StrengthSliderInc': 25,
'StrengthSliderInfoText': 'STRENGTH AMOUNT:\nIncrease up to 5x additional swaps (500%). 200% is generally a good result. Set to 0 to turn off swapping but allow the rest of the pipeline to apply to the original image.',
'StrengthSliderMax': 500,
'StrengthSliderMin': 0,
'ThreadsSliderAmount': 5,
'ThreadsSliderInc': 1,
'ThreadsSliderInfoText': 'EXECUTION THREADS:\nSet number of execution threads while playing and recording. Depends strongly on GPU VRAM. 5 threads for 24GB.',
'ThreadsSliderMax': 20,
'ThreadsSliderMin': 1,
'ThresholdSliderAmount': 55,
'ThresholdSliderInc': 1,
'ThresholdSliderInfoText': 'THRESHHOLD AMOUNT:\nRaise to reduce faces hopping around when swapping multiple people. A higher value is stricter.',
'ThresholdSliderMax': 100,
'ThresholdSliderMin': 0,
'VideoQualSliderAmount': 18,
'VideoQualSliderInc': 1,
'VideoQualSliderInfoText': 'VIDEO QUALITY:\nThe encoding quality of the recorded video. 0 is best, 50 is worst, 18 is mostly lossless. File size increases with a lower quality number.',
'VideoQualSliderMax': 50,
'VideoQualSliderMin': 0,
'CLIPSliderAmount': 50,
'CLIPSliderInc': 1,
'CLIPSliderInfoText': 'TEXT MASKING STENGTH:\nIncrease to strengthen the effect.',
'CLIPSliderMax': 100,
'CLIPSliderMin': 0,
'ColorGammaSliderAmount': 1,
'ColorGammaSliderInc': 0.02,
'ColorGammaSliderInfoText': 'GAMMA VALUE:\nChanges Gamma.',
'ColorGammaSliderMax': 2,
'ColorGammaSliderMin': 0,
# Text Selection
'DetectTypeTextSelInfoText': 'FACE DETECTION MODEL:\nSelect the face detection model. Mostly only subtle differences, but can significant differences when the face is at extreme angles or covered.',
'DetectTypeTextSelMode': 'Retinaface',
'DetectTypeTextSelModes': ['Retinaface', 'Yolov8', 'SCRDF'],
'PreviewModeTextSelInfoText': '',
'PreviewModeTextSelMode': 'Video',
'PreviewModeTextSelModes': ['Video', 'Image','Theater'],
'RecordTypeTextSelInfoText': 'VIDEO RECORDING LIBRARY:\nSelect the recording library used for video recording. FFMPEG uses the Video Quality slider to adjust the size and quality of the final video. OPENCV has no options but is faster and produces good results.',
'RecordTypeTextSelMode': 'FFMPEG',
'RecordTypeTextSelModes': ['FFMPEG', 'OPENCV'],
'RestorerDetTypeTextSelInfoText': 'ALIGNMENT:\nSelect how the face is aligned for the Restorer. Original preserves facial features and expressions, but can show some artifacts. Reference softens features. Blend is closer to Reference but is much faster.',
'RestorerDetTypeTextSelMode': 'Blend',
'RestorerDetTypeTextSelModes': ['Original', 'Blend', 'Reference'],
'RestorerTypeTextSelInfoText': 'RESTORER TYPE:\nSelect the Restorer type.\nSpeed: GPEN256>GFPGAN>CF>GPEN512',
'RestorerTypeTextSelMode': 'GFPGAN',
'RestorerTypeTextSelModes': ['GFPGAN', 'CF', 'GPEN256', 'GPEN512'],
'MergeTextSelInfoText': 'INPUT FACES MERGE MATH:\nWhen shift-clicking face for merging, determines how the embedding vectors are combined.',
'MergeTextSelMode': 'Mean',
'MergeTextSelModes': ['Mean', 'Median'],
'SwapperTypeTextSelInfoText': 'SWAPPER OUTPUT RESOLUTION:\nDetermines the resolution of the swapper output.',
'SwapperTypeTextSelMode': '128',
'SwapperTypeTextSelModes': ['128', '256', '512'],
# Text Entry
'CLIPTextEntry': '',
'CLIPTextEntryInfoText': 'TEXT MASKING ENTRY:\nTo use, type a word(s) in the box separated by commas and press <enter>.',
}
PARAM_VARS = {
'CLIPState': False,
'CLIPMode': 0,
'CLIPModes': ['CLIP'],
'CLIPAmount': [50],
'CLIPMin': 0,
'CLIPMax': 100,
'CLIPInc': 1,
'CLIPUnit': '%',
'CLIPIcon': './rope/media/CLIP.png',
'CLIPMessage': 'CLIP - Text based occluder. Occluded objects are visible in the final image (occluded from the mask). [LB: on/off, MW: strength]',
'CLIPFunction': False,
"CLIPText": '',
}
PARAMS = {
'ClearmemFunction': 'self.clear_mem()',
'PerfTestFunction': 'self.toggle_perf_test()',
'ImgVidFunction': 'self.toggle_vid_img()',
'AutoSwapFunction': 'self.toggle_auto_swap()',
'SaveImageFunction': 'self.save_image()',
'ClearmemIcon': './rope/media/clear_mem.png',
'SaveImageIcon': './rope/media/save_disk.png',
'PerfTestIcon': './rope/media/test.png',
'RefDelIcon': './rope/media/construction.png',
'TransformIcon': './rope/media/scale.png',
'ThresholdIcon': './rope/media/thresh.png',
'LoadSFacesIcon': './rope/media/save.png',
'BorderIcon': './rope/media/maskup.png',
'OccluderIcon': './rope/media/occluder.png',
'ColorIcon': './rope/media/rgb.png',
'StrengthIcon': './rope/media/strength.png',
'OrientationIcon': './rope/media/orient.png',
'DiffIcon': './rope/media/diff.png',
'MouthParserIcon': './rope/media/parse.png',
'AudioIcon': './rope/media/rgb.png',
'VideoQualityIcon': './rope/media/tarface.png',
'MaskViewIcon': './rope/media/maskblur.png',
'BlurIcon': './rope/media/blur.png',
'ToggleStopIcon': './rope/media/STOP.png',
'DelEmbedIcon': './rope/media/delemb.png',
'ImgVidIcon': './rope/media/imgvid.png',
'ImgVidMessage': 'IMAGE/VIDEO - Toggle between Image and Video folder view.',
'ToggleStopMessage': 'STOP MARKER - Sets a frame that will stop the video playing/recording.',
'AutoSwapMessage': 'AUTO SWAP - Automatically swaps the first person in an image to the selcted source faces [LB: Turn on/off]',
'SaveImageMessage': 'SAVE IMAGE - Save image to output folder',
'ClearmemMessage': 'CLEAR VRAM - Clears all models from VRAM [LB: Clear]',
'PerfTestMessage': 'PERFORMANCE DATA - Displays timing data in the console for critical Rope functions. [LB: on/off]',
'RefDelMessage': 'REFERENCE DELTA - Modify the reference points. Turn on mask preview to see adjustments. [LB: on/off, RB: translate x/y, and scale, MW: amount]' ,
'ThresholdMessage': 'THRESHOLD - Threshold for determining if Target Faces match faces in a frame. Lower is stricter. [LB: use amount/match all, MW: value]',
'TransformMessage': 'SCALE - Adjust the scale of the face. Use with Background parser to blend into the image. [LB: on/off, MW: amount]',
'PlayMessage': 'PLAY - Plays the video. Press again to stop playing',
}
+1901
View File
File diff suppressed because it is too large Load Diff
+1247
View File
File diff suppressed because it is too large Load Diff
+1278
View File
File diff suppressed because it is too large Load Diff
+286
View File
@@ -0,0 +1,286 @@
canvas_frame_label_1 = {
'bg': '#17181A',
'bd': '0',
'relief': 'flat',
'highlightthickness': '0'
}
canvas_frame_label_2 = {
'bg': '#212126',
'bd': '0',
'relief': 'flat',
'highlightthickness': '0'
}
canvas_frame_label_3 = {
'bg': '#28282e',
'bd': '0',
'relief': 'flat',
'highlightthickness': '0'
}
info_label = {
'bg': '#28282e',
'fg': '#FFFFFF',
'bd': '5',
'relief': 'flat',
'highlightthickness': '0',
'font': ("Segoe UI", 9),
'anchor': 'nw',
'justify': 'left',
}
text_1 = {
'bg': '#17181A',
'fg': '#D0D0D0',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 9)
}
text_2 = {
'bg': '#212126',
'fg': '#D0D0D0',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 9)
}
text_3 = {
'bg': '#28282e',
'fg': '#D0D0D0',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 9)
}
option_slider_style = {
'bg': '#919191', #sliderbar color
'activebackground': 'white',
'highlightcolor': 'white',
'highlightthickness': '0',
'relief': 'flat',
'sliderrelief': 'flat',
'border': '0',
'width': '3',
'troughcolor': '#1F1F1F',
}
entry_3 = {
'bg': '#1F1F1F',
'fg': '#FFFFFF',
'relief': 'flat',
'border': '0',
'width': '5',
'justify': 'c',
'font': ("Segoe UI", 9),
'highlightthickness': '1',
'highlightbackground': '#17181A',
}
entry_2 = {
'bg': '#1F1F1F',
'fg': '#FFFFFF',
'relief': 'flat',
'border': '0',
'highlightthickness': '1',
'highlightbackground': '#17181A',
'width': '5',
'justify': 'l',
'font': ("Segoe UI", 9)
}
text_selection_off_3 = {
'bg': '#28282e',
'fg': '#7A7A7A',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
text_selection_on_3 = {
'bg': '#28282e',
'fg': '#FFFFFF',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
text_selection_off_2 = {
'bg': '#212126',
'fg': '#7A7A7A',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
text_selection_on_2 = {
'bg': '#212126',
'fg': '#FFFFFF',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
parameter_switch_3 = {
'bg': '#28282e',
'fg': '#FFFFFF',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
canvas_bg = {
'bg': '#090909',
'relief': 'flat',
'bd': '0',
'highlightthickness': '0'
}
icon = {
'IconOn': './rope/media/OnState.png',
'IconOff': './rope/media/OffState.png',
}
frame_style_bg = {
'bg': '#090909',
'relief': 'flat',
'bd': '0'
}
button_3 = {
'bg': '#28282E',
'fg': '#FFFFFF',
'activebackground': '#28282E',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
button_2 = {
'bg': '#212126',
'fg': '#FFFFFF',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
button_1 = {
'bg': '#17181A',
'fg': '#FFFFFF',
'activebackground': '#17181A',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
button_inactive = {
'bg': '#17181A',
'fg': '#FFFFFF',
'activebackground': '#17181A',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
button_active = {
'bg': '#17181A',
'fg': '#FFFFFF',
'activebackground': '#17181A',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 10)
}
media_button_off_3= {
'bg': '#28282E',
'fg': '#7A7A7A',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 8)
}
media_button_on_3= {
'bg': '#d10303',
'fg': '#FFFFFF',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 8)
}
ui_text_na_2 = {
'bg': '#212126',
'fg': '#7A7A7A',
'activebackground': '#212126',
'activeforeground': 'white',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI", 9)
}
timeline_canvas = {
'bg': '#212126',
'relief': 'flat',
'bd': '0',
'highlightthickness': '0'
}
donate_1 = {
'bg': '#17181A',
'fg': 'light goldenrod',
'relief': 'flat',
'border': '0',
'font': ("Segoe UI Semibold", 10),
'cursor': "hand2",
}
# Panes
# 3:#28282E
# 2:#212126
# 1:#17181A
# preview background: #1A1A1A
# Num Fields, slider bg: #1F1F1F
# slider ball: #919191
# Borders:#090909
# Text
# On/off:#FFFFFF
# labels: #D0D0D0
# notActive: #7A7A7A
# active:#FFFFFF
# highlighted button: #B1B1B2
# Button off: #828282
# on: #FFFFFF
# hover: #b1b1b2
# off: #828282
+1478
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
from .clip import *
Binary file not shown.
+245
View File
@@ -0,0 +1,245 @@
import hashlib
import os
import urllib
import warnings
from typing import Any, Union, List
from pkg_resources import packaging
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokenizer import SimpleTokenizer as _Tokenizer
try:
from torchvision.transforms import InterpolationMode
BICUBIC = InterpolationMode.BICUBIC
except ImportError:
BICUBIC = Image.BICUBIC
if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
warnings.warn("PyTorch version 1.7.1 or higher is recommended")
__all__ = ["available_models", "load", "tokenize"]
_tokenizer = _Tokenizer()
_MODELS = {
"RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
"RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
"RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
"RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
"RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
"ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
"ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
"ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
"ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
}
def _download(url: str, root: str):
os.makedirs(root, exist_ok=True)
filename = os.path.basename(url)
expected_sha256 = url.split("/")[-2]
download_target = os.path.join(root, filename)
if os.path.exists(download_target) and not os.path.isfile(download_target):
raise RuntimeError(f"{download_target} exists and is not a regular file")
if os.path.isfile(download_target):
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
return download_target
else:
warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
while True:
buffer = source.read(8192)
if not buffer:
break
output.write(buffer)
loop.update(len(buffer))
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
return download_target
def _convert_image_to_rgb(image):
return image.convert("RGB")
def _transform(n_px):
return Compose([
Resize(n_px, interpolation=BICUBIC),
CenterCrop(n_px),
_convert_image_to_rgb,
ToTensor(),
Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
])
def available_models() -> List[str]:
"""Returns the names of available CLIP models"""
return list(_MODELS.keys())
def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
"""Load a CLIP model
Parameters
----------
name : str
A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
device : Union[str, torch.device]
The device to put the loaded model
jit : bool
Whether to load the optimized JIT model or more hackable non-JIT model (default).
download_root: str
path to download the model files; by default, it uses "~/.cache/clip"
Returns
-------
model : torch.nn.Module
The CLIP model
preprocess : Callable[[PIL.Image], torch.Tensor]
A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
"""
if name in _MODELS:
model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
elif os.path.isfile(name):
model_path = name
else:
raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
with open(model_path, 'rb') as opened_file:
try:
# loading JIT archive
model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
state_dict = None
except RuntimeError:
# loading saved state dict
if jit:
warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
jit = False
state_dict = torch.load(opened_file, map_location="cpu")
if not jit:
model = build_model(state_dict or model.state_dict()).to(device)
if str(device) == "cpu":
model.float()
return model, _transform(model.visual.input_resolution)
# patch the device names
device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
def _node_get(node: torch._C.Node, key: str):
"""Gets attributes of a node which is polymorphic over return type.
From https://github.com/pytorch/pytorch/pull/82628
"""
sel = node.kindOf(key)
return getattr(node, sel)(key)
def patch_device(module):
try:
graphs = [module.graph] if hasattr(module, "graph") else []
except RuntimeError:
graphs = []
if hasattr(module, "forward1"):
graphs.append(module.forward1.graph)
for graph in graphs:
for node in graph.findAllNodes("prim::Constant"):
if "value" in node.attributeNames() and str(_node_get(node, "value")).startswith("cuda"):
node.copyAttributes(device_node)
model.apply(patch_device)
patch_device(model.encode_image)
patch_device(model.encode_text)
# patch dtype to float32 on CPU
if str(device) == "cpu":
float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
float_node = float_input.node()
def patch_float(module):
try:
graphs = [module.graph] if hasattr(module, "graph") else []
except RuntimeError:
graphs = []
if hasattr(module, "forward1"):
graphs.append(module.forward1.graph)
for graph in graphs:
for node in graph.findAllNodes("aten::to"):
inputs = list(node.inputs())
for i in [1, 2]: # dtype can be the second or third argument to aten::to()
if _node_get(inputs[i].node(), "value") == 5:
inputs[i].node().copyAttributes(float_node)
model.apply(patch_float)
patch_float(model.encode_image)
patch_float(model.encode_text)
model.float()
return model, _transform(model.input_resolution.item())
def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]:
"""
Returns the tokenized representation of given input string(s)
Parameters
----------
texts : Union[str, List[str]]
An input string or a list of input strings to tokenize
context_length : int
The context length to use; all CLIP models use 77 as the context length
truncate: bool
Whether to truncate the text in case its encoding is longer than the context length
Returns
-------
A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
"""
if isinstance(texts, str):
texts = [texts]
sot_token = _tokenizer.encoder["<|startoftext|>"]
eot_token = _tokenizer.encoder["<|endoftext|>"]
all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
else:
result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
for i, tokens in enumerate(all_tokens):
if len(tokens) > context_length:
if truncate:
tokens = tokens[:context_length]
tokens[-1] = eot_token
else:
raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
result[i, :len(tokens)] = torch.tensor(tokens)
return result
+436
View File
@@ -0,0 +1,436 @@
from collections import OrderedDict
from typing import Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.relu2 = nn.ReLU(inplace=True)
self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu3 = nn.ReLU(inplace=True)
self.downsample = None
self.stride = stride
if stride > 1 or inplanes != planes * Bottleneck.expansion:
# downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
self.downsample = nn.Sequential(OrderedDict([
("-1", nn.AvgPool2d(stride)),
("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
("1", nn.BatchNorm2d(planes * self.expansion))
]))
def forward(self, x: torch.Tensor):
identity = x
out = self.relu1(self.bn1(self.conv1(x)))
out = self.relu2(self.bn2(self.conv2(out)))
out = self.avgpool(out)
out = self.bn3(self.conv3(out))
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu3(out)
return out
class AttentionPool2d(nn.Module):
def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
super().__init__()
self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
self.k_proj = nn.Linear(embed_dim, embed_dim)
self.q_proj = nn.Linear(embed_dim, embed_dim)
self.v_proj = nn.Linear(embed_dim, embed_dim)
self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
self.num_heads = num_heads
def forward(self, x):
x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
x, _ = F.multi_head_attention_forward(
query=x[:1], key=x, value=x,
embed_dim_to_check=x.shape[-1],
num_heads=self.num_heads,
q_proj_weight=self.q_proj.weight,
k_proj_weight=self.k_proj.weight,
v_proj_weight=self.v_proj.weight,
in_proj_weight=None,
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
bias_k=None,
bias_v=None,
add_zero_attn=False,
dropout_p=0,
out_proj_weight=self.c_proj.weight,
out_proj_bias=self.c_proj.bias,
use_separate_proj_weight=True,
training=self.training,
need_weights=False
)
return x.squeeze(0)
class ModifiedResNet(nn.Module):
"""
A ResNet class that is similar to torchvision's but contains the following changes:
- There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
- Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
- The final pooling layer is a QKV attention instead of an average pool
"""
def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
super().__init__()
self.output_dim = output_dim
self.input_resolution = input_resolution
# the 3-layer stem
self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(width // 2)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(width // 2)
self.relu2 = nn.ReLU(inplace=True)
self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
self.bn3 = nn.BatchNorm2d(width)
self.relu3 = nn.ReLU(inplace=True)
self.avgpool = nn.AvgPool2d(2)
# residual layers
self._inplanes = width # this is a *mutable* variable used during construction
self.layer1 = self._make_layer(width, layers[0])
self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
embed_dim = width * 32 # the ResNet feature dimension
self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
def _make_layer(self, planes, blocks, stride=1):
layers = [Bottleneck(self._inplanes, planes, stride)]
self._inplanes = planes * Bottleneck.expansion
for _ in range(1, blocks):
layers.append(Bottleneck(self._inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
def stem(x):
x = self.relu1(self.bn1(self.conv1(x)))
x = self.relu2(self.bn2(self.conv2(x)))
x = self.relu3(self.bn3(self.conv3(x)))
x = self.avgpool(x)
return x
x = x.type(self.conv1.weight.dtype)
x = stem(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.attnpool(x)
return x
class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor):
orig_type = x.dtype
ret = super().forward(x.type(torch.float32))
return ret.type(orig_type)
class QuickGELU(nn.Module):
def forward(self, x: torch.Tensor):
return x * torch.sigmoid(1.702 * x)
class ResidualAttentionBlock(nn.Module):
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(OrderedDict([
("c_fc", nn.Linear(d_model, d_model * 4)),
("gelu", QuickGELU()),
("c_proj", nn.Linear(d_model * 4, d_model))
]))
self.ln_2 = LayerNorm(d_model)
self.attn_mask = attn_mask
def attention(self, x: torch.Tensor):
self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
def forward(self, x: torch.Tensor):
x = x + self.attention(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
class Transformer(nn.Module):
def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
super().__init__()
self.width = width
self.layers = layers
self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
def forward(self, x: torch.Tensor):
return self.resblocks(x)
class VisionTransformer(nn.Module):
def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
super().__init__()
self.input_resolution = input_resolution
self.output_dim = output_dim
self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
scale = width ** -0.5
self.class_embedding = nn.Parameter(scale * torch.randn(width))
self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
self.ln_pre = LayerNorm(width)
self.transformer = Transformer(width, layers, heads)
self.ln_post = LayerNorm(width)
self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
def forward(self, x: torch.Tensor):
x = self.conv1(x) # shape = [*, width, grid, grid]
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
x = x + self.positional_embedding.to(x.dtype)
x = self.ln_pre(x)
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer(x)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_post(x[:, 0, :])
if self.proj is not None:
x = x @ self.proj
return x
class CLIP(nn.Module):
def __init__(self,
embed_dim: int,
# vision
image_resolution: int,
vision_layers: Union[Tuple[int, int, int, int], int],
vision_width: int,
vision_patch_size: int,
# text
context_length: int,
vocab_size: int,
transformer_width: int,
transformer_heads: int,
transformer_layers: int
):
super().__init__()
self.context_length = context_length
if isinstance(vision_layers, (tuple, list)):
vision_heads = vision_width * 32 // 64
self.visual = ModifiedResNet(
layers=vision_layers,
output_dim=embed_dim,
heads=vision_heads,
input_resolution=image_resolution,
width=vision_width
)
else:
vision_heads = vision_width // 64
self.visual = VisionTransformer(
input_resolution=image_resolution,
patch_size=vision_patch_size,
width=vision_width,
layers=vision_layers,
heads=vision_heads,
output_dim=embed_dim
)
self.transformer = Transformer(
width=transformer_width,
layers=transformer_layers,
heads=transformer_heads,
attn_mask=self.build_attention_mask()
)
self.vocab_size = vocab_size
self.token_embedding = nn.Embedding(vocab_size, transformer_width)
self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
self.ln_final = LayerNorm(transformer_width)
self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
self.initialize_parameters()
def initialize_parameters(self):
nn.init.normal_(self.token_embedding.weight, std=0.02)
nn.init.normal_(self.positional_embedding, std=0.01)
if isinstance(self.visual, ModifiedResNet):
if self.visual.attnpool is not None:
std = self.visual.attnpool.c_proj.in_features ** -0.5
nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
for name, param in resnet_block.named_parameters():
if name.endswith("bn3.weight"):
nn.init.zeros_(param)
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
attn_std = self.transformer.width ** -0.5
fc_std = (2 * self.transformer.width) ** -0.5
for block in self.transformer.resblocks:
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
if self.text_projection is not None:
nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
def build_attention_mask(self):
# lazily create causal attention mask, with full attention between the vision tokens
# pytorch uses additive attention mask; fill with -inf
mask = torch.empty(self.context_length, self.context_length)
mask.fill_(float("-inf"))
mask.triu_(1) # zero out the lower diagonal
return mask
@property
def dtype(self):
return self.visual.conv1.weight.dtype
def encode_image(self, image):
return self.visual(image.type(self.dtype))
def encode_text(self, text):
x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
x = x + self.positional_embedding.type(self.dtype)
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer(x)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_final(x).type(self.dtype)
# x.shape = [batch_size, n_ctx, transformer.width]
# take features from the eot embedding (eot_token is the highest number in each sequence)
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
return x
def forward(self, image, text):
image_features = self.encode_image(image)
text_features = self.encode_text(text)
# normalized features
image_features = image_features / image_features.norm(dim=1, keepdim=True)
text_features = text_features / text_features.norm(dim=1, keepdim=True)
# cosine similarity as logits
logit_scale = self.logit_scale.exp()
logits_per_image = logit_scale * image_features @ text_features.t()
logits_per_text = logits_per_image.t()
# shape = [global_batch_size, global_batch_size]
return logits_per_image, logits_per_text
def convert_weights(model: nn.Module):
"""Convert applicable model parameters to fp16"""
def _convert_weights_to_fp16(l):
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
l.weight.data = l.weight.data.half()
if l.bias is not None:
l.bias.data = l.bias.data.half()
if isinstance(l, nn.MultiheadAttention):
for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
tensor = getattr(l, attr)
if tensor is not None:
tensor.data = tensor.data.half()
for name in ["text_projection", "proj"]:
if hasattr(l, name):
attr = getattr(l, name)
if attr is not None:
attr.data = attr.data.half()
model.apply(_convert_weights_to_fp16)
def build_model(state_dict: dict):
vit = "visual.proj" in state_dict
if vit:
vision_width = state_dict["visual.conv1.weight"].shape[0]
vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
image_resolution = vision_patch_size * grid_size
else:
counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
vision_layers = tuple(counts)
vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
vision_patch_size = None
assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
image_resolution = output_width * 32
embed_dim = state_dict["text_projection"].shape[1]
context_length = state_dict["positional_embedding"].shape[0]
vocab_size = state_dict["token_embedding.weight"].shape[0]
transformer_width = state_dict["ln_final.weight"].shape[0]
transformer_heads = transformer_width // 64
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
model = CLIP(
embed_dim,
image_resolution, vision_layers, vision_width, vision_patch_size,
context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
)
for key in ["input_resolution", "context_length", "vocab_size"]:
if key in state_dict:
del state_dict[key]
convert_weights(model)
model.load_state_dict(state_dict)
return model.eval()
+132
View File
@@ -0,0 +1,132 @@
import gzip
import html
import os
from functools import lru_cache
import ftfy
import regex as re
@lru_cache()
def default_bpe():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
@lru_cache()
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a corresponding list of unicode strings.
The reversible bpe codes work on unicode strings.
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
This is a signficant percentage of your normal, say, 32K bpe vocab.
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
And avoids mapping to whitespace/control characters the bpe code barfs on.
"""
bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
cs = bs[:]
n = 0
for b in range(2**8):
if b not in bs:
bs.append(b)
cs.append(2**8+n)
n += 1
cs = [chr(n) for n in cs]
return dict(zip(bs, cs))
def get_pairs(word):
"""Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
def basic_clean(text):
text = ftfy.fix_text(text)
text = html.unescape(html.unescape(text))
return text.strip()
def whitespace_clean(text):
text = re.sub(r'\s+', ' ', text)
text = text.strip()
return text
class SimpleTokenizer(object):
def __init__(self, bpe_path: str = default_bpe()):
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
merges = merges[1:49152-256-2+1]
merges = [tuple(merge.split()) for merge in merges]
vocab = list(bytes_to_unicode().values())
vocab = vocab + [v+'</w>' for v in vocab]
for merge in merges:
vocab.append(''.join(merge))
vocab.extend(['<|startoftext|>', '<|endoftext|>'])
self.encoder = dict(zip(vocab, range(len(vocab))))
self.decoder = {v: k for k, v in self.encoder.items()}
self.bpe_ranks = dict(zip(merges, range(len(merges))))
self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
def bpe(self, token):
if token in self.cache:
return self.cache[token]
word = tuple(token[:-1]) + ( token[-1] + '</w>',)
pairs = get_pairs(word)
if not pairs:
return token+'</w>'
while True:
bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
if bigram not in self.bpe_ranks:
break
first, second = bigram
new_word = []
i = 0
while i < len(word):
try:
j = word.index(first, i)
new_word.extend(word[i:j])
i = j
except:
new_word.extend(word[i:])
break
if word[i] == first and i < len(word)-1 and word[i+1] == second:
new_word.append(first+second)
i += 2
else:
new_word.append(word[i])
i += 1
new_word = tuple(new_word)
word = new_word
if len(word) == 1:
break
else:
pairs = get_pairs(word)
word = ' '.join(word)
self.cache[token] = word
return word
def encode(self, text):
bpe_tokens = []
text = whitespace_clean(basic_clean(text)).lower()
for token in re.findall(self.pat, text):
token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
return bpe_tokens
def decode(self, tokens):
text = ''.join([self.decoder[token] for token in tokens])
text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
return text
+538
View File
@@ -0,0 +1,538 @@
import math
from os.path import basename, dirname, join, isfile
import torch
from torch import nn
from torch.nn import functional as nnf
from torch.nn.modules.activation import ReLU
def get_prompt_list(prompt):
if prompt == 'plain':
return ['{}']
elif prompt == 'fixed':
return ['a photo of a {}.']
elif prompt == 'shuffle':
return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.']
elif prompt == 'shuffle+':
return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.',
'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.',
'a bad photo of a {}.', 'a photo of the {}.']
else:
raise ValueError('Invalid value for prompt')
def forward_multihead_attention(x, b, with_aff=False, attn_mask=None):
"""
Simplified version of multihead attention (taken from torch source code but without tons of if clauses).
The mlp and layer norm come from CLIP.
x: input.
b: multihead attention module.
"""
x_ = b.ln_1(x)
q, k, v = nnf.linear(x_, b.attn.in_proj_weight, b.attn.in_proj_bias).chunk(3, dim=-1)
tgt_len, bsz, embed_dim = q.size()
head_dim = embed_dim // b.attn.num_heads
scaling = float(head_dim) ** -0.5
q = q.contiguous().view(tgt_len, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
k = k.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
v = v.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1)
q = q * scaling
attn_output_weights = torch.bmm(q, k.transpose(1, 2)) # n_heads * batch_size, tokens^2, tokens^2
if attn_mask is not None:
attn_mask_type, attn_mask = attn_mask
n_heads = attn_output_weights.size(0) // attn_mask.size(0)
attn_mask = attn_mask.repeat(n_heads, 1)
if attn_mask_type == 'cls_token':
# the mask only affects similarities compared to the readout-token.
attn_output_weights[:, 0, 1:] = attn_output_weights[:, 0, 1:] * attn_mask[None,...]
# attn_output_weights[:, 0, 0] = 0*attn_output_weights[:, 0, 0]
if attn_mask_type == 'all':
# print(attn_output_weights.shape, attn_mask[:, None].shape)
attn_output_weights[:, 1:, 1:] = attn_output_weights[:, 1:, 1:] * attn_mask[:, None]
attn_output_weights = torch.softmax(attn_output_weights, dim=-1)
attn_output = torch.bmm(attn_output_weights, v)
attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
attn_output = b.attn.out_proj(attn_output)
x = x + attn_output
x = x + b.mlp(b.ln_2(x))
if with_aff:
return x, attn_output_weights
else:
return x
class CLIPDenseBase(nn.Module):
def __init__(self, version, reduce_cond, reduce_dim, prompt, n_tokens):
super().__init__()
from rope.external.cliplib import clip
# prec = torch.FloatTensor
self.clip_model, _ = clip.load(version, device='cpu', jit=False)
self.model = self.clip_model.visual
# if not None, scale conv weights such that we obtain n_tokens.
self.n_tokens = n_tokens
for p in self.clip_model.parameters():
p.requires_grad_(False)
# conditional
if reduce_cond is not None:
self.reduce_cond = nn.Linear(512, reduce_cond)
for p in self.reduce_cond.parameters():
p.requires_grad_(False)
else:
self.reduce_cond = None
self.film_mul = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
self.film_add = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim)
self.reduce = nn.Linear(768, reduce_dim)
self.prompt_list = get_prompt_list(prompt)
# precomputed prompts
import pickle
if isfile('precomputed_prompt_vectors.pickle'):
precomp = pickle.load(open('precomputed_prompt_vectors.pickle', 'rb'))
self.precomputed_prompts = {k: torch.from_numpy(v) for k, v in precomp.items()}
else:
self.precomputed_prompts = dict()
def rescaled_pos_emb(self, new_size):
assert len(new_size) == 2
a = self.model.positional_embedding[1:].T.view(1, 768, *self.token_shape)
b = nnf.interpolate(a, new_size, mode='bicubic', align_corners=False).squeeze(0).view(768, new_size[0]*new_size[1]).T
return torch.cat([self.model.positional_embedding[:1], b])
def visual_forward(self, x_inp, extract_layers=(), skip=False, mask=None):
with torch.no_grad():
inp_size = x_inp.shape[2:]
if self.n_tokens is not None:
stride2 = x_inp.shape[2] // self.n_tokens
conv_weight2 = nnf.interpolate(self.model.conv1.weight, (stride2, stride2), mode='bilinear', align_corners=True)
x = nnf.conv2d(x_inp, conv_weight2, bias=self.model.conv1.bias, stride=stride2, dilation=self.model.conv1.dilation)
else:
x = self.model.conv1(x_inp) # shape = [*, width, grid, grid]
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
x = torch.cat([self.model.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
standard_n_tokens = 50 if self.model.conv1.kernel_size[0] == 32 else 197
if x.shape[1] != standard_n_tokens:
new_shape = int(math.sqrt(x.shape[1]-1))
x = x + self.rescaled_pos_emb((new_shape, new_shape)).to(x.dtype)[None,:,:]
else:
x = x + self.model.positional_embedding.to(x.dtype)
x = self.model.ln_pre(x)
x = x.permute(1, 0, 2) # NLD -> LND
activations, affinities = [], []
for i, res_block in enumerate(self.model.transformer.resblocks):
if mask is not None:
mask_layer, mask_type, mask_tensor = mask
if mask_layer == i or mask_layer == 'all':
# import ipdb; ipdb.set_trace()
size = int(math.sqrt(x.shape[0] - 1))
attn_mask = (mask_type, nnf.interpolate(mask_tensor.unsqueeze(1).float(), (size, size)).view(mask_tensor.shape[0], size * size))
else:
attn_mask = None
else:
attn_mask = None
x, aff_per_head = forward_multihead_attention(x, res_block, with_aff=True, attn_mask=attn_mask)
if i in extract_layers:
affinities += [aff_per_head]
#if self.n_tokens is not None:
# activations += [nnf.interpolate(x, inp_size, mode='bilinear', align_corners=True)]
#else:
activations += [x]
if len(extract_layers) > 0 and i == max(extract_layers) and skip:
print('early skip')
break
x = x.permute(1, 0, 2) # LND -> NLD
x = self.model.ln_post(x[:, 0, :])
if self.model.proj is not None:
x = x @ self.model.proj
return x, activations, affinities
def sample_prompts(self, words, prompt_list=None):
prompt_list = prompt_list if prompt_list is not None else self.prompt_list
prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True)
prompts = [prompt_list[i] for i in prompt_indices]
return [promt.format(w) for promt, w in zip(prompts, words)]
def get_cond_vec(self, conditional, batch_size):
# compute conditional from a single string
if conditional is not None and type(conditional) == str:
cond = self.compute_conditional(conditional)
cond = cond.repeat(batch_size, 1)
# compute conditional from string list/tuple
elif conditional is not None and type(conditional) in {list, tuple} and type(conditional[0]) == str:
assert len(conditional) == batch_size
cond = self.compute_conditional(conditional)
# use conditional directly
elif conditional is not None and type(conditional) == torch.Tensor and conditional.ndim == 2:
cond = conditional
# compute conditional from image
elif conditional is not None and type(conditional) == torch.Tensor:
with torch.no_grad():
cond, _, _ = self.visual_forward(conditional)
else:
raise ValueError('invalid conditional')
return cond
def compute_conditional(self, conditional):
from rope.external.cliplib import clip
dev = next(self.parameters()).device
if type(conditional) in {list, tuple}:
text_tokens = clip.tokenize(conditional).to(dev)
cond = self.clip_model.encode_text(text_tokens)
else:
if conditional in self.precomputed_prompts:
cond = self.precomputed_prompts[conditional].float().to(dev)
else:
text_tokens = clip.tokenize([conditional]).to(dev)
cond = self.clip_model.encode_text(text_tokens)[0]
if self.shift_vector is not None:
return cond + self.shift_vector
else:
return cond
def clip_load_untrained(version):
assert version == 'ViT-B/16'
from clip.model import CLIP
from clip.clip import _MODELS, _download
model = torch.jit.load(_download(_MODELS['ViT-B/16'])).eval()
state_dict = model.state_dict()
vision_width = state_dict["visual.conv1.weight"].shape[0]
vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
image_resolution = vision_patch_size * grid_size
embed_dim = state_dict["text_projection"].shape[1]
context_length = state_dict["positional_embedding"].shape[0]
vocab_size = state_dict["token_embedding.weight"].shape[0]
transformer_width = state_dict["ln_final.weight"].shape[0]
transformer_heads = transformer_width // 64
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
return CLIP(embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size,
context_length, vocab_size, transformer_width, transformer_heads, transformer_layers)
class CLIPDensePredT(CLIPDenseBase):
def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, prompt='fixed',
extra_blocks=0, reduce_cond=None, fix_shift=False,
learn_trans_conv_only=False, limit_to_clip_only=False, upsample=False,
add_calibration=False, rev_activations=False, trans_conv=None, n_tokens=None, complex_trans_conv=False):
super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens)
# device = 'cpu'
self.extract_layers = extract_layers
self.cond_layer = cond_layer
self.limit_to_clip_only = limit_to_clip_only
self.process_cond = None
self.rev_activations = rev_activations
depth = len(extract_layers)
if add_calibration:
self.calibration_conds = 1
self.upsample_proj = nn.Conv2d(reduce_dim, 1, kernel_size=1) if upsample else None
self.add_activation1 = True
self.version = version
self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version]
if fix_shift:
# self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'clip_text_shift_vector.pth')), requires_grad=False)
self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'shift_text_to_vis.pth')), requires_grad=False)
# self.shift_vector = nn.Parameter(-1*torch.load(join(dirname(basename(__file__)), 'shift2.pth')), requires_grad=False)
else:
self.shift_vector = None
if trans_conv is None:
trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version]
else:
# explicitly define transposed conv kernel size
trans_conv_ks = (trans_conv, trans_conv)
if not complex_trans_conv:
self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
else:
assert trans_conv_ks[0] == trans_conv_ks[1]
tp_kernels = (trans_conv_ks[0] // 4, trans_conv_ks[0] // 4)
self.trans_conv = nn.Sequential(
nn.Conv2d(reduce_dim, reduce_dim, kernel_size=3, padding=1),
nn.ReLU(),
nn.ConvTranspose2d(reduce_dim, reduce_dim // 2, kernel_size=tp_kernels[0], stride=tp_kernels[0]),
nn.ReLU(),
nn.ConvTranspose2d(reduce_dim // 2, 1, kernel_size=tp_kernels[1], stride=tp_kernels[1]),
)
# self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
assert len(self.extract_layers) == depth
self.reduces = nn.ModuleList([nn.Linear(768, reduce_dim) for _ in range(depth)])
self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(len(self.extract_layers))])
self.extra_blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(extra_blocks)])
# refinement and trans conv
if learn_trans_conv_only:
for p in self.parameters():
p.requires_grad_(False)
for p in self.trans_conv.parameters():
p.requires_grad_(True)
self.prompt_list = get_prompt_list(prompt)
def forward(self, inp_image, conditional=None, return_features=False, mask=None):
assert type(return_features) == bool
inp_image = inp_image.to(self.model.positional_embedding.device)
if mask is not None:
raise ValueError('mask not supported')
# x_inp = normalize(inp_image)
x_inp = inp_image
bs, dev = inp_image.shape[0], x_inp.device
cond = self.get_cond_vec(conditional, bs)
visual_q, activations, _ = self.visual_forward(x_inp, extract_layers=[0] + list(self.extract_layers))
activation1 = activations[0]
activations = activations[1:]
_activations = activations[::-1] if not self.rev_activations else activations
a = None
for i, (activation, block, reduce) in enumerate(zip(_activations, self.blocks, self.reduces)):
if a is not None:
a = reduce(activation) + a
else:
a = reduce(activation)
if i == self.cond_layer:
if self.reduce_cond is not None:
cond = self.reduce_cond(cond)
a = self.film_mul(cond) * a + self.film_add(cond)
a = block(a)
for block in self.extra_blocks:
a = a + block(a)
a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
size = int(math.sqrt(a.shape[2]))
a = a.view(bs, a.shape[1], size, size)
a = self.trans_conv(a)
if self.n_tokens is not None:
a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear', align_corners=True)
if self.upsample_proj is not None:
a = self.upsample_proj(a)
a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear')
if return_features:
return a, visual_q, cond, [activation1] + activations
else:
return a,
class CLIPDensePredTMasked(CLIPDensePredT):
def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4,
prompt='fixed', extra_blocks=0, reduce_cond=None, fix_shift=False, learn_trans_conv_only=False,
refine=None, limit_to_clip_only=False, upsample=False, add_calibration=False, n_tokens=None):
super().__init__(version=version, extract_layers=extract_layers, cond_layer=cond_layer, reduce_dim=reduce_dim,
n_heads=n_heads, prompt=prompt, extra_blocks=extra_blocks, reduce_cond=reduce_cond,
fix_shift=fix_shift, learn_trans_conv_only=learn_trans_conv_only,
limit_to_clip_only=limit_to_clip_only, upsample=upsample, add_calibration=add_calibration,
n_tokens=n_tokens)
def visual_forward_masked(self, img_s, seg_s):
return super().visual_forward(img_s, mask=('all', 'cls_token', seg_s))
def forward(self, img_q, cond_or_img_s, seg_s=None, return_features=False):
if seg_s is None:
cond = cond_or_img_s
else:
img_s = cond_or_img_s
with torch.no_grad():
cond, _, _ = self.visual_forward_masked(img_s, seg_s)
return super().forward(img_q, cond, return_features=return_features)
class CLIPDenseBaseline(CLIPDenseBase):
def __init__(self, version='ViT-B/32', cond_layer=0,
extract_layer=9, reduce_dim=128, reduce2_dim=None, prompt='fixed',
reduce_cond=None, limit_to_clip_only=False, n_tokens=None):
super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens)
device = 'cpu'
# self.cond_layer = cond_layer
self.extract_layer = extract_layer
self.limit_to_clip_only = limit_to_clip_only
self.shift_vector = None
self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version]
assert reduce2_dim is not None
self.reduce2 = nn.Sequential(
nn.Linear(reduce_dim, reduce2_dim),
nn.ReLU(),
nn.Linear(reduce2_dim, reduce_dim)
)
trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version]
self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks)
def forward(self, inp_image, conditional=None, return_features=False):
inp_image = inp_image.to(self.model.positional_embedding.device)
# x_inp = normalize(inp_image)
x_inp = inp_image
bs, dev = inp_image.shape[0], x_inp.device
cond = self.get_cond_vec(conditional, bs)
visual_q, activations, affinities = self.visual_forward(x_inp, extract_layers=[self.extract_layer])
a = activations[0]
a = self.reduce(a)
a = self.film_mul(cond) * a + self.film_add(cond)
if self.reduce2 is not None:
a = self.reduce2(a)
# the original model would execute a transformer block here
a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens
size = int(math.sqrt(a.shape[2]))
a = a.view(bs, a.shape[1], size, size)
a = self.trans_conv(a)
if return_features:
return a, visual_q, cond, activations
else:
return a,
class CLIPSegMultiLabel(nn.Module):
def __init__(self, model) -> None:
super().__init__()
from third_party.JoEm.data_loader import get_seen_idx, get_unseen_idx, VOC
self.pascal_classes = VOC
from models.clipseg import CLIPDensePredT
from general_utils import load_model
# self.clipseg = load_model('rd64-vit16-neg0.2-phrasecut', strict=False)
self.clipseg = load_model(model, strict=False)
self.clipseg.eval()
def forward(self, x):
bs = x.shape[0]
out = torch.ones(21, bs, 352, 352).to(x.device) * -10
for class_id, class_name in enumerate(self.pascal_classes):
fac = 3 if class_name == 'background' else 1
with torch.no_grad():
pred = torch.sigmoid(self.clipseg(x, class_name)[0][:,0]) * fac
out[class_id] += pred
out = out.permute(1, 0, 2, 3)
return out
# construct output tensor
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as modelzoo
# from modules.bn import InPlaceABNSync as BatchNorm2d
resnet18_url = 'https://download.pytorch.org/models/resnet18-5c106cde.pth'
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
def __init__(self, in_chan, out_chan, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(in_chan, out_chan, stride)
self.bn1 = nn.BatchNorm2d(out_chan)
self.conv2 = conv3x3(out_chan, out_chan)
self.bn2 = nn.BatchNorm2d(out_chan)
self.relu = nn.ReLU(inplace=True)
self.downsample = None
if in_chan != out_chan or stride != 1:
self.downsample = nn.Sequential(
nn.Conv2d(in_chan, out_chan,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_chan),
)
def forward(self, x):
residual = self.conv1(x)
residual = F.relu(self.bn1(residual))
residual = self.conv2(residual)
residual = self.bn2(residual)
shortcut = x
if self.downsample is not None:
shortcut = self.downsample(x)
out = shortcut + residual
out = self.relu(out)
return out
def create_layer_basic(in_chan, out_chan, bnum, stride=1):
layers = [BasicBlock(in_chan, out_chan, stride=stride)]
for i in range(bnum-1):
layers.append(BasicBlock(out_chan, out_chan, stride=1))
return nn.Sequential(*layers)
class Resnet18(nn.Module):
def __init__(self):
super(Resnet18, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = create_layer_basic(64, 64, bnum=2, stride=1)
self.layer2 = create_layer_basic(64, 128, bnum=2, stride=2)
self.layer3 = create_layer_basic(128, 256, bnum=2, stride=2)
self.layer4 = create_layer_basic(256, 512, bnum=2, stride=2)
self.init_weight()
def forward(self, x):
x = self.conv1(x)
x = F.relu(self.bn1(x))
x = self.maxpool(x)
x = self.layer1(x)
feat8 = self.layer2(x) # 1/8
feat16 = self.layer3(feat8) # 1/16
feat32 = self.layer4(feat16) # 1/32
return feat8, feat16, feat32
def init_weight(self):
state_dict = modelzoo.load_url(resnet18_url)
self_state_dict = self.state_dict()
for k, v in state_dict.items():
if 'fc' in k: continue
self_state_dict.update({k: v})
self.load_state_dict(self_state_dict)
def get_params(self):
wd_params, nowd_params = [], []
for name, module in self.named_modules():
if isinstance(module, (nn.Linear, nn.Conv2d)):
wd_params.append(module.weight)
if not module.bias is None:
nowd_params.append(module.bias)
elif isinstance(module, nn.BatchNorm2d):
nowd_params += list(module.parameters())
return wd_params, nowd_params
if __name__ == "__main__":
net = Resnet18()
x = torch.randn(16, 3, 224, 224)
out = net(x)
print(out[0].size())
print(out[1].size())
print(out[2].size())
net.get_params()
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 833 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 938 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 948 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 938 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

+238
View File
@@ -0,0 +1,238 @@
import hashlib
import os
from typing import Iterable
import shutil
import subprocess
import re
import server
from .logger import logger
## 这个文件来自,comfyui-videoHelperSuite,除了加print之外没有改动
## all credits go to the original author
BIGMIN = -(2**53-1)
BIGMAX = (2**53-1)
DIMMAX = 8192
def ffmpeg_suitability(path):
try:
version = subprocess.run([path, "-version"], check=True,
capture_output=True).stdout.decode("utf-8")
except:
return 0
score = 0
#rough layout of the importance of various features
simple_criterion = [("libvpx", 20),("264",10), ("265",3),
("svtav1",5),("libopus", 1)]
for criterion in simple_criterion:
if version.find(criterion[0]) >= 0:
score += criterion[1]
#obtain rough compile year from copyright information
copyright_index = version.find('2000-2')
if copyright_index >= 0:
copyright_year = version[copyright_index+6:copyright_index+9]
if copyright_year.isnumeric():
score += int(copyright_year)
return score
if "VHS_FORCE_FFMPEG_PATH" in os.environ:
ffmpeg_path = os.environ.get("VHS_FORCE_FFMPEG_PATH")
else:
ffmpeg_paths = []
try:
from imageio_ffmpeg import get_ffmpeg_exe
imageio_ffmpeg_path = get_ffmpeg_exe()
ffmpeg_paths.append(imageio_ffmpeg_path)
except:
if "VHS_USE_IMAGEIO_FFMPEG" in os.environ:
raise
logger.warn("Failed to import imageio_ffmpeg")
if "VHS_USE_IMAGEIO_FFMPEG" in os.environ:
ffmpeg_path = imageio_ffmpeg_path
else:
system_ffmpeg = shutil.which("ffmpeg")
if system_ffmpeg is not None:
ffmpeg_paths.append(system_ffmpeg)
if os.path.isfile("ffmpeg"):
ffmpeg_paths.append(os.path.abspath("ffmpeg"))
if os.path.isfile("ffmpeg.exe"):
ffmpeg_paths.append(os.path.abspath("ffmpeg.exe"))
if len(ffmpeg_paths) == 0:
logger.error("No valid ffmpeg found.")
ffmpeg_path = None
elif len(ffmpeg_paths) == 1:
#Evaluation of suitability isn't required, can take sole option
#to reduce startup time
ffmpeg_path = ffmpeg_paths[0]
else:
ffmpeg_path = max(ffmpeg_paths, key=ffmpeg_suitability)
gifski_path = os.environ.get("VHS_GIFSKI", None)
if gifski_path is None:
gifski_path = os.environ.get("JOV_GIFSKI", None)
if gifski_path is None:
gifski_path = shutil.which("gifski")
def is_safe_path(path):
if "VHS_STRICT_PATHS" not in os.environ:
return True
basedir = os.path.abspath('.')
try:
common_path = os.path.commonpath([basedir, path])
except:
#Different drive on windows
return False
return common_path == basedir
def get_sorted_dir_files_from_directory(directory: str, skip_first_images: int=0, select_every_nth: int=1, extensions: Iterable=None):
directory = strip_path(directory)
dir_files = os.listdir(directory)
dir_files = sorted(dir_files)
dir_files = [os.path.join(directory, x) for x in dir_files]
dir_files = list(filter(lambda filepath: os.path.isfile(filepath), dir_files))
# filter by extension, if needed
if extensions is not None:
extensions = list(extensions)
new_dir_files = []
for filepath in dir_files:
ext = "." + filepath.split(".")[-1]
if ext.lower() in extensions:
new_dir_files.append(filepath)
dir_files = new_dir_files
# start at skip_first_images
dir_files = dir_files[skip_first_images:]
dir_files = dir_files[0::select_every_nth]
return dir_files
# modified from https://stackoverflow.com/questions/22058048/hashing-a-file-in-python
def calculate_file_hash(filename: str, hash_every_n: int = 1):
#Larger video files were taking >.5 seconds to hash even when cached,
#so instead the modified time from the filesystem is used as a hash
h = hashlib.sha256()
h.update(filename.encode())
h.update(str(os.path.getmtime(filename)).encode())
return h.hexdigest()
prompt_queue = server.PromptServer.instance.prompt_queue
def requeue_workflow_unchecked():
"""Requeues the current workflow without checking for multiple requeues"""
currently_running = prompt_queue.currently_running
(_, _, prompt, extra_data, outputs_to_execute) = next(iter(currently_running.values()))
#Ensure batch_managers are marked stale
prompt = prompt.copy()
for uid in prompt:
if prompt[uid]['class_type'] == 'VHS_BatchManager':
prompt[uid]['inputs']['requeue'] = prompt[uid]['inputs'].get('requeue',0)+1
#execution.py has guards for concurrency, but server doesn't.
#TODO: Check that this won't be an issue
number = -server.PromptServer.instance.number
server.PromptServer.instance.number += 1
prompt_id = str(server.uuid.uuid4())
prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
requeue_guard = [None, 0, 0, {}]
def requeue_workflow(requeue_required=(-1,True)):
assert(len(prompt_queue.currently_running) == 1)
global requeue_guard
(run_number, _, prompt, _, _) = next(iter(prompt_queue.currently_running.values()))
if requeue_guard[0] != run_number:
#Calculate a count of how many outputs are managed by a batch manager
managed_outputs=0
for bm_uid in prompt:
if prompt[bm_uid]['class_type'] == 'VHS_BatchManager':
for output_uid in prompt:
if prompt[output_uid]['class_type'] in ["RopeVideoCombine"]:
for inp in prompt[output_uid]['inputs'].values():
if inp == [bm_uid, 0]:
managed_outputs+=1
requeue_guard = [run_number, 0, managed_outputs, {}]
requeue_guard[1] = requeue_guard[1]+1
requeue_guard[3][requeue_required[0]] = requeue_required[1]
if requeue_guard[1] == requeue_guard[2] and max(requeue_guard[3].values()):
requeue_workflow_unchecked()
def get_audio(file, start_time=0, duration=0):
args = [ffmpeg_path, "-v", "error", "-i", file]
if start_time > 0:
args += ["-ss", str(start_time)]
if duration > 0:
args += ["-t", str(duration)]
try:
res = subprocess.run(args + ["-f", "wav", "-"],
stdout=subprocess.PIPE, check=True).stdout
except subprocess.CalledProcessError as e:
logger.warning(f"Failed to extract audio from: {file}")
return False
return res
def lazy_eval(func):
class Cache:
def __init__(self, func):
self.res = None
self.func = func
def get(self):
if self.res is None:
self.res = self.func()
return self.res
cache = Cache(func)
return lambda : cache.get()
def is_url(url):
return url.split("://")[0] in ["http", "https"]
def validate_sequence(path):
#Check if path is a valid ffmpeg sequence that points to at least one file
(path, file) = os.path.split(path)
if not os.path.isdir(path):
return False
match = re.search('%0?\\d+d', file)
if not match:
return False
seq = match.group()
if seq == '%d':
seq = '\\\\d+'
else:
seq = '\\\\d{%s}' % seq[1:-1]
file_matcher = re.compile(re.sub('%0?\\d+d', seq, file))
for file in os.listdir(path):
if file_matcher.fullmatch(file):
return True
return False
def strip_path(path):
#This leaves whitespace inside quotes and only a single "
#thus ' ""test"' -> '"test'
#consider path.strip(string.whitespace+"\"")
#or weightier re.fullmatch("[\\s\"]*(.+?)[\\s\"]*", path).group(1)
path = path.strip()
if path.startswith("\""):
path = path[1:]
if path.endswith("\""):
path = path[:-1]
return path
def hash_path(path):
if path is None:
return "input"
if is_url(path):
return "url"
return calculate_file_hash(strip_path(path))
def validate_path(path, allow_none=False, allow_url=True):
if path is None:
return allow_none
if is_url(path):
#Probably not feasible to check if url resolves here
if not allow_url:
return "URLs are unsupported for this path"
return is_safe_path(path)
if not os.path.isfile(strip_path(path)):
return "Invalid file path: {}".format(path)
return is_safe_path(path)
+565
View File
@@ -0,0 +1,565 @@
## 这个文件来自,comfyui-videoHelperSuite,除了加print之外没有改动
## all credits go to the original author
import os
import sys
import json
import subprocess
import numpy as np
import re
import datetime
from typing import List
import torch
from PIL import Image, ExifTags
from PIL.PngImagePlugin import PngInfo
from pathlib import Path
from string import Template
import itertools
import folder_paths
from .utils import ffmpeg_path, get_audio, hash_path, validate_path, requeue_workflow, gifski_path, calculate_file_hash, strip_path
from comfy.utils import ProgressBar
folder_paths.folder_names_and_paths["VHS_video_formats"] = (
[
os.path.join(os.path.dirname(os.path.abspath(__file__)), "video_formats"),
],
[".json"]
)
audio_extensions = ['mp3', 'mp4', 'wav', 'ogg']
def gen_format_widgets(video_format):
for k in video_format:
if k.endswith("_pass"):
for i in range(len(video_format[k])):
if isinstance(video_format[k][i], list):
item = [video_format[k][i]]
yield item
video_format[k][i] = item[0]
else:
if isinstance(video_format[k], list):
item = [video_format[k]]
yield item
video_format[k] = item[0]
def get_video_formats():
formats = []
for format_name in folder_paths.get_filename_list("VHS_video_formats"):
format_name = format_name[:-5]
video_format_path = folder_paths.get_full_path("VHS_video_formats", format_name + ".json")
with open(video_format_path, 'r') as stream:
video_format = json.load(stream)
if "gifski_pass" in video_format and gifski_path is None:
#Skip format
continue
widgets = [w[0] for w in gen_format_widgets(video_format)]
if (len(widgets) > 0):
formats.append(["video/" + format_name, widgets])
else:
formats.append("video/" + format_name)
return formats
def get_format_widget_defaults(format_name):
video_format_path = folder_paths.get_full_path("VHS_video_formats", format_name + ".json")
with open(video_format_path, 'r') as stream:
video_format = json.load(stream)
results = {}
for w in gen_format_widgets(video_format):
if len(w[0]) > 2 and 'default' in w[0][2]:
default = w[0][2]['default']
else:
if type(w[0][1]) is list:
default = w[0][1][0]
else:
#NOTE: This doesn't respect max/min, but should be good enough as a fallback to a fallback to a fallback
default = {"BOOLEAN": False, "INT": 0, "FLOAT": 0, "STRING": ""}[w[0][1]]
results[w[0][0]] = default
return results
def apply_format_widgets(format_name, kwargs):
video_format_path = folder_paths.get_full_path("VHS_video_formats", format_name + ".json")
with open(video_format_path, 'r') as stream:
video_format = json.load(stream)
for w in gen_format_widgets(video_format):
assert(w[0][0] in kwargs)
if len(w[0]) > 3:
w[0] = Template(w[0][3]).substitute(val=kwargs[w[0][0]])
else:
w[0] = str(kwargs[w[0][0]])
return video_format
def tensor_to_int(tensor, bits):
#TODO: investigate benefit of rounding by adding 0.5 before clip/cast
tensor = tensor.cpu().numpy() * (2**bits-1)
return np.clip(tensor, 0, (2**bits-1))
def tensor_to_shorts(tensor):
return tensor_to_int(tensor, 16).astype(np.uint16)
def tensor_to_bytes(tensor):
return tensor_to_int(tensor, 8).astype(np.uint8)
def ffmpeg_process(args, video_format, video_metadata, file_path, env):
# print("in ffmpeg_process")
# print("args:", args)
# print("video_format:",video_format)
# print("video_metadata:",video_metadata)
# print("file_path:",file_path)
# print("env:",env)
res = None
frame_data = yield
total_frames_output = 0
if video_format.get('save_metadata', 'False') != 'False':
os.makedirs(folder_paths.get_temp_directory(), exist_ok=True)
metadata = json.dumps(video_metadata)
metadata_path = os.path.join(folder_paths.get_temp_directory(), "metadata.txt")
#metadata from file should escape = ; # \ and newline
metadata = metadata.replace("\\","\\\\")
metadata = metadata.replace(";","\\;")
metadata = metadata.replace("#","\\#")
metadata = metadata.replace("=","\\=")
metadata = metadata.replace("\n","\\\n")
metadata = "comment=" + metadata
with open(metadata_path, "w") as f:
f.write(";FFMETADATA1\n")
f.write(metadata)
m_args = args[:1] + ["-i", metadata_path] + args[1:] + ["-metadata", "creation_time=now"]
with subprocess.Popen(m_args + [file_path], stderr=subprocess.PIPE,
stdin=subprocess.PIPE, env=env) as proc:
try:
while frame_data is not None:
proc.stdin.write(frame_data)
#TODO: skip flush for increased speed
frame_data = yield
total_frames_output+=1
proc.stdin.flush()
proc.stdin.close()
res = proc.stderr.read()
except BrokenPipeError as e:
err = proc.stderr.read()
#Check if output file exists. If it does, the re-execution
#will also fail. This obscures the cause of the error
#and seems to never occur concurrent to the metadata issue
if os.path.exists(file_path):
raise Exception("An error occurred in the ffmpeg subprocess:\n" \
+ err.decode("utf-8"))
#Res was not set
print(err.decode("utf-8"), end="", file=sys.stderr)
print("An error occurred when saving with metadata")
if res != b'':
with subprocess.Popen(args + [file_path], stderr=subprocess.PIPE,
stdin=subprocess.PIPE, env=env) as proc:
try:
while frame_data is not None:
proc.stdin.write(frame_data)
frame_data = yield
total_frames_output+=1
proc.stdin.flush()
proc.stdin.close()
res = proc.stderr.read()
except BrokenPipeError as e:
res = proc.stderr.read()
raise Exception("An error occurred in the ffmpeg subprocess:\n" \
+ res.decode("utf-8"))
yield total_frames_output
if len(res) > 0:
print(res.decode("utf-8"), end="", file=sys.stderr)
def gifski_process(args, video_format, file_path, env):
frame_data = yield
with subprocess.Popen(args + video_format['main_pass'] + ['-f', 'yuv4mpegpipe', '-'],
stderr=subprocess.PIPE, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, env=env) as procff:
with subprocess.Popen([gifski_path] + video_format['gifski_pass']
+ ['-q', '-o', file_path, '-'], stderr=subprocess.PIPE,
stdin=procff.stdout, stdout=subprocess.PIPE,
env=env) as procgs:
try:
while frame_data is not None:
procff.stdin.write(frame_data)
frame_data = yield
procff.stdin.flush()
procff.stdin.close()
resff = procff.stderr.read()
resgs = procgs.stderr.read()
outgs = procgs.stdout.read()
except BrokenPipeError as e:
procff.stdin.close()
resff = procff.stderr.read()
resgs = procgs.stderr.read()
raise Exception("An error occurred while creating gifski output\n" \
+ "Make sure you are using gifski --version >=1.32.0\nffmpeg: " \
+ resff.decode("utf-8") + '\ngifski: ' + resgs.decode("utf-8"))
if len(resff) > 0:
print(resff.decode("utf-8"), end="", file=sys.stderr)
if len(resgs) > 0:
print(resgs.decode("utf-8"), end="", file=sys.stderr)
#should always be empty as the quiet flag is passed
if len(outgs) > 0:
print(outgs.decode("utf-8"))
def to_pingpong(inp):
if not hasattr(inp, "__getitem__"):
inp = list(inp)
yield from inp
for i in range(len(inp)-2,0,-1):
yield inp[i]
class RopeVideoCombine:
@classmethod
def INPUT_TYPES(s):
ffmpeg_formats = get_video_formats()
return {
"required": {
"frame_rate": (
"FLOAT",
{"default": 8, "min": 1, "step": 1},
),
"loop_count": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
"filename_prefix": ("STRING", {"default": "RopeHahahaha"}),
"format": (["image/gif", "image/webp"] + ffmpeg_formats,),
"pingpong": ("BOOLEAN", {"default": False}),
"save_output": ("BOOLEAN", {"default": True}),
},
"optional": {
"images": ("IMAGE",),
"audio": ("VHS_AUDIO",),
"meta_batch": ("VHS_BatchManager",),
"vae": ("VAE",),
"latents": ("LATENT",),
},
"hidden": {
"prompt": "PROMPT",
"extra_pnginfo": "EXTRA_PNGINFO",
"unique_id": "UNIQUE_ID"
},
}
RETURN_TYPES = ("VHS_FILENAMES",)
RETURN_NAMES = ("Filenames",)
OUTPUT_NODE = True
CATEGORY = "RopeWrapper"
FUNCTION = "combine_video"
def combine_video(
self,
frame_rate: int,
loop_count: int,
images=None,
latents=None,
filename_prefix="RopeHahahaha",
format="image/gif",
pingpong=False,
save_output=True,
prompt=None,
extra_pnginfo=None,
audio=None,
unique_id=None,
manual_format_widgets=None,
meta_batch=None,
vae=None
):
if latents is not None:
images = latents
if images is None:
return ((save_output, []),)
if vae is not None:
if isinstance(images, dict):
images = images['samples']
else:
vae = None
if isinstance(images, torch.Tensor) and images.size(0) == 0:
return ((save_output, []),)
num_frames = len(images)
pbar = ProgressBar(num_frames)
if vae is not None:
downscale_ratio = getattr(vae, "downscale_ratio", 8)
width = images.size(3)*downscale_ratio
height = images.size(2)*downscale_ratio
frames_per_batch = (1920 * 1080 * 16) // (width * height) or 1
#Python 3.12 adds an itertools.batched, but it's easily replicated for legacy support
def batched(it, n):
while batch := tuple(itertools.islice(it, n)):
yield batch
def batched_encode(images, vae, frames_per_batch):
for batch in batched(iter(images), frames_per_batch):
image_batch = torch.from_numpy(np.array(batch))
yield from vae.decode(image_batch)
images = batched_encode(images, vae, frames_per_batch)
first_image = next(images)
#repush first_image
images = itertools.chain([first_image], images)
else:
first_image = images[0]
images = iter(images)
# get output information
output_dir = (
folder_paths.get_output_directory()
if save_output
else folder_paths.get_temp_directory()
)
(
full_output_folder,
filename,
_,
subfolder,
_,
) = folder_paths.get_save_image_path(filename_prefix, output_dir)
output_files = []
metadata = PngInfo()
video_metadata = {}
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
video_metadata["prompt"] = prompt
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
video_metadata[x] = extra_pnginfo[x]
metadata.add_text("CreationTime", datetime.datetime.now().isoformat(" ")[:19])
if meta_batch is not None and unique_id in meta_batch.outputs:
(counter, output_process) = meta_batch.outputs[unique_id]
else:
# comfy counter workaround
max_counter = 0
# Loop through the existing files
matcher = re.compile(f"{re.escape(filename)}_(\\d+)\\D*\\..+", re.IGNORECASE)
for existing_file in os.listdir(full_output_folder):
# Check if the file matches the expected format
match = matcher.fullmatch(existing_file)
if match:
# Extract the numeric portion of the filename
file_counter = int(match.group(1))
# Update the maximum counter value if necessary
if file_counter > max_counter:
max_counter = file_counter
# Increment the counter by 1 to get the next available value
counter = max_counter + 1
output_process = None
# save first frame as png to keep metadata
file = f"{filename}_{counter:05}.png"
file_path = os.path.join(full_output_folder, file)
Image.fromarray(tensor_to_bytes(first_image)).save(
file_path,
pnginfo=metadata,
compress_level=4,
)
output_files.append(file_path)
format_type, format_ext = format.split("/")
if format_type == "image":
if meta_batch is not None:
raise Exception("Pillow('image/') formats are not compatible with batched output")
image_kwargs = {}
if format_ext == "gif":
image_kwargs['disposal'] = 2
if format_ext == "webp":
#Save timestamp information
exif = Image.Exif()
exif[ExifTags.IFD.Exif] = {36867: datetime.datetime.now().isoformat(" ")[:19]}
image_kwargs['exif'] = exif
file = f"{filename}_{counter:05}.{format_ext}"
file_path = os.path.join(full_output_folder, file)
if pingpong:
images = to_pingpong(images)
frames = map(lambda x : Image.fromarray(tensor_to_bytes(x)), images)
# Use pillow directly to save an animated image
next(frames).save(
file_path,
format=format_ext.upper(),
save_all=True,
append_images=frames,
duration=round(1000 / frame_rate),
loop=loop_count,
compress_level=4,
**image_kwargs
)
output_files.append(file_path)
else:
# Use ffmpeg to save a video
if ffmpeg_path is None:
raise ProcessLookupError(f"ffmpeg is required for video outputs and could not be found.\nIn order to use video outputs, you must either:\n- Install imageio-ffmpeg with pip,\n- Place a ffmpeg executable in {os.path.abspath('')}, or\n- Install ffmpeg and add it to the system path.")
#Acquire additional format_widget values
kwargs = None
if manual_format_widgets is None:
if prompt is not None:
kwargs = prompt[unique_id]['inputs']
else:
manual_format_widgets = {}
if kwargs is None:
kwargs = get_format_widget_defaults(format_ext)
missing = {}
for k in kwargs.keys():
if k in manual_format_widgets:
kwargs[k] = manual_format_widgets[k]
else:
missing[k] = kwargs[k]
if len(missing) > 0:
print("Extra format values were not provided, the following defaults will be used: " + str(kwargs) + "\nThis is likely due to usage of ComfyUI-to-python. These values can be manually set by supplying a manual_format_widgets argument")
video_format = apply_format_widgets(format_ext, kwargs)
has_alpha = first_image.shape[-1] == 4
dim_alignment = video_format.get("dim_alignment", 8)
if (first_image.shape[1] % dim_alignment) or (first_image.shape[0] % dim_alignment):
#output frames must be padded
to_pad = (-first_image.shape[1] % dim_alignment,
-first_image.shape[0] % dim_alignment)
padding = (to_pad[0]//2, to_pad[0] - to_pad[0]//2,
to_pad[1]//2, to_pad[1] - to_pad[1]//2)
padfunc = torch.nn.ReplicationPad2d(padding)
def pad(image):
image = image.permute((2,0,1))#HWC to CHW
padded = padfunc(image.to(dtype=torch.float32))
return padded.permute((1,2,0))
images = map(pad, images)
new_dims = (-first_image.shape[1] % dim_alignment + first_image.shape[1],
-first_image.shape[0] % dim_alignment + first_image.shape[0])
dimensions = f"{new_dims[0]}x{new_dims[1]}"
print("Output images were not of valid resolution and have had padding applied")
else:
dimensions = f"{first_image.shape[1]}x{first_image.shape[0]}"
if loop_count > 0:
loop_args = ["-vf", "loop=loop=" + str(loop_count)+":size=" + str(num_frames)]
else:
loop_args = []
if pingpong:
if meta_batch is not None:
print("pingpong is incompatible with batched output")
images = to_pingpong(images)
if video_format.get('input_color_depth', '8bit') == '16bit':
images = map(tensor_to_shorts, images)
if has_alpha:
i_pix_fmt = 'rgba64'
else:
i_pix_fmt = 'rgb48'
else:
images = map(tensor_to_bytes, images)
if has_alpha:
i_pix_fmt = 'rgba'
else:
i_pix_fmt = 'rgb24'
file = f"{filename}_{counter:05}.{video_format['extension']}"
file_path = os.path.join(full_output_folder, file)
bitrate_arg = []
bitrate = video_format.get('bitrate')
if bitrate is not None:
bitrate_arg = ["-b:v", str(bitrate) + "M" if video_format.get('megabit') == 'True' else str(bitrate) + "K"]
args = [ffmpeg_path, "-v", "error", "-f", "rawvideo", "-pix_fmt", i_pix_fmt,
"-s", dimensions, "-r", str(frame_rate), "-i", "-"] \
+ loop_args
images = map(lambda x: x.tobytes(), images)
env=os.environ.copy()
if "environment" in video_format:
env.update(video_format["environment"])
if "pre_pass" in video_format:
if meta_batch is not None:
#Performing a prepass requires keeping access to all frames.
#Potential solutions include keeping just output frames in
#memory or using 3 passes with intermediate file, but
#very long gifs probably shouldn't be encouraged
raise Exception("Formats which require a pre_pass are incompatible with Batch Manager.")
images = [b''.join(images)]
os.makedirs(folder_paths.get_temp_directory(), exist_ok=True)
pre_pass_args = args[:13] + video_format['pre_pass']
try:
subprocess.run(pre_pass_args, input=images[0], env=env,
capture_output=True, check=True)
except subprocess.CalledProcessError as e:
raise Exception("An error occurred in the ffmpeg prepass:\n" \
+ e.stderr.decode("utf-8"))
if "inputs_main_pass" in video_format:
args = args[:13] + video_format['inputs_main_pass'] + args[13:]
if output_process is None:
if 'gifski_pass' in video_format:
output_process = gifski_process(args, video_format, file_path, env)
else:
args += video_format['main_pass'] + bitrate_arg
output_process = ffmpeg_process(args, video_format, video_metadata, file_path, env)
#Proceed to first yield
output_process.send(None)
if meta_batch is not None:
meta_batch.outputs[unique_id] = (counter, output_process)
for image in images:
pbar.update(1)
output_process.send(image)
if meta_batch is not None:
requeue_workflow((meta_batch.unique_id, not meta_batch.has_closed_inputs))
if meta_batch is None or meta_batch.has_closed_inputs:
#Close pipe and wait for termination.
try:
total_frames_output = output_process.send(None)
output_process.send(None)
except StopIteration:
pass
if meta_batch is not None:
meta_batch.outputs.pop(unique_id)
if len(meta_batch.outputs) == 0:
meta_batch.reset()
else:
#batch is unfinished
#TODO: Check if empty output breaks other custom nodes
return {"ui": {"unfinished_batch": [True]}, "result": ((save_output, []),)}
output_files.append(file_path)
if audio is not None and audio() is not False:
# Create audio file if input was provided
output_file_with_audio = f"{filename}_{counter:05}-audio.{video_format['extension']}"
output_file_with_audio_path = os.path.join(full_output_folder, output_file_with_audio)
if "audio_pass" not in video_format:
logger.warn("Selected video format does not have explicit audio support")
video_format["audio_pass"] = ["-c:a", "libopus"]
# FFmpeg command with audio re-encoding
#TODO: expose audio quality options if format widgets makes it in
#Reconsider forcing apad/shortest
min_audio_dur = total_frames_output / frame_rate + 1
mux_args = [ffmpeg_path, "-v", "error", "-n", "-i", file_path,
"-i", "-", "-c:v", "copy"] \
+ video_format["audio_pass"] \
+ ["-af", "apad=whole_dur="+str(min_audio_dur),
"-shortest", output_file_with_audio_path]
try:
res = subprocess.run(mux_args, input=audio(), env=env,
capture_output=True, check=True)
except subprocess.CalledProcessError as e:
raise Exception("An error occured in the ffmpeg subprocess:\n" \
+ e.stderr.decode("utf-8"))
if res.stderr:
print(res.stderr.decode("utf-8"), end="", file=sys.stderr)
output_files.append(output_file_with_audio_path)
#Return this file with audio to the webui.
#It will be muted unless opened or saved with right click
file = output_file_with_audio
previews = [
{
"filename": file,
"subfolder": subfolder,
"type": "output" if save_output else "temp",
"format": format,
"frame_rate": frame_rate,
}
]
if num_frames == 1 and 'png' in format and '%03d' in file:
previews[0]['format'] = 'image/png'
previews[0]['filename'] = file.replace('%03d', '001')
#print(previews)
#print("save_output:",save_output)
#print("output_files:",output_files)
return {"ui": {"gifs": previews}, "result": ((save_output, output_files),)}
@classmethod
def VALIDATE_INPUTS(self, format, **kwargs):
return True
+9
View File
@@ -0,0 +1,9 @@
{
"main_pass":
[
"-n",
"-pix_fmt", "rgba64"
],
"input_color_depth": "16bit",
"extension": "%03d.png"
}
+7
View File
@@ -0,0 +1,7 @@
{
"main_pass":
[
"-n"
],
"extension": "%03d.png"
}
+10
View File
@@ -0,0 +1,10 @@
{
"main_pass":
[
"-n", "-c:v", "prores_ks",
"-profile:v","3",
"-pix_fmt", "yuv422p10"
],
"audio_pass": ["-c:a", "pcm_s16le"],
"extension": "mov"
}
+13
View File
@@ -0,0 +1,13 @@
{
"main_pass":
[
"-n", "-c:v", "libsvtav1",
"-pix_fmt", ["pix_fmt", ["yuv420p10le", "yuv420p"]],
"-crf", ["crf","INT", {"default": 23, "min": 0, "max": 100, "step": 1}]
],
"audio_pass": ["-c:a", "libopus"],
"input_color_depth": ["input_color_depth", ["8bit", "16bit"]],
"save_metadata": ["save_metadata", "BOOLEAN", {"default": true}],
"extension": "webm",
"environment": {"SVT_LOG": "1"}
}
+8
View File
@@ -0,0 +1,8 @@
{
"main_pass":
[
"-n",
"-filter_complex", ["dither", ["bayer", "heckbert", "floyd_steinberg", "sierra2", "sierra2_4a", "sierra3", "burkes", "atkinson", "none"], {"default": "sierra2_4a"}, "[0:v] split [a][b]; [a] palettegen=reserve_transparent=on:transparency_color=ffffff [p]; [b][p] paletteuse=dither=$val"]
],
"extension": "gif"
}
+10
View File
@@ -0,0 +1,10 @@
{
"main_pass":
[
"-pix_fmt", "yuv420p"
],
"extension": "gif",
"gifski_pass": [
"-Q", ["quality","INT", {"default": 90, "min": 1, "max": 100, "step": 1}]
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"main_pass":
[
"-n", "-c:v", "libx264",
"-pix_fmt", ["pix_fmt", ["yuv420p", "yuv420p10le"]],
"-crf", ["crf","INT", {"default": 19, "min": 0, "max": 100, "step": 1}]
],
"audio_pass": ["-c:a", "aac"],
"save_metadata": ["save_metadata", "BOOLEAN", {"default": true}],
"extension": "mp4"
}
+14
View File
@@ -0,0 +1,14 @@
{
"main_pass":
[
"-n", "-c:v", "libx265",
"-vtag", "hvc1",
"-pix_fmt", ["pix_fmt", ["yuv420p10le", "yuv420p"]],
"-crf", ["crf","INT", {"default": 22, "min": 0, "max": 100, "step": 1}],
"-preset", "medium",
"-x265-params", "log-level=quiet"
],
"audio_pass": ["-c:a", "aac"],
"save_metadata": ["save_metadata", "BOOLEAN", {"default": true}],
"extension": "mp4"
}
+12
View File
@@ -0,0 +1,12 @@
{
"main_pass":
[
"-n", "-c:v", "h264_nvenc",
"-pix_fmt", ["pix_fmt", ["yuv420p", "yuv420p10le"]]
],
"audio_pass": ["-c:a", "aac"],
"bitrate": ["bitrate","INT", {"default": 10, "min": 1, "max": 999, "step": 1 }],
"megabit": ["megabit","BOOLEAN", {"default": true}],
"save_metadata": ["save_metadata", "BOOLEAN", {"default": true}],
"extension": "mp4"
}
+13
View File
@@ -0,0 +1,13 @@
{
"main_pass":
[
"-n", "-c:v", "hevc_nvenc",
"-vtag", "hvc1",
"-pix_fmt", ["pix_fmt", ["yuv420p", "yuv420p10le"]]
],
"audio_pass": ["-c:a", "aac"],
"bitrate": ["bitrate","INT", {"default": 10, "min": 1, "max": 999, "step": 1 }],
"megabit": ["megabit","BOOLEAN", {"default": true}],
"save_metadata": ["save_metadata", "BOOLEAN", {"default": true}],
"extension": "mp4"
}
+12
View File
@@ -0,0 +1,12 @@
{
"main_pass":
[
"-n",
"-pix_fmt", "yuv420p",
"-crf", ["crf","INT", {"default": 20, "min": 0, "max": 100, "step": 1}],
"-b:v", "0"
],
"audio_pass": ["-c:a", "libvorbis"],
"save_metadata": ["save_metadata", "BOOLEAN", {"default": true}],
"extension": "webm"
}