Upload 33 files
Browse filesFiles changed (33)
- sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/bug_report.ymlAdded+58
- sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/config.ymlAdded+5
- sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/feature_request.ymlAdded+16
- sd-webui-reactor-main/sd-webui-reactor-main/.gitignoreAdded+10
- sd-webui-reactor-main/sd-webui-reactor-main/API.mdAdded+71
- sd-webui-reactor-main/sd-webui-reactor-main/LICENSEAdded+661
- sd-webui-reactor-main/sd-webui-reactor-main/README.mdAdded+361
- sd-webui-reactor-main/sd-webui-reactor-main/README_RU.mdAdded+370
- sd-webui-reactor-main/sd-webui-reactor-main/example/IamSFW.jpgAdded
- sd-webui-reactor-main/sd-webui-reactor-main/example/api_example.pyAdded+103
- sd-webui-reactor-main/sd-webui-reactor-main/example/api_external.curlAdded
- sd-webui-reactor-main/sd-webui-reactor-main/example/api_external.jsonAdded
- sd-webui-reactor-main/sd-webui-reactor-main/example/insightface-0.7.3-cp310-cp310-win_amd64.whlAdded
- sd-webui-reactor-main/sd-webui-reactor-main/install.pyAdded+147
- sd-webui-reactor-main/sd-webui-reactor-main/reactor_modules/reactor_mask.pyAdded+176
- sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/__init__.pyAdded+4
- sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_main_ui.pyAdded+182
- sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_settings_ui.pyAdded+77
- sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_tools_ui.pyAdded+25
- sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_upscale_ui.pyAdded+39
- sd-webui-reactor-main/sd-webui-reactor-main/requirements.txtAdded+3
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/console_log_patch.pyAdded+120
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_api.pyAdded+118
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_entities/face.pyAdded+147
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_entities/rect.pyAdded+78
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_faceswap.pyAdded+577
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_globals.pyAdded+40
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_helpers.pyAdded+209
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_inferencers/bisenet_mask_generator.pyAdded+86
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_inferencers/mask_generator.pyAdded+36
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_logger.pyAdded+55
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_swapper.pyAdded+715
- sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_version.pyAdded+10
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758name: Bug Reportdescription: You think somethings is brokenlabels: ["bug", "new"]
body: - type: checkboxes attributes: label: First, confirm description: Make sure you use the latest version of the ReActor extension and you have already searched to see if an issue already exists for the bug you encountered before you create a new Issue. options: - label: I have read the [instruction](https://github.com/Gourieff/sd-webui-reactor/blob/main/README.md) carefully required: true - label: I have searched the existing issues required: true - label: I have updated the extension to the latest version required: true - type: markdown attributes: value: | *Please fill this form with as much information as possible and *provide screenshots if possible** - type: textarea id: what-did attributes: label: What happened? description: Tell what happened in a very clear and simple way validations: required: true - type: textarea id: steps attributes: label: Steps to reproduce the problem description: Please provide with precise step by step instructions on how to reproduce the bug value: | 1. Go to .... 2. Press .... 3. ... validations: required: true - type: textarea id: sysinfo attributes: label: Sysinfo description: Describe your platform. OS, browser, GPU, what SD WebUI you use, what version and what extensions are also enabled. If you use A1111 you can generate "System info file" (Settings -> Sysinfo) and put it here. validations: required: true - type: textarea id: logs attributes: label: Relevant console log description: Please provide cmd/terminal logs from the moment you started UI to the momemt you got an error. This will be automatically formatted into code, so no need for backticks. render: Shell validations: required: true - type: textarea id: misc attributes: label: Additional information description: Please provide with any relevant additional info or context.12345blank_issues_enabled: falsecontact_links: - name: ReActor Extension Community Support url: https://github.com/Gourieff/sd-webui-reactor/discussions about: Please ask and answer questions here.12345678910111213141516name: Feature requestdescription: Suggest an idea for this projecttitle: "[Feature]: "labels: ["enhancement", "new"]
body: - type: textarea id: description attributes: label: Feature description description: Describe the feature in a clear and simple way value: - type: markdown attributes: value: | The best way to propose an idea is to start a new discussion via the [Discussions](https://github.com/Gourieff/sd-webui-reactor/discussions) section (choose the "Idea" category)12345678910__pycache__/*.py[cod]*$py.class*.pyc
.vscode/
example*.txt!requirements.txt1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# <div align="center">ReActor Extension API</div>
<div align="center">
[Built-in SD WebUI API](#built-in-sd-webui-api) | [External ReActor API](#external-reactor-api)
---</div>
Gourieff's **ReActor** SD WebUI Extension allows to operate via API: both built-in and external (POST and GET requests).
## Built-in SD WebUI API
This API is actual if you use Automatic1111 stable-diffusion-webui.
First of all - check the [SD Web API Wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/API) for how to use the API.
* Call `requests.get(url=f'{address}/sdapi/v1/script-info')` to find the args that ReActor needs;* Define ReActor script args and add like this `"alwayson_scripts": {"reactor":{"args":args}}` in the payload;* Call the API.
You can find the [full usage example](./example/api_example.py) with all the available parameters and discriptions in the "example" folder.
## External ReActor API
ReActor extension supports for external calls via POST or GET requests while your SD WebUI server is working.
> :warning: Source and Target images must be "base64".
Example:
```curl -X POST \ 'http://127.0.0.1:7860/reactor/image' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "source_image": "data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABQAAD/7g...", "target_image": "data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABCAAD/7g...", "source_faces_index": [0], "face_index": [0], "upscaler": "4x_Struzan_300000", "scale": 2, "upscale_visibility": 1, "face_restorer": "CodeFormer", "restorer_visibility": 1, "restore_first": 1, "model": "inswapper_128.onnx", "gender_source": 0, "gender_target": 0, "save_to_file": 0, "result_file_path": "" }'```
* Set `"upscaler"` to `"None"` and `"scale"` to `1` if you don't need to upscale;* Set `"save_to_file"` to `1` if you need to save result to a file;* `"result_file_path"` is set to the `"outputs/api"` folder by default (please, create the folder beforehand to avoid any errors) with a timestamped filename; (output_YYYY-MM-DD_hh-mm-ss), you can set any specific path, e.g. `"C:/stable-diffusion-webui/outputs/api/output.png"`.
You can find full usage examples with all the available parameters in the "example" folder: [cURL](./example/api_external.curl), [JSON](./example/api_external.json).
As a result you recieve a "base64" image:
```{"image":"iVBORw0KGgoAAAANSUhEUgAABlAAAARQCAIAAAAdiYuqAAEAAElEQVR4nOz9+ZMlSXImBn6qau4vIjKzzr5wzwBCDrm/7f+/K7IHV3ZkhUIuyZHlkBhiMGig0Y0..."}```
A list of available models can be seen by GET:* http://127.0.0.1:7860/reactor/models* http://127.0.0.1:7860/reactor/upscalers123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 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 Affero General Public License is a free, copyleft license forsoftware and other kinds of works, specifically designed to ensurecooperation with the community in the case of network server software.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,our General Public Licenses are intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rightswith two steps: (1) assert copyright on the software, and (2) offeryou this License which gives you legal permission to copy, distributeand/or modify the software.
A secondary benefit of defending all users' freedom is thatimprovements made in alternate versions of the program, if theyreceive widespread use, become available for other developers toincorporate. Many developers of free software are heartened andencouraged by the resulting cooperation. However, in the case ofsoftware used on network servers, this result may fail to come about.The GNU General Public License permits making a modified version andletting the public access it on a server without ever releasing itssource code to the public.
The GNU Affero General Public License is designed specifically toensure that, in such cases, the modified source code becomes availableto the community. It requires the operator of a network server toprovide the source code of the modified version running there to theusers of that server. Therefore, public use of a modified version, ona publicly accessible server, gives the public access to the sourcecode of the modified version.
An older license, called the Affero General Public License andpublished by Affero, was designed to accomplish similar goals. This isa different license, not a version of the Affero GPL, but Affero hasreleased a new version of the Affero GPL which permits relicensing underthis license.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. 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 workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha 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 visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation 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 toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients 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 toproduce it from the Program, in the form of source code under theterms 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 independentworks, 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 notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-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 excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe 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 installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional 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 youadd to a covered work, you may (if authorized by the copyright holders ofthat 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 "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform 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 expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered 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 automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent 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 anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain 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 limitingany implied license or other defenses to infringement that mayotherwise 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 orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify theProgram, your modified version must prominently offer all usersinteracting with it remotely through a computer network (if your versionsupports such interaction) an opportunity to receive the CorrespondingSource of your version by providing access to the Corresponding Sourcefrom a network server at no charge, through some standard or customarymeans of facilitating copying of software. This Corresponding Sourceshall include the Corresponding Source for any work covered by version 3of the GNU General Public License that is incorporated pursuant to thefollowing paragraph.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the work with which it is combined will remain governed by version3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU Affero General Public License from time to time. Such new versionswill be similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU Affero GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU Affero General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU Affero General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES 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 OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy 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 greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computernetwork, you should also make sure that it provides a way for users toget its source. For example, if your program is a web application, itsinterface could display a "Source" link that leads users to an archiveof the code. There are many ways you could offer source, and differentsolutions will be better for different programs; see section 13 for thespecific requirements.
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 AGPL, see<https://www.gnu.org/licenses/>.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361<div align="center">
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_EN.png?raw=true" alt="logo" width="180px"/>  <a href="https://boosty.to/artgourieff" target="_blank"> <img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/> <br> <sup> Support This Project </sup> </a>
<hr> [](https://github.com/Gourieff/sd-webui-reactor/commits/main)  [](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0) [](https://github.com/Gourieff/sd-webui-reactor/issues?q=is%3Aissue+is%3Aclosed) 
English | [Русский](/README_RU.md)
# ReActor for Stable Diffusion
### The Fast and Simple FaceSwap Extension with a lot of improvements and without NSFW filter (uncensored, use it on your own [responsibility](#disclaimer))
--- <b> <a href="#latestupdate">What's new</a> | <a href="#installation">Installation</a> | <a href="#features">Features</a> | <a href="#usage">Usage</a> | <a href="#api">API</a> | <a href="#troubleshooting">Troubleshooting</a> | <a href="#updating">Updating</a> | <a href="#comfyui">ComfyUI</a> | <a href="#disclaimer">Disclaimer</a> </b></div>
---
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
<a name="latestupdate">
## What's new in the latest updates
### 0.6.0 <sub><sup>ALPHA1
- UI reworked- You can now load several source images (with reference faces) or set the path to the folder containing faces images
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_01.png?raw=true" alt="0.6.0-whatsnew-01" width="100%"/>
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_02.png?raw=true" alt="0.6.0-whatsnew-02" width="100%"/>
### 0.5.1
- You can save face models as "safetensors" files (stored in `<sd-web-ui-folder>\models\reactor\faces`) and load them into ReActor, keeping super lightweight face models of the faces you use;- "Face Mask Correction" option - if you encounter some pixelation around face contours, this option will be useful;
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/face_model_demo_01.jpg?raw=true" alt="0.5.0-whatsnew-01" width="100%"/>
## Installation
[Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
<a name="a1111">If you use [AUTOMATIC1111 web-ui](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
1. (For Windows Users): - Install **Visual Studio 2022** (Community version, for example - you need this step to build some of dependencies): https://visualstudio.microsoft.com/downloads/ - OR only **VS C++ Build Tools** (if you don't need the whole Visual Studio) and select "Desktop Development with C++" under "Workloads -> Desktop & Mobile": https://visualstudio.microsoft.com/visual-cpp-build-tools/ - OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. VIII)](#insightfacebuild)2. In web-ui, go to the "Extensions" tab, load "Available" extensions and type "ReActor" in the search field or use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab - and click "Install"3. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)4. Check the last message in your SD-WebUI Console:* If you see the message "--- PLEASE, RESTART the Server! ---" - so, do it, stop the Server (CTRL+C or CMD+C) and start it again - or just go to the "Installed" tab, click "Apply and restart UI" * If you see the message "Done!", just reload the UI5. Enjoy!
<a name="sdnext">If you use [SD.Next](https://github.com/vladmandic/automatic):
1. Close (stop) your SD WebUI Server if it's running2. (For Windows Users) See the [1st step](#a1111) for Automatic1111 (if you followed [this steps (sec. VIII)](#insightfacebuild) instead - go to the Step 5)3. Go to (Windows)`automatic\venv\Scripts` or (MacOS/Linux)`automatic/venv/bin`, run Terminal or Console (cmd) for that folder and type `activate`4. Run `pip install insightface==0.7.3`5. Run SD.Next, go to the "Extensions" tab and use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab and click "Install"6. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)7. Check the last message in your SD.Next Console:* If you see the message "--- PLEASE, RESTART the Server! ---" - stop the Server (CTRL+C or CMD+C) or just close your console8. Go to the `automatic\extensions\sd-webui-reactor` directory - if you see there `models\insightface` folder with the file `inswapper_128.onnx`, just move the file to the `automatic\models\insightface` folder9. Run your SD.Next WebUI and enjoy!
<a name="colab">If you use [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
1. In active WebUI, go to the "Extensions" tab, load "Available" extensions and type "ReActor" in the search field or use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab - and click "Install"2. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)3. When you see the message "--- PLEASE, RESTART the Server! ---" (in your Colab Notebook Start UI section "Start Cagliostro Colab UI") - just go to the "Installed" tab and click "Apply and restart UI"4. Enjoy!
## Features
- Very fast and accurate **face replacement (face swap)** in images- **Multiple faces support**- **Gender detection**- Ability to **save original images** (made before swapping)- **Face restoration** of a swapped face- **Upscaling** of a resulting image- Saving ans loading **Safetensors Face Models**- **Facial Mask Correction** to avoid any pixelation around face contours- Ability to set the **Postprocessing order**- **100% compatibility** with different **SD WebUIs**: Automatic1111, SD.Next, Cagliostro Colab UI- **Fast performance** even with CPU, ReActor for SD WebUI is absolutely not picky about how powerful your GPU is- **CUDA** acceleration support since version 0.5.0- **[API](/API.md) support**: both SD WebUI built-in and external (via POST/GET requests)- **ComfyUI [support](https://github.com/Gourieff/comfyui-reactor-node)**- **Mac M1/M2 [support](https://github.com/Gourieff/sd-webui-reactor/issues/42)**- Console **log level control**- **NSFW filter free** (this extension is aimed at highly developed intellectual people, not at perverts; our society must be oriented on its way towards the highest standards, not the lowest - this is the essence of development and evolution; so, my position is - that mature-minded people are clever enough to understand for themselves what is good and what is bad and take full responsibility for personal actions; for others - no "filters" will help until they do understand how Universe works)
## Usage
> Using this software you are agree with [disclaimer](#disclaimer)
1. Under "ReActor" drop-down menu, import an image containing a face;2. Turn on the "Enable" checkbox;3. That's it, now the generated result will have the face you selected.
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
### Face Indexes
ReActor detects faces in images in the following order:<br>left->right, top->bottom
And if you need to specify faces, you can set indexes for source and input images.
Index of the first detected face is 0.
You can set indexes in the order you need.<br>E.g.: 0,1,2 (for Source); 1,0,2 (for Input).<br>This means: the second Input face (index = 1) will be swapped by the first Source face (index = 0) and so on.
### Genders
You can specify the gender to detect in images.<br>ReActor will swap a face only if it meets the given condition.
### The result face is blurryUse the "Restore Face" option. You can also try the "Upscaler" option or for more finer control, use an upscaler from the "Extras" tab.You can also set the postproduction order (from 0.1.0 version):<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
*The old logic was the opposite (Upscale -> then Restore), resulting in worse face quality (and big texture differences) after upscaling.*
### There are multiple faces in resultSelect the face numbers you wish to swap using the "Comma separated face number(s)" option for swap-source and result images. You can use different index order.<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
### ~~The result is totally black~~~~This means NSFW filter detected that your image is NSFW.~~
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
### Img2Img
You can choose to activate the swap on the source image or on the generated image, or on both using the checkboxes. Activating on source image allows you to start from a given base and apply the diffusion process to it.
ReActor works with Inpainting - but only the masked part will be swapped.<br>Please use with the "Only masked" option for "Inpaint area" if you enabled "Upscaler". Otherwise use the upscale option via the Extras tab or via the Script loader (below the screen) with "SD upscale" or "Ultimate SD upscale".
### Extras Tab
From the version 0.5.0 you can use ReActor via the Extras Tab. It gives a superfast perfomance and ability to swap face2image avoiding SD pipeline that can cause smushing of original image's details
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
## API
You can use ReActor with the built-in Webui API or via an external API.
Please follow **[this](/API.md)** page for the detailed instruction.
## Troubleshooting
### **I. "You should at least have one model in models directory"**
Please, check the path where "inswapper_128.onnx" model is stored. It must be inside the folder `stable-diffusion-webui\models\insightface`. Move the model there if it's stored in a different directory.
### **II. Any problems with installing Insightface or other dependencies**
(for Mac M1/M2 users) If you get errors when trying to install Insightface - please read https://github.com/Gourieff/sd-webui-reactor/issues/42
(for Windows Users) If you have VS C++ Build Tools or MS VS 2022 installed but still have a problem, then try the next step:1. Close (stop) your SD WebUI Server and start it again (for Any OS Users) If the problem still there, then do the following:1. Close (stop) your SD WebUI Server if it's running2. Go to (Windows)`venv\Lib\site-packages` folder or (MacOS/Linux)`venv/lib/python3.10/site-packages`3. If you see any folders with names start from `~` (e.g. "~rotobuf") - delete them4. Go to (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin`5. Run Terminal or Console (cmd) for that folder and type `activate`6. Update your pip at first: `pip install -U pip`7. Then one-by-one: - `pip install insightface==0.7.3` - `pip install onnx` - `pip install "onnxruntime-gpu>=1.16.1"` - `pip install opencv-python` - `pip install tqdm`8. Type `deactivate`, you can close your Terminal or Console and start your SD WebUI, ReActor should start OK - if not, welcome to the Issues section.
### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
First of all - you need to disable any other Roop-based extensions:- Go to 'Extensions -> Installed' tab and uncheck any Roop-based extensions except this one <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>- Click 'Apply and restart UI'
Alternative solutions: - https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243- https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (can be actual, if you use Vladmandic SD.Next)
### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
Probably, you need to disable the "SD-CN-Animation" extension (or perhaps some another that causes the conflict)
### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed" OR "AttributeError: 'NoneType' object has no attribute 'get'" OR "AttributeError: 'FaceSwapScript' object has no attribute 'save_original'"**
This error may occur if there's smth wrong with the model file `inswapper_128.onnx`
Try to download it manually from [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)and put it to the `stable-diffusion-webui\models\insightface` replacing existing one
### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" OR "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
1. Close (stop) your SD WebUI Server if it's running2. Go to the (Windows)`venv\Lib\site-packages` or (MacOS/Linux)`venv/lib/python3.10/site-packages` and see if there are any folders with names start from "~" (for example "~rotobuf"), delete them3. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`4. Then:- `python -m pip install -U pip`- `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`- `pip install "onnxruntime-gpu>=1.16.1"`
If it didn't help - it seems that you have another extension reinstalling `onnxruntime` when SD WebUI checks requirements. Please see your extensions list. Some extensions can causes reinstalling of `onnxruntime-gpu` to `onnxruntime<1.16.1` every time SD WebUI runs.<br>ORT 1.16.0 has a bug https://github.com/microsoft/onnxruntime/issues/17631 - don't install it!
### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
1. Close (stop) your SD WebUI Server if it's running2. Go to the (Windows)`venv\Lib\site-packages` or (MacOS/Linux)`venv/lib/python3.10/site-packages` and see if there are any folders with names start from "~" (for example "~rotobuf"), delete them3. Go to the "google" folder (inside the "site-packages") and delete any folders there with names start from "~"4. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`5. Then:- `python -m pip install -U pip`- `pip uninstall protobuf`- `pip install "protobuf>=3.20.3"`
If this method doesn't help - there is some other extension that has a wrong version of protobuf dependence and SD WebUI installs it on a startup requirements check
<a name="insightfacebuild">
### **VIII. (For Windows users) If you still cannot build Insightface for some reasons or just don't want to install Visual Studio or VS C++ Build Tools - do the following:**
1. Close (stop) your SD WebUI Server if it's running2. Download and put [prebuilt Insightface package](https://github.com/Gourieff/sd-webui-reactor/raw/main/example/insightface-0.7.3-cp310-cp310-win_amd64.whl) into the stable-diffusion-webui (or SD.Next) root folder (where you have "webui-user.bat" file)3. From stable-diffusion-webui (or SD.Next) root folder run CMD and `.\venv\Scripts\activate`4. Then update your PIP: `python -m pip install -U pip`5. Then install Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`6. Enjoy!
### **IX. 07-August-23 Update problem**
If after `git pull` you see the message: `Merge made by the 'recursive' strategy` and then when you check `git status` you see `Your branch is ahead of 'origin/main' by`
Please do the next:
Inside the folder `extensions\sd-webui-reactor` run Terminal or Console (cmd) and then:- `git reset f48bdf1 --hard`- `git pull`
OR
Just delete the folder `sd-webui-reactor` inside the `extensions` directory and then run Terminal or Console (cmd) and type `git clone https://github.com/Gourieff/sd-webui-reactor`
### **X. StabilityMatrix Issues**
If you encounter any issues with installing this extension in the StabilityMatrix package manager - read here how to solve: https://github.com/Gourieff/sd-webui-reactor/issues/129#issuecomment-1768210875
## Updating
A good and quick way to check for Extensions updates: https://github.com/Gourieff/sd-webui-extensions-updater
## ComfyUI
You can use ReActor with ComfyUI.<br>For the installation instruction follow the [ReActor Node repo](https://github.com/Gourieff/comfyui-reactor-node)
## Disclaimer
This software is meant to be a productive contribution to the rapidly growing AI-generated media industry. It will help artists with tasks such as animating a custom character or using the character as a model for clothing etc.
The developers of this software are aware of its possible unethical applicaitons and are committed to take preventative measures against them. We will continue to develop this project in the positive direction while adhering to law and ethics.
Users of this software are expected to use this software responsibly while abiding the local law. If face of a real person is being used, users are suggested to get consent from the concerned person and clearly mention that it is a deepfake when posting content online. **Developers and Contributors of this software are not responsible for actions of end-users.**
By using this extension you are agree not to create any content that:- violates any laws;- causes any harm to a person or persons;- propogates (spreads) any information (both public or personal) or images (both public or personal) which could be meant for harm;- spreads misinformation;- targets vulnerable groups of people.
This software utilizes the pre-trained models `buffalo_l` and `inswapper_128.onnx`, which are provided by [InsightFace](https://github.com/deepinsight/insightface/). These models are included under the following conditions:
[From insighface licence](https://github.com/deepinsight/insightface/tree/master/python-package): The InsightFace’s pre-trained models are available for non-commercial research purposes only. This includes both auto-downloading models and manually downloaded models.
Users of this software must strictly adhere to these conditions of use. The developers and maintainers of this software are not responsible for any misuse of InsightFace’s pre-trained models.
Please note that if you intend to use this software for any commercial purposes, you will need to train your own models or find models that can be used commercially.
### Models Hashsum
#### Safe-to-use models have the folowing hash:
inswapper_128.onnx```MD5:a3a155b90354160350efd66fed6b3d80SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af```
1k3d68.onnx
```MD5:6fb94fcdb0055e3638bf9158e6a108f4SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc```
2d106det.onnx
```MD5:a3613ef9eb3662b4ef88eb90db1fcf26SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf```
det_10g.onnx
```MD5:4c10eef5c9e168357a16fdd580fa8371SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91```
genderage.onnx
```MD5:81c77ba87ab38163b0dec6b26f8e2af2SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb```
w600k_r50.onnx
```MD5:80248d427976241cbd1343889ed132b3SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43```
**Please check hashsums if you download these models from unverified (or untrusted) sources**123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370<div align="center">
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_RU.png?raw=true" alt="logo" width="180px"/>  <a href="https://boosty.to/artgourieff" target="_blank"> <img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Поддержать проект на Boosty"/> <br> <sup> Поддержать проект </sup> </a> <hr> [](https://github.com/Gourieff/sd-webui-reactor/commits/main)  [](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0) [](https://github.com/Gourieff/sd-webui-reactor/issues?q=is%3Aissue+is%3Aclosed) 
[English](/README.md) | Русский
# ReActor для Stable Diffusion### Расширение для быстрой и простой замены лиц на любых изображениях. Без фильтра цензуры, 18+, используйте под вашу собственную [ответственность](#disclaimer)
--- <b> <a href="#latestupdate">Что нового</a> | <a href="#installation">Установка</a> | <a href="#features">Возможности</a> | <a href="#usage">Использование</a> | <a href="#api">API</a> | <a href="#troubleshooting">Устранение проблем</a> | <a href="#updating">Обновление</a> | <a href="#comfyui">ComfyUI</a> | <a href="#disclaimer">Ответственность</a> </b></div>
---
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
<a name="latestupdate">
## Что нового в последних обновлениях
### 0.6.0 <sub><sup>ALPHA1
- UI переработан- Появилась возможность загружать несколько исходных изображений с лицами или задавать путь к папке, содержащей такие изображения
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_01.png?raw=true" alt="0.6.0-whatsnew-01" width="100%"/>
### 0.5.1
- Теперь можно сохранять модели лиц в качестве файлов "safetensors" (находятся в `<sd-web-ui-folder>\models\reactor\faces`) и загружать их с ReActor, храня супер легкие модели лиц, которые вы чаще всего используете;- Новые опция "Face Mask Correction" - если вы сталкиваетесь с пикселизацией вокруг контуров лица, эта опция будет полезной;
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/face_model_demo_01.jpg?raw=true" alt="0.5.0-whatsnew-01" width="100%"/>
<a name="installation">
## Установка
[Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
<a name="a1111">Если вы используете [AUTOMATIC1111 Web-UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
1. (Для пользователей Windows): - Установите **Visual Studio 2022** (Например, версию Community - этот шаг нужен для правильной компиляции библиотеки Insightface): https://visualstudio.microsoft.com/downloads/ - ИЛИ только **VS C++ Build Tools** (если вам не нужен весь пакет Visual Studio), выберите "Desktop Development with C++" в разделе "Workloads -> Desktop & Mobile": https://visualstudio.microsoft.com/visual-cpp-build-tools/ - ИЛИ если же вы не хотите устанавливать что-либо из вышеуказанного - выполните [следующие шаги (пункт VIII)](#insightfacebuild)2. Внутри SD Web-UI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"3. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)4. Проверьте последнее сообщение в консоли SD-WebUI:* Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) и запустите его заново - ИЛИ же перейдите во вкладку "Installed", нажмите "Apply and restart UI" * Если вы видите "Done!", просто перезагрузите UI, нажав на "Reload UI"5. Готово!
<a name="sdnext">Если вы используете [SD.Next](https://github.com/vladmandic/automatic):
1. Закройте (остановите) SD WebUI Сервер, если он запущен2. (Для пользователей Windows) Смотрите [Шаг 1](#a1111) для Automatic1111 (если же вы следовали [данным шагам (пункт VIII)](#insightfacebuild) вместо этого - переходите к Шагу 5)3. Перейдите в (Windows)`automatic\venv\Scripts` или (MacOS/Linux)`automatic/venv/bin`, запустите Терминал или Консоль (cmd) для данной папки и выполните `activate`4. Выполните `pip install insightface==0.7.3`5. Запустите SD.Next, перейдите во вкладку "Extensions", вставьте эту ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"6. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)7. Проверьте последнее сообщение в консоли SD.Next:* Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) или просто закройте консоль8. Перейдите в директорию `automatic\extensions\sd-webui-reactor` - если вы видите там папку `models\insightface` с файлом `inswapper_128.onnx` внутри, переместите его в папку `automatic\models\insightface`9. Готово, можете запустить SD.Next WebUI!
<a name="colab">Если вы используете [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
1. В активном WebUI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"2. Пожалуйста, подождите некоторое время, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)3. Когда вы увидите сообщение "--- PLEASE, RESTART the Server! ---" (в секции "Start UI" вашего ноутбука "Start Cagliostro Colab UI") - перейдите во вкладку "Installed" и нажмите "Apply and restart UI"4. Готово!
<a name="features">
## Возможности
- Быстрая и точна **замена лиц (faceswap)** на изображении- **Поддержка нескольких лиц**- **Определение пола**- Функция **сохранения оригинального изображения** (сгенерированного до замены лица)- **Восстановление лица** после замены- **Увеличение размера** полученного изображения- Сохранение и загрузка **Моделей Лиц типа Safetensors**- **Коррекция Маски Лица** для предотвращения какой-либо пикселизации вокруг контуров лиц- Возможность задать **порядок постобработки**- **100% совместимость** с разными **SD WebUI**: Automatic1111, SD.Next, Cagliostro Colab UI- **Отличная производительность** даже с использованием ЦПУ, ReActor для SD WebUI абсолютно не требователен к мощности вашей видеокарты- **Поддержка CUDA**, начиная с версии 0.5.0- **Поддержка [API](/API.md)**: как встроенного в SD WebUI, так и внешнего (через POST/GET запросы)- **[Поддержка](https://github.com/Gourieff/comfyui-reactor-node) ComfyUI**- **[Поддержка](https://github.com/Gourieff/sd-webui-reactor/issues/42) ��омпьютеров Mac M1/M2**- **Регулировка уровня логов** консоли- **Без NSFW фильтров** (данное расширение адресовано высокоразвитым интеллектуальным людям, а не извращенцам; наше общество должно быть ориентировано на своём пути на высшие стандарты, а не на низшие - в этом состоит суть развития и эволюции человеческого общества; поэтому, моя позиция такова - что зрелые умом люди достаточно разумны, чтобы понимать, что есть хорошо, а что плохо и нести полную ответственность за собственные действия; для прочих - никакие "фильтры" не помогут, пока эти люди сами не поймут, как работает Вселенная)
<a name="usage">
## Использование
> Используя данное программное обеспечение, вы соглашаетесь с [ответственностью](#disclaimer)
1. В раскрывающимся меню "ReActor" импортируйте изображение, содержащее лицо;2. Установите флажок "Enable";3. Готово, теперь результат будет иметь то лицо, которое вы выбрали.
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
### Индексы Лиц (Face Indexes)
ReActor определяет лица на изображении в следующей последовательности:<br>слева-направо, сверху-вниз.
Если вам нужно заменить определенное лицо, вы можете указать индекс для исходного (source, с лицом) и входного (input, где будет замена лица) изображений.
Индекс первого обнаруженного лица - 0.
Вы можете задать индексы в том порядке, который вам нужен.<br>Например: 0,1,2 (для Source); 1,0,2 (для Input).<br>Это означает, что: второе лицо из Input (индекс = 1) будет заменено первым лицом из Source (индекс = 0) и так далее.
### Определение Пола
Вы можете обозначить, какой пол нужно определять на изображении.<br>ReActor заменит только то лицо, которое удовлетворяет заданному условию.
### Если лицо получилось нечёткимИспользуйте опцию "Restore Face". Также можете попробовать опцию "Upscaler". Для более точного контроля параметров используйте Upscaler во вкладке "Extras".Также вы можете установить порядок постобработки (начиная с версии 0.1.0):<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
*Прежняя логика была противоположенной (Upscale -> затем Restore), что приводило к более худшему качеству изображения лица (а также к значительной разнице текстур) после увеличения.*
### Результат имеет несколько лицВыберите номера лиц, которые нужно поменять, используя поля "Comma separated face number(s)" для исходного изображения лица и для результата. Можно устанавливать любой, необходимый вам, порядок лиц.<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
### ~~Результат получился чёрным~~~~Это значит, что сработал NSFW фильтр.~~
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
### Img2Img
Используйте эту вкладку, чтобы заменить лицо на уже готовом изображении (флажок "Swap in source image") или на сгенерированном на основе готового (флажок "Swap in generated image").
Inpainting также работает, но замена лица происходит только в области маски.<br>Пожалуйста, используйте с опцией "Only masked" для "Inpaint area", если вы применяете "Upscaler". Иначе, используйте функцию увеличения (апскейла) через вкладку "Extras" или через опциональный загрузчик "Script" (внизу экрана), применив "SD upscale" или "Ultimate SD upscale".
### Extras
Начиная с версии 0.5.0, вы можете использовать ReActor через вкладку Extras, что даёт очень быструю производительность и возможность замены лиц в обход пайплайна SD, что иногда вызывает размытие или искажение деталей оригинального изображения
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
## API
Вы можете использовать ReActor как со встроенным SD Webui API так и через внешнее API.
Подробная инструкция **[здесь](/API.md)**.
<a name="troubleshooting">
## Устранение проблем
### **I. "You should at least have one model in models directory"**
Проверьте путь, где хранится модель "inswapper_128.onnx". Файл должен находиться в папке `stable-diffusion-webui\models\insightface`. Переместите модель туда, если она находится в какой-то иной директории.
### **II. Какие-либо проблемы с установкой Insightface или прочих пакетов**
(Для пользователей Mac M1/M2) Если вы получаете ошибки в ходе установки Insightface - читайте https://github.com/Gourieff/sd-webui-reactor/issues/42
(Для пользователей Windows) Если VS C++ Build Tools или MS VS 2022 установлены но вы видите ошибки, связанные с отсутствием Insightface, попробуйте следующее:1. Закройте (остановите) SD WebUI Сервер и запустите его снова (возможно, не прошла инициализация пакета после его установки) (Для пользователей любых ОС) Попробуйте следующее:1. Закройте (остановите) SD WebUI Сервер, если он запущен2. Перейдите в папку (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages`3. Если вы видите к-л папки с именами, начинающимися с `~` (например, "~rotobuf") - удалите их4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`5. Откройте Терминал или Консоль (cmd) для этой папки и выполните `activate`6. Для начала обновите pip: `pip install -U pip`7. Далее: - `pip install insightface==0.7.3` - `pip install onnx` - `pip install "onnxruntime-gpu>=1.16.1"` - `pip install opencv-python` - `pip install tqdm`8. Выполните `deactivate`, закройте Терминал или Консоль и запустите SD WebUI, ReActor должен запуститься без к-л проблем - если же нет, добро пожаловать в раздел "Issues".
### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
Для начала отключите любые другие Roop-подобные расширения:- Перейдите в 'Extensions -> Installed' и снимите флажок с ненужных: <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>- Нажмите 'Apply and restart UI'
Альтернативные решения: - https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243- https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (актуально для Vladmandic SD.Next)
### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
Отключите расширение "SD-CN-Animation" (или какое-либо другое, вызывающее конфликт)
### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed" ИЛИ "AttributeError: 'NoneType' object has no attribute 'get'" ИЛИ "AttributeError: 'FaceSwapScript' object has no attribute 'save_original'"**
Эта ошибка появляется, если что-то не так с файлом модели `inswapper_128.onnx`.
Скачайте вручную по ссылке [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)и сохраните в директорию `stable-diffusion-webui\models\insightface`, заменив имеющийся файл.
### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" ИЛИ "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
1. Закройте (остановите) SD WebUI Сервер, если он запущен2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их3. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`4. Затем:- `python -m pip install -U pip`- `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`- `pip install "onnxruntime-gpu>=1.16.1"`
Если это не помогло - значит какое-то другое расширение переустанавливает `onnxruntime` всякий раз, когда SD WebUI проверяет требования пакетов. Внимательно посмотрите список активных расширений. Некоторые расширения могут вызывать переустановку `onnxruntime-gpu` на версию `onnxruntime<1.16.1` при каждом запуске SD WebUI.<br>ORT 1.16.0 выкатили с ошибкой https://github.com/microsoft/onnxruntime/issues/17631 - не устанавливайте её!
### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
1. Закройте (остановите) SD WebUI Сервер, если он запущен2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их3. Перейдите в папку "google" (внутри "site-packages") и удалите любые папки с именам, начинающимися на "~"4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`5. Затем:- `python -m pip install -U pip`- `pip uninstall protobuf`- `pip install "protobuf>=3.20.3"`
Если это не помгло - значит, есть к-л другое расширение, которое использует неподходящую версию пакета protobuf, и SD WebUI устанавливает эту версию при каждом запуске.
<a name="insightfacebuild">
### **VIII. (Для пользователей Windows) Если вы до сих пор не можете установить пакет Insightface по каким-то причинам или же просто не желаете устанавливать Visual Studio или VS C++ Build Tools - сделайте следующее:**
1. Закройте (остановите) SD WebUI Сервер, если он запущен2. Скачайте готовый [пакет Insightface](https://github.com/Gourieff/sd-webui-reactor/raw/main/example/insightface-0.7.3-cp310-cp310-win_amd64.whl) и сохраните его в корневую директорию stable-diffusion-webui (или SD.Next) - туда, где лежит файл "webui-user.bat"3. Из корневой директории откройте Консоль (CMD) и выполните `.\venv\Scripts\activate`4. Обновите PIP: `python -m pip install -U pip`5. Затем установите Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`6. Готово!
### **IX. Ошибка обновления 07-Август-23**
Если после очередного `git pull` вы получили сообщение: `Merge made by the 'recursive' strategy` и затем, когда проверяете статус репозитория через `git status`, вы видите `Your branch is ahead of 'origin/main' by`
Выполните следующее:
Внутри папки `extensions\sd-webui-reactor` запустите Терминал или Консоль (cmd) и затем:- `git reset f48bdf1 --hard`- `git pull`
ИЛИ:
Полностью удалите папку `sd-webui-reactor` внутри директории `extensions`, запустите Терминал или Консоль (cmd) и выполните `git clone https://github.com/Gourieff/sd-webui-reactor`
### **X. Ошибки установки в StabilityMatrix**
Если вы столкнулись с ошибками при установки данного расширения в пакетном менеджере StabilityMatrix - изучите информацию по ссылке: https://github.com/Gourieff/sd-webui-reactor/issues/129#issuecomment-1768210875
<a name="updating">
## Обновление
Самый простой и удобный способ обновления SD WebUI и расширений: https://github.com/Gourieff/sd-webui-extensions-updater
## ComfyUI
Вы можете использовать ReActor с ComfyUI<br>Инструкция здесь: [ReActor Node](https://github.com/Gourieff/comfyui-reactor-node)
<a name="disclaimer">
## Ответственность
Это программное обеспечение призвано стать продуктивным вкладом в быстрорастущую медиаиндустрию на основе генеративных сетей и искусственного интеллекта. Данное ПО поможет художникам в решении таких задач, как анимация собственного персонажа или использование персонажа в качестве модели для одежды и т.д.
Разработчики этого программного обеспечения осведомлены о возможных неэтичных применениях и обязуются принять против этого превентивные меры. Мы продолжим развивать этот проект в позитивном направлении, придерживаясь закона и этики.
Подразумевается, что пользователи этого программного обеспечения будут использовать его ответственно, соблюдая локальное законодательство. Если используется лицо реального человека, пользователь обязан получить согласие заинтересованного лица и четко указать, что это дипфейк при размещении контента в Интернете. **Разработчики и Со-авторы данного программного обеспечения не несут ответственности за действия конечных пользователей.**
Используя данное расширение, вы соглашаетесь не создавать материалы, которые:- нарушают какие-либо действующие законы тех или иных государств или международных организаций;- причиняют какой-либо вред человеку или лицам;- пропагандируют любую информацию (как общедоступную, так и личную) или изображения (как общедоступные, так и личные), которые могут быть направлены на причинение вреда;- используются для распространения дезинформации;- нацелены на уязвимые группы людей.
Данное программное обеспечение использует предварительно обученные модели `buffalo_l` и `inswapper_128.onnx`, представленные разработчиками [InsightFace](https://github.com/deepinsight/insightface/). Эти модели распространяются при следующих условиях:
[Перевод из текста лицензии insighface](https://github.com/deepinsight/insightface/tree/master/python-package): Предварительно обученные модели InsightFace доступны только для некоммерческих исследовательских целей. Сюда входят как модели с автоматической загрузкой, так и модели, загруженные вручную.
Пользователи данного программного обеспечения должны строго соблюдать данные условия использования. Разработчики и Со-авторы данного программного продукта не несут ответственности за неправильное использование предварительно обученных моделей InsightFace.
Обратите внимание: если вы собираетесь использовать это программное обеспечение в каких-либо коммерческих целях, вам необходимо будет обучить свои собстве��ные модели или найти модели, которые можно использовать в коммерческих целях.
### Хэш файлов моделей
#### Безопасные для использования модели имеют следующий хэш:
inswapper_128.onnx```MD5:a3a155b90354160350efd66fed6b3d80SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af```
1k3d68.onnx
```MD5:6fb94fcdb0055e3638bf9158e6a108f4SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc```
2d106det.onnx
```MD5:a3613ef9eb3662b4ef88eb90db1fcf26SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf```
det_10g.onnx
```MD5:4c10eef5c9e168357a16fdd580fa8371SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91```
genderage.onnx
```MD5:81c77ba87ab38163b0dec6b26f8e2af2SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb```
w600k_r50.onnx
```MD5:80248d427976241cbd1343889ed132b3SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43```
**Пожалуйста, сравните хэш, если вы скачиваете данные модели из непроверенных источников**123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import base64, io, requests, jsonfrom PIL import Image, PngImagePluginfrom datetime import datetime, date
address = 'http://127.0.0.1:7860'input_file = "extensions\sd-webui-reactor\example\IamSFW.jpg" # Input file pathtime = datetime.now()today = date.today()current_date = today.strftime('%Y-%m-%d')current_time = time.strftime('%H-%M-%S')output = 'outputs/api/output_'+current_date+'_'+current_time # Output file path + name indextry: im = Image.open(input_file)except Exception as e: print(e)finally: print(im)
img_bytes = io.BytesIO()im.save(img_bytes, format='PNG') img_base64 = base64.b64encode(img_bytes.getvalue()).decode('utf-8')
# ReActor arguments:args=[ img_base64, #0 True, #1 Enable ReActor '0', #2 Comma separated face number(s) from swap-source image '0', #3 Comma separated face number(s) for target image (result) 'C:\stable-diffusion-webui\models\insightface\inswapper_128.onnx', #4 model path 'CodeFormer', #4 Restore Face: None; CodeFormer; GFPGAN 1, #5 Restore visibility value True, #7 Restore face -> Upscale '4x_NMKD-Superscale-SP_178000_G', #8 Upscaler (type 'None' if doesn't need), see full list here: http://127.0.0.1:7860/sdapi/v1/script-info -> reactor -> sec.8 2, #9 Upscaler scale value 1, #10 Upscaler visibility (if scale = 1) False, #11 Swap in source image True, #12 Swap in generated image 1, #13 Console Log Level (0 - min, 1 - med or 2 - max) 0, #14 Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only) 0, #15 Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only) False, #16 Save the original image(s) made before swapping 0.8, #17 CodeFormer Weight (0 = maximum effect, 1 = minimum effect), 0.5 - by default False, #18 Source Image Hash Check, True - by default False, #19 Target Image Hash Check, False - by default "CUDA", #20 CPU or CUDA (if you have it), CPU - by default True, #21 Face Mask Correction 1, #22 Select Source, 0 - Image, 1 - Face Model, 2 - Source Folder "elena.safetensors", #23 Filename of the face model (from "models/reactor/faces"), e.g. elena.safetensors, don't forger to set #22 to 1 "C:\PATH_TO_FACES_IMAGES", #24 The path to the folder containing source faces images, don't forger to set #22 to 2]
# The args for ReActor can be found by # requests.get(url=f'{address}/sdapi/v1/script-info')
prompt = "(8k, best quality, masterpiece, highly detailed:1.1),realistic photo of fantastic happy woman,hairstyle of blonde and red short bob hair,modern clothing,cinematic lightning,film grain,dynamic pose,bokeh,dof"
neg = "ng_deepnegative_v1_75t,(badhandv4:1.2),(worst quality:2),(low quality:2),(normal quality:2),lowres,(bad anatomy),(bad hands),((monochrome)),((grayscale)),(verybadimagenegative_v1.3:0.8),negative_hand-neg,badhandv4,nude,naked,(strabismus),cross-eye,heterochromia,((blurred))"
payload = { "prompt": prompt, "negative_prompt": neg, "seed": -1, "sampler_name": "DPM++ 2M Karras", "steps": 15, "cfg_scale": 7, "width": 512, "height": 768, "restore_faces": False, "alwayson_scripts": {"reactor":{"args":args}}}
try: print('Working... Please wait...') result = requests.post(url=f'{address}/sdapi/v1/txt2img', json=payload)except Exception as e: print(e)finally: print('Done! Saving file...')
if result is not None: r = result.json() n = 0
for i in r['images']: image = Image.open(io.BytesIO(base64.b64decode(i.split(",",1)[0])))
png_payload = { "image": "data:image/png;base64," + i } response2 = requests.post(url=f'{address}/sdapi/v1/png-info', json=png_payload)
pnginfo = PngImagePlugin.PngInfo() pnginfo.add_text("parameters", response2.json().get("info")) output_file = output+'_'+str(n)+'_.png' try: image.save(output_file, pnginfo=pnginfo) except Exception as e: print(e) finally: print(f'{output_file} is saved\nAll is done!') n += 1else: print('Something went wrong...')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import subprocessimport os, sysfrom typing import Anyimport pkg_resourcesfrom tqdm import tqdmimport urllib.requestfrom packaging import version as pv
try: from modules.paths_internal import models_pathexcept: try: from modules.paths import models_path except: model_path = os.path.abspath("models")
BASE_PATH = os.path.dirname(os.path.realpath(__file__))
req_file = os.path.join(BASE_PATH, "requirements.txt")
models_dir = os.path.join(models_path, "insightface")
# DEPRECATED:# models_dir_old = os.path.join(models_path, "roop")# if os.path.exists(models_dir_old):# if not os.listdir(models_dir_old) and (not os.listdir(models_dir) or not os.path.exists(models_dir)):# os.rename(models_dir_old, models_dir)# else:# import shutil# for file in os.listdir(models_dir_old):# shutil.move(os.path.join(models_dir_old, file), os.path.join(models_dir, file))# try:# os.rmdir(models_dir_old)# except Exception as e:# print(f"OSError: {e}") model_url = "https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx"model_name = os.path.basename(model_url)model_path = os.path.join(models_dir, model_name)
def pip_install(*args): subprocess.run([sys.executable, "-m", "pip", "install", *args])
def pip_uninstall(*args): subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", *args])
def is_installed ( package: str, version: str | None = None, strict: bool = True): has_package = None try: has_package = pkg_resources.get_distribution(package) if has_package is not None: installed_version = has_package.version if (installed_version != version and strict == True) or (pv.parse(installed_version) < pv.parse(version) and strict == False): return False else: return True else: return False except Exception as e: print(f"Error: {e}") return False def download(url, path): request = urllib.request.urlopen(url) total = int(request.headers.get('Content-Length', 0)) with tqdm(total=total, desc='Downloading...', unit='B', unit_scale=True, unit_divisor=1024) as progress: urllib.request.urlretrieve(url, path, reporthook=lambda count, block_size, total_size: progress.update(block_size))
if not os.path.exists(models_dir): os.makedirs(models_dir)
if not os.path.exists(model_path): download(model_url, model_path)
print("ReActor preheating...", end=' ')
last_device = Nonefirst_run = Falseavailable_devices = ["CPU", "CUDA"]
try: last_device_log = os.path.join(BASE_PATH, "last_device.txt") with open(last_device_log) as f: last_device = f.readline().strip() if last_device not in available_devices: last_device = Noneexcept: last_device = "CPU" first_run = True with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt: txt.write(last_device)
with open(req_file) as file: install_count = 0 ort = "onnxruntime-gpu" import torch try: if torch.cuda.is_available(): if first_run or last_device is None: last_device = "CUDA" elif torch.backends.mps.is_available() or hasattr(torch,'dml'): ort = "onnxruntime" # to prevent errors when ORT-GPU is installed but we want ORT instead: if first_run: pip_uninstall("onnxruntime", "onnxruntime-gpu") # just in case: if last_device == "CUDA" or last_device is None: last_device = "CPU" else: if last_device == "CUDA" or last_device is None: last_device = "CPU" with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt: txt.write(last_device) if not is_installed(ort,"1.16.1",False): install_count += 1 pip_install(ort, "-U") except Exception as e: print(e) print(f"\nERROR: Failed to install {ort} - ReActor won't start") raise e print(f"Device: {last_device}") strict = True for package in file: package_version = None try: package = package.strip() if "==" in package: package_version = package.split('==')[1] elif ">=" in package: package_version = package.split('>=')[1] strict = False if not is_installed(package,package_version,strict): install_count += 1 pip_install(package) except Exception as e: print(e) print(f"\nERROR: Failed to install {package} - ReActor won't start") raise e if install_count > 0: print(f""" +---------------------------------+ --- PLEASE, RESTART the Server! --- +---------------------------------+ """)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176import cv2import numpy as npfrom PIL import Image, ImageDraw
from torchvision.transforms.functional import to_pil_image
from scripts.reactor_logger import loggerfrom scripts.reactor_inferencers.bisenet_mask_generator import BiSeNetMaskGeneratorfrom scripts.reactor_entities.face import FaceAreafrom scripts.reactor_entities.rect import Rect
colors = [ (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255), (255, 255, 255), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (0, 128, 128),]
def color_generator(colors): while True: for color in colors: yield color
def process_face_image( face: FaceArea, **kwargs, ) -> Image: image = np.array(face.image) overlay = image.copy() color_iter = color_generator(colors) cv2.rectangle(overlay, (0, 0), (image.shape[1], image.shape[0]), next(color_iter), -1) l, t, r, b = face.face_area_on_image cv2.rectangle(overlay, (l, t), (r, b), (0, 0, 0), 10) if face.landmarks_on_image is not None: for landmark in face.landmarks_on_image: cv2.circle(overlay, (int(landmark.x), int(landmark.y)), 6, (0, 0, 0), 10) alpha = 0.3 output = cv2.addWeighted(image, 1 - alpha, overlay, alpha, 0) return Image.fromarray(output)
def apply_face_mask(swapped_image:np.ndarray,target_image:np.ndarray,target_face,entire_mask_image:np.array)->np.ndarray: logger.status("Correcting Face Mask") mask_generator = BiSeNetMaskGenerator() face = FaceArea(target_image,Rect.from_ndarray(np.array(target_face.bbox)),1.6,512,"") face_image = np.array(face.image) process_face_image(face) face_area_on_image = face.face_area_on_image mask = mask_generator.generate_mask( face_image, face_area_on_image=face_area_on_image, affected_areas=["Face"], mask_size=0, use_minimal_area=True ) mask = cv2.blur(mask, (12, 12)) # """entire_mask_image = np.zeros_like(target_image)""" larger_mask = cv2.resize(mask, dsize=(face.width, face.height)) entire_mask_image[ face.top : face.bottom, face.left : face.right, ] = larger_mask result = Image.composite(Image.fromarray(swapped_image),Image.fromarray(target_image), Image.fromarray(entire_mask_image).convert("L")) return np.array(result)
def rotate_array(image: np.ndarray, angle: float) -> np.ndarray: if angle == 0: return image
h, w = image.shape[:2] center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0) return cv2.warpAffine(image, M, (w, h))
def rotate_image(image: Image, angle: float) -> Image: if angle == 0: return image return Image.fromarray(rotate_array(np.array(image), angle))
def correct_face_tilt(angle: float) -> bool: angle = abs(angle) if angle > 180: angle = 360 - angle return angle > 40
def _dilate(arr: np.ndarray, value: int) -> np.ndarray: kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value)) return cv2.dilate(arr, kernel, iterations=1)
def _erode(arr: np.ndarray, value: int) -> np.ndarray: kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value)) return cv2.erode(arr, kernel, iterations=1)
def dilate_erode(img: Image.Image, value: int) -> Image.Image: """ The dilate_erode function takes an image and a value. If the value is positive, it dilates the image by that amount. If the value is negative, it erodes the image by that amount.
Parameters ---------- img: PIL.Image.Image the image to be processed value: int kernel size of dilation or erosion
Returns ------- PIL.Image.Image The image that has been dilated or eroded """ if value == 0: return img
arr = np.array(img) arr = _dilate(arr, value) if value > 0 else _erode(arr, -value)
return Image.fromarray(arr)
def mask_to_pil(masks, shape: tuple[int, int]) -> list[Image.Image]: """ Parameters ---------- masks: torch.Tensor, dtype=torch.float32, shape=(N, H, W). The device can be CUDA, but `to_pil_image` takes care of that.
shape: tuple[int, int] (width, height) of the original image """ n = masks.shape[0] return [to_pil_image(masks[i], mode="L").resize(shape) for i in range(n)]
def create_mask_from_bbox( bboxes: list[list[float]], shape: tuple[int, int]) -> list[Image.Image]: """ Parameters ---------- bboxes: list[list[float]] list of [x1, y1, x2, y2] bounding boxes shape: tuple[int, int] shape of the image (width, height)
Returns ------- masks: list[Image.Image] A list of masks
""" masks = [] for bbox in bboxes: mask = Image.new("L", shape, 0) mask_draw = ImageDraw.Draw(mask) mask_draw.rectangle(bbox, fill=255) masks.append(mask) return masks1234import reactor_ui.reactor_upscale_ui as ui_upscaleimport reactor_ui.reactor_tools_ui as ui_toolsimport reactor_ui.reactor_settings_ui as ui_settingsimport reactor_ui.reactor_main_ui as ui_main123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182import gradio as grfrom scripts.reactor_helpers import ( get_model_names, get_facemodels)from scripts.reactor_swapper import ( clear_faces_list,)from modules import shared
SAVE_ORIGINAL: bool = False
def update_fm_list(selected: str): return gr.Dropdown.update( value=selected, choices=get_model_names(get_facemodels) )
# TAB MAINdef show(is_img2img: bool, show_br: bool = True, **msgs):
def on_select_source(selected: bool, evt: gr.SelectData): global SAVE_ORIGINAL if evt.index == 2: if SAVE_ORIGINAL != selected: SAVE_ORIGINAL = selected return { control_col_1: gr.Column.update(visible=False), control_col_2: gr.Column.update(visible=False), control_col_3: gr.Column.update(visible=True), save_original: gr.Checkbox.update(value=False,visible=False), imgs_hash_clear: gr.Button.update(visible=True) } if evt.index == 0: return { control_col_1: gr.Column.update(visible=True), control_col_2: gr.Column.update(visible=False), control_col_3: gr.Column.update(visible=False), save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br), imgs_hash_clear: gr.Button.update(visible=False) } if evt.index == 1: return { control_col_1: gr.Column.update(visible=False), control_col_2: gr.Column.update(visible=True), control_col_3: gr.Column.update(visible=False), save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br), imgs_hash_clear: gr.Button.update(visible=False) } progressbar_area = gr.Markdown("") with gr.Tab("Main"): with gr.Column(): with gr.Row(): select_source = gr.Radio( ["Image(s)","Face Model","Folder"], value="Image(s)", label="Select Source", type="index", scale=1, ) with gr.Column(visible=False) as control_col_2: with gr.Row(): face_models = get_model_names(get_facemodels) face_model = gr.Dropdown( choices=face_models, label="Choose Face Model", value="None", scale=1, ) fm_update = gr.Button( value="🔄", variant="tool", ) fm_update.click( update_fm_list, inputs=[face_model], outputs=[face_model], ) imgs_hash_clear = gr.Button( value="Clear Source Images Hash", scale=1, visible=False, ) imgs_hash_clear.click(clear_faces_list,None,[progressbar_area]) gr.Markdown("<br>", visible=show_br) with gr.Column(visible=True) as control_col_1: gr.Markdown("<center>🔽🔽🔽 Single Image has priority when both Areas in use 🔽🔽🔽</center>") with gr.Row(): img = gr.Image( type="pil", label="Single Source Image", ) imgs = gr.Files( label=f"Multiple Source Images{msgs['extra_multiple_source']}", file_types=["image"], ) with gr.Column(visible=False) as control_col_3: gr.Markdown("<span style='display:block;text-align:right;padding-right:3px;margin: -15px 0;font-size:1.1em'><sup>Clear Hash if you see the previous face was swapped instead of the new one</sup></span>") source_folder = gr.Textbox( value="", placeholder="Paste here the path to the folder containing source faces images", label=f"Source Folder{msgs['extra_multiple_source']}", ) setattr(face_model, "do_not_save_to_config", True) if is_img2img: save_original = gr.Checkbox( False, label="Save Original (Swap in generated only)", info="Save the original image(s) made before swapping (it always saves Original when you use Multiple Images or Folder)" ) else: save_original = gr.Checkbox( False, label="Save Original", info="Save the original image(s) made before swapping (it always saves Original when you use Multiple Images or Folder)", visible=show_br ) # imgs.upload(on_files_upload_uncheck_so,[save_original],[save_original],show_progress=False) # imgs.clear(on_files_clear,None,[save_original],show_progress=False) imgs.clear(clear_faces_list,None,None,show_progress=False) mask_face = gr.Checkbox( False, label="Face Mask Correction", info="Apply this option if you see some pixelation around face contours" ) gr.Markdown("<br>", visible=show_br) gr.Markdown("Source Image (above):") with gr.Row(): source_faces_index = gr.Textbox( value="0", placeholder="Which face(s) to use as Source (comma separated)", label="Comma separated face number(s); Example: 0,2,1", ) gender_source = gr.Radio( ["No", "Female Only", "Male Only"], value="No", label="Gender Detection (Source)", type="index", ) gr.Markdown("<br>", visible=show_br) gr.Markdown("Target Image (result):") with gr.Row(): faces_index = gr.Textbox( value="0", placeholder="Which face(s) to Swap into Target (comma separated)", label="Comma separated face number(s); Example: 1,0,2", ) gender_target = gr.Radio( ["No", "Female Only", "Male Only"], value="No", label="Gender Detection (Target)", type="index", ) gr.Markdown("<br>", visible=show_br) with gr.Row(): face_restorer_name = gr.Radio( label="Restore Face", choices=["None"] + [x.name() for x in shared.face_restorers], value=shared.face_restorers[0].name(), type="value", ) with gr.Column(): face_restorer_visibility = gr.Slider( 0, 1, 1, step=0.1, label="Restore Face Visibility" ) codeformer_weight = gr.Slider( 0, 1, 0.5, step=0.1, label="CodeFormer Weight", info="0 = maximum effect, 1 = minimum effect" ) gr.Markdown("<br>", visible=show_br) swap_in_source = gr.Checkbox( False, label="Swap in source image", visible=is_img2img, ) swap_in_generated = gr.Checkbox( True, label="Swap in generated image", visible=is_img2img, ) select_source.select(on_select_source,[save_original],[control_col_1,control_col_2,control_col_3,save_original,imgs_hash_clear],show_progress=False)
return img, imgs, select_source, face_model, source_folder, save_original, mask_face, source_faces_index, gender_source, faces_index, gender_target, face_restorer_name, face_restorer_visibility, codeformer_weight, swap_in_source, swap_in_generated1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import gradio as grfrom scripts.reactor_logger import loggerfrom scripts.reactor_helpers import get_models, set_Devicefrom scripts.reactor_globals import DEVICE, DEVICE_LISTtry: import torch.cuda as cuda EP_is_visible = True if cuda.is_available() else Falseexcept: EP_is_visible = False
def update_models_list(selected: str): return gr.Dropdown.update( value=selected, choices=get_models() )
def show(hash_check_block: bool = True): # TAB SETTINGS with gr.Tab("Settings"): models = get_models() with gr.Row(visible=EP_is_visible): device = gr.Radio( label="Execution Provider", choices=DEVICE_LIST, value=DEVICE, type="value", info="If you already run 'Generate' - RESTART is required to apply. Click 'Save', (A1111) Extensions Tab -> 'Apply and restart UI' or (SD.Next) close the Server and start it again", scale=2, ) save_device_btn = gr.Button("Save", scale=0) save = gr.Markdown("", visible=EP_is_visible) setattr(device, "do_not_save_to_config", True) save_device_btn.click( set_Device, inputs=[device], outputs=[save], ) with gr.Row(): if len(models) == 0: logger.warning( "You should at least have one model in models directory, please read the doc here: https://github.com/Gourieff/sd-webui-reactor/" ) model = gr.Dropdown( choices=models, label="Model not found, please download one and refresh the list" ) else: model = gr.Dropdown( choices=models, label="Model", value=models[0] ) models_update = gr.Button( value="🔄", variant="tool", ) models_update.click( update_models_list, inputs=[model], outputs=[model], ) console_logging_level = gr.Radio( ["No log", "Minimum", "Default"], value="Minimum", label="Console Log Level", type="index" ) gr.Markdown("<br>", visible=hash_check_block) with gr.Row(visible=hash_check_block): source_hash_check = gr.Checkbox( True, label="Source Image Hash Check", info="Recommended to keep it ON. Processing is faster when Source Image is the same." ) target_hash_check = gr.Checkbox( False, label="Target Image Hash Check", info="Affects if you use Extras tab or img2img with only 'Swap in source image' on." ) return model, device, console_logging_level, source_hash_check, target_hash_check12345678910111213141516171819202122232425import gradio as grfrom scripts.reactor_swapper import build_face_model
# TAB TOOLSdef show(): with gr.Tab("Tools"): with gr.Tab("Face Models"): gr.Markdown("Load an image containing one person, name it and click 'Build and Save'") img_fm = gr.Image( type="pil", label="Load Image to build Face Model", ) with gr.Row(equal_height=True): fm_name = gr.Textbox( value="", placeholder="Please type any name (e.g. Elena)", label="Face Model Name", ) save_fm_btn = gr.Button("Build and Save") save_fm = gr.Markdown("You can find saved models in 'models/reactor/faces'") save_fm_btn.click( build_face_model, inputs=[img_fm, fm_name], outputs=[save_fm], )123456789101112131415161718192021222324252627282930313233343536373839import gradio as grfrom modules import shared
def update_upscalers_list(selected: str): return gr.Dropdown.update( value=selected, choices=[upscaler.name for upscaler in shared.sd_upscalers] )
# TAB UPSCALEdef show(show_br: bool = True): with gr.Tab("Upscale"): restore_first = gr.Checkbox( True, label="1. Restore Face -> 2. Upscale (-Uncheck- if you want vice versa)", info="Postprocessing Order" ) with gr.Row(): upscaler_name = gr.Dropdown( choices=[upscaler.name for upscaler in shared.sd_upscalers], label="Upscaler", value="None", info="Won't scale if you choose -Swap in Source- via img2img, only 1x-postprocessing will affect (texturing, denoising, restyling etc.)" ) upscalers_update = gr.Button( value="🔄", variant="tool", ) upscalers_update.click( update_upscalers_list, inputs=[upscaler_name], outputs=[upscaler_name], ) gr.Markdown("<br>", visible=show_br) with gr.Row(): upscaler_scale = gr.Slider(1, 8, 1, step=0.1, label="Scale by") upscaler_visibility = gr.Slider( 0, 1, 1, step=0.1, label="Upscaler Visibility (if scale = 1)" ) return restore_first, upscaler_name, upscaler_scale, upscaler_visibility123insightface==0.7.3onnx>=1.14.0opencv-python>=4.7.0.72123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import os.path as ospimport globimport loggingimport insightfacefrom insightface.model_zoo.model_zoo import ModelRouter, PickableInferenceSessionfrom insightface.model_zoo.retinaface import RetinaFacefrom insightface.model_zoo.landmark import Landmarkfrom insightface.model_zoo.attribute import Attributefrom insightface.model_zoo.inswapper import INSwapperfrom insightface.model_zoo.arcface_onnx import ArcFaceONNXfrom insightface.app import FaceAnalysisfrom insightface.utils import DEFAULT_MP_NAME, ensure_availablefrom insightface.model_zoo import model_zooimport onnxruntimeimport onnxfrom onnx import numpy_helperfrom scripts.reactor_logger import logger
def patched_get_model(self, **kwargs): session = PickableInferenceSession(self.onnx_file, **kwargs) inputs = session.get_inputs() input_cfg = inputs[0] input_shape = input_cfg.shape outputs = session.get_outputs()
if len(outputs) >= 5: return RetinaFace(model_file=self.onnx_file, session=session) elif input_shape[2] == 192 and input_shape[3] == 192: return Landmark(model_file=self.onnx_file, session=session) elif input_shape[2] == 96 and input_shape[3] == 96: return Attribute(model_file=self.onnx_file, session=session) elif len(inputs) == 2 and input_shape[2] == 128 and input_shape[3] == 128: return INSwapper(model_file=self.onnx_file, session=session) elif input_shape[2] == input_shape[3] and input_shape[2] >= 112 and input_shape[2] % 16 == 0: return ArcFaceONNX(model_file=self.onnx_file, session=session) else: return None
def patched_faceanalysis_init(self, name=DEFAULT_MP_NAME, root='~/.insightface', allowed_modules=None, **kwargs): onnxruntime.set_default_logger_severity(3) self.models = {} self.model_dir = ensure_available('models', name, root=root) onnx_files = glob.glob(osp.join(self.model_dir, '*.onnx')) onnx_files = sorted(onnx_files) for onnx_file in onnx_files: model = model_zoo.get_model(onnx_file, **kwargs) if model is None: print('model not recognized:', onnx_file) elif allowed_modules is not None and model.taskname not in allowed_modules: print('model ignore:', onnx_file, model.taskname) del model elif model.taskname not in self.models and (allowed_modules is None or model.taskname in allowed_modules): self.models[model.taskname] = model else: print('duplicated model task type, ignore:', onnx_file, model.taskname) del model assert 'detection' in self.models self.det_model = self.models['detection']
def patched_faceanalysis_prepare(self, ctx_id, det_thresh=0.5, det_size=(640, 640)): self.det_thresh = det_thresh assert det_size is not None self.det_size = det_size for taskname, model in self.models.items(): if taskname == 'detection': model.prepare(ctx_id, input_size=det_size, det_thresh=det_thresh) else: model.prepare(ctx_id)
def patched_inswapper_init(self, model_file=None, session=None): self.model_file = model_file self.session = session model = onnx.load(self.model_file) graph = model.graph self.emap = numpy_helper.to_array(graph.initializer[-1]) self.input_mean = 0.0 self.input_std = 255.0 if self.session is None: self.session = onnxruntime.InferenceSession(self.model_file, None) inputs = self.session.get_inputs() self.input_names = [] for inp in inputs: self.input_names.append(inp.name) outputs = self.session.get_outputs() output_names = [] for out in outputs: output_names.append(out.name) self.output_names = output_names assert len(self.output_names) == 1 input_cfg = inputs[0] input_shape = input_cfg.shape self.input_shape = input_shape self.input_size = tuple(input_shape[2:4][::-1])
def patch_insightface(get_model, faceanalysis_init, faceanalysis_prepare, inswapper_init): insightface.model_zoo.model_zoo.ModelRouter.get_model = get_model insightface.app.FaceAnalysis.__init__ = faceanalysis_init insightface.app.FaceAnalysis.prepare = faceanalysis_prepare insightface.model_zoo.inswapper.INSwapper.__init__ = inswapper_init
original_functions = [ModelRouter.get_model, FaceAnalysis.__init__, FaceAnalysis.prepare, INSwapper.__init__]patched_functions = [patched_get_model, patched_faceanalysis_init, patched_faceanalysis_prepare, patched_inswapper_init]
def apply_logging_patch(console_logging_level): if console_logging_level == 0: patch_insightface(*patched_functions) logger.setLevel(logging.WARNING) elif console_logging_level == 1: patch_insightface(*patched_functions) logger.setLevel(logging.STATUS) elif console_logging_level == 2: patch_insightface(*original_functions) logger.setLevel(logging.INFO)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118'''Thanks SpenserCai for the original version of the roop api script-------------------------------------- ReActor External API v1.0.1 --------------------------------------'''import os, globfrom datetime import datetime, datefrom fastapi import FastAPI, Body
# from modules.api.models import *from modules import scripts, sharedfrom modules.api import api
import gradio as gr
from scripts.reactor_swapper import EnhancementOptions, swap_facefrom scripts.reactor_logger import logger
def default_file_path(): time = datetime.now() today = date.today() current_date = today.strftime('%Y-%m-%d') current_time = time.strftime('%H-%M-%S') output_file = 'output_'+current_date+'_'+current_time+'.png' return os.path.join(os.path.abspath("outputs/api"), output_file)
def get_face_restorer(name): for restorer in shared.face_restorers: if restorer.name() == name: return restorer return None
def get_upscaler(name): for upscaler in shared.sd_upscalers: if upscaler.name == name: return upscaler return None
def get_models(): models_path = os.path.join(scripts.basedir(), "models/insightface/*") models = glob.glob(models_path) models = [x for x in models if x.endswith(".onnx") or x.endswith(".pth")] return models
def get_full_model(model_name): models = get_models() for model in models: model_path = os.path.split(model) if model_path[1] == model_name: return model return None
def reactor_api(_: gr.Blocks, app: FastAPI): @app.post("/reactor/image") async def reactor_image( source_image: str = Body("",title="Source Face Image"), target_image: str = Body("",title="Target Image"), source_faces_index: list[int] = Body([0],title="Comma separated face number(s) from swap-source image"), face_index: list[int] = Body([0],title="Comma separated face number(s) for target image (result)"), upscaler: str = Body("None",title="Upscaler"), scale: int = Body(1,title="Scale by"), upscale_visibility: float = Body(1,title="Upscaler visibility (if scale = 1)"), face_restorer: str = Body("None",title="Restore Face: 0 - None; 1 - CodeFormer; 2 - GFPGA"), restorer_visibility: float = Body(1,title="Restore visibility value"), codeformer_weight: float = Body(0.5,title="CodeFormer Weight"), restore_first: int = Body(1,title="Restore face -> Then upscale, 1 - True, 0 - False"), model: str = Body("inswapper_128.onnx",title="Model"), gender_source: int = Body(0,title="Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)"), gender_target: int = Body(0,title="Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)"), save_to_file: int = Body(0,title="Save Result to file, 0 - No, 1 - Yes"), result_file_path: str = Body("",title="(if 'save_to_file = 1') Result file path"), device: str = Body("CPU",title="CPU or CUDA (if you have it)"), mask_face: int = Body(0,title="Face Mask Correction, 1 - True, 0 - False"), select_source: int = Body(0,title="Select Source, 0 - Image, 1 - Face Model, 2 - Source Folder"), face_model: str = Body("None",title="Filename of the face model (from 'models/reactor/faces'), e.g. elena.safetensors"), source_folder: str = Body("",title="The path to the folder containing source faces images") ): s_image = api.decode_base64_to_image(source_image) t_image = api.decode_base64_to_image(target_image) sf_index = source_faces_index f_index = face_index gender_s = gender_source gender_t = gender_target restore_first_bool = True if restore_first == 1 else False mask_face = True if mask_face == 1 else False up_options = EnhancementOptions(do_restore_first=restore_first_bool, scale=scale, upscaler=get_upscaler(upscaler), upscale_visibility=upscale_visibility,face_restorer=get_face_restorer(face_restorer),restorer_visibility=restorer_visibility,codeformer_weight=codeformer_weight) use_model = get_full_model(model) if use_model is None: Exception("Model not found") result = swap_face(s_image, t_image, use_model, sf_index, f_index, up_options, gender_s, gender_t, True, True, device, mask_face, select_source, face_model, source_folder, None) if save_to_file == 1: if result_file_path == "": result_file_path = default_file_path() try: result[0].save(result_file_path, format='PNG') logger.status("Result has been saved to: %s", result_file_path) except Exception as e: logger.error("Error while saving result: %s",e) return {"image": api.encode_pil_to_base64(result[0])}
@app.get("/reactor/models") async def reactor_models(): model_names = [os.path.split(model)[1] for model in get_models()] return {"models": model_names} @app.get("/reactor/upscalers") async def reactor_upscalers(): names = [upscaler.name for upscaler in shared.sd_upscalers] return {"upscalers": names}
try: import modules.script_callbacks as script_callbacks
script_callbacks.on_app_started(reactor_api)except: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import traceback
import cv2import numpy as npfrom modules import imagesfrom PIL import Image
from scripts.reactor_entities.rect import Point, Rect
class FaceArea: def __init__(self, entire_image: np.ndarray, face_area: Rect, face_margin: float, face_size: int, upscaler: str): self.face_area = face_area self.center = face_area.center left, top, right, bottom = face_area.to_square()
self.left, self.top, self.right, self.bottom = self.__ensure_margin( left, top, right, bottom, entire_image, face_margin )
self.width = self.right - self.left self.height = self.bottom - self.top
self.image = self.__crop_face_image(entire_image, face_size, upscaler) self.face_size = face_size self.scale_factor = face_size / self.width self.face_area_on_image = self.__get_face_area_on_image() self.landmarks_on_image = self.__get_landmarks_on_image()
def __get_face_area_on_image(self): left = int((self.face_area.left - self.left) * self.scale_factor) top = int((self.face_area.top - self.top) * self.scale_factor) right = int((self.face_area.right - self.left) * self.scale_factor) bottom = int((self.face_area.bottom - self.top) * self.scale_factor) return self.__clip_values(left, top, right, bottom)
def __get_landmarks_on_image(self): landmarks = [] if self.face_area.landmarks is not None: for landmark in self.face_area.landmarks: landmarks.append( Point( int((landmark.x - self.left) * self.scale_factor), int((landmark.y - self.top) * self.scale_factor), ) ) return landmarks
def __crop_face_image(self, entire_image: np.ndarray, face_size: int, upscaler: str): cropped = entire_image[self.top : self.bottom, self.left : self.right, :] if upscaler: return images.resize_image(0, Image.fromarray(cropped), face_size, face_size, upscaler) else: return Image.fromarray(cv2.resize(cropped, dsize=(face_size, face_size)))
def __ensure_margin(self, left: int, top: int, right: int, bottom: int, entire_image: np.ndarray, margin: float): entire_height, entire_width = entire_image.shape[:2]
side_length = right - left margin = min(min(entire_height, entire_width) / side_length, margin) diff = int((side_length * margin - side_length) / 2)
top = top - diff bottom = bottom + diff left = left - diff right = right + diff
if top < 0: bottom = bottom - top top = 0 if left < 0: right = right - left left = 0
if bottom > entire_height: top = top - (bottom - entire_height) bottom = entire_height if right > entire_width: left = left - (right - entire_width) right = entire_width
return left, top, right, bottom
def get_angle(self) -> float: landmarks = getattr(self.face_area, "landmarks", None) if landmarks is None: return 0
eye1 = getattr(landmarks, "eye1", None) eye2 = getattr(landmarks, "eye2", None) if eye2 is None or eye1 is None: return 0
try: dx = eye2.x - eye1.x dy = eye2.y - eye1.y if dx == 0: dx = 1 angle = np.arctan(dy / dx) * 180 / np.pi
if dx < 0: angle = (angle + 180) % 360 return angle except Exception: print(traceback.format_exc()) return 0
def rotate_face_area_on_image(self, angle: float): center = [ (self.face_area_on_image[0] + self.face_area_on_image[2]) / 2, (self.face_area_on_image[1] + self.face_area_on_image[3]) / 2, ]
points = [ [self.face_area_on_image[0], self.face_area_on_image[1]], [self.face_area_on_image[2], self.face_area_on_image[3]], ]
angle = np.radians(angle) rot_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
points = np.array(points) - center points = np.dot(points, rot_matrix.T) points += center left, top, right, bottom = (int(points[0][0]), int(points[0][1]), int(points[1][0]), int(points[1][1]))
left, right = (right, left) if left > right else (left, right) top, bottom = (bottom, top) if top > bottom else (top, bottom)
width, height = right - left, bottom - top if width < height: left, right = left - (height - width) // 2, right + (height - width) // 2 elif height < width: top, bottom = top - (width - height) // 2, bottom + (width - height) // 2 return self.__clip_values(left, top, right, bottom)
def __clip_values(self, *args): result = [] for val in args: if val < 0: result.append(0) elif val > self.face_size: result.append(self.face_size) else: result.append(val) return tuple(result)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778from typing import Dict, NamedTuple, Tuple
import numpy as np
class Point(NamedTuple): x: int y: int
class Landmarks(NamedTuple): eye1: Point eye2: Point nose: Point mouth1: Point mouth2: Point
class Rect: def __init__( self, left: int, top: int, right: int, bottom: int, tag: str = "face", landmarks: Landmarks = None, attributes: Dict[str, str] = {}, ) -> None: self.tag = tag self.left = left self.top = top self.right = right self.bottom = bottom self.center = int((right + left) / 2) self.middle = int((top + bottom) / 2) self.width = right - left self.height = bottom - top self.size = self.width * self.height self.landmarks = landmarks self.attributes = attributes
@classmethod def from_ndarray( cls, face_box: np.ndarray, tag: str = "face", landmarks: Landmarks = None, attributes: Dict[str, str] = {}, ) -> "Rect": left, top, right, bottom, *_ = list(map(int, face_box)) return cls(left, top, right, bottom, tag, landmarks, attributes)
def to_tuple(self) -> Tuple[int, int, int, int]: return self.left, self.top, self.right, self.bottom
def to_square(self): left, top, right, bottom = self.to_tuple()
width = right - left height = bottom - top
if width % 2 == 1: right = right + 1 width = width + 1 if height % 2 == 1: bottom = bottom + 1 height = height + 1
diff = int(abs(width - height) / 2) if width > height: top = top - diff bottom = bottom + diff else: left = left - diff right = right + diff
return left, top, right, bottom123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577import os, globimport gradio as grfrom PIL import Image
from typing import List
import modules.scripts as scriptsfrom modules.upscaler import Upscaler, UpscalerDatafrom modules import scripts, shared, images, scripts_postprocessingfrom modules.processing import ( Processed, StableDiffusionProcessing, StableDiffusionProcessingImg2Img,)from modules.face_restoration import FaceRestorationfrom modules.images import save_image
from reactor_ui import ui_main, ui_upscale, ui_tools, ui_settingsfrom scripts.reactor_logger import loggerfrom scripts.reactor_swapper import ( EnhancementOptions, swap_face, check_process_halt, reset_messaged,)from scripts.reactor_version import version_flag, app_titlefrom scripts.console_log_patch import apply_logging_patchfrom scripts.reactor_helpers import ( make_grid, set_Device, )from scripts.reactor_globals import SWAPPER_MODELS_PATH #, DEVICE, DEVICE_LIST
class FaceSwapScript(scripts.Script): def title(self): return f"{app_title}"
def show(self, is_img2img): return scripts.AlwaysVisible
def ui(self, is_img2img): with gr.Accordion(f"{app_title}", open=False):
# def on_files_upload_uncheck_so(selected: bool): # global SAVE_ORIGINAL # SAVE_ORIGINAL = selected # return gr.Checkbox.update(value=False,visible=False) # def on_files_clear(): # clear_faces_list() # return gr.Checkbox.update(value=SAVE_ORIGINAL,visible=True) enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}") gr.Markdown("<br>")
# TAB MAIN msgs: dict = { "extra_multiple_source": "", } img, imgs, select_source, face_model, source_folder, save_original, mask_face, source_faces_index, gender_source, faces_index, gender_target, face_restorer_name, face_restorer_visibility, codeformer_weight, swap_in_source, swap_in_generated = ui_main.show(is_img2img=is_img2img, **msgs) # TAB UPSCALE restore_first, upscaler_name, upscaler_scale, upscaler_visibility = ui_upscale.show()
# TAB TOOLS ui_tools.show() # TAB SETTINGS model, device, console_logging_level, source_hash_check, target_hash_check = ui_settings.show() gr.Markdown("<span style='display:block;text-align:right;padding:3px;font-size:0.666em;margin-bottom:-12px;'>by <a style='font-weight:normal' href='https://github.com/Gourieff' target='_blank'>Eugene Gourieff</a></span>")
return [ img, enable, source_faces_index, faces_index, model, face_restorer_name, face_restorer_visibility, restore_first, upscaler_name, upscaler_scale, upscaler_visibility, swap_in_source, swap_in_generated, console_logging_level, gender_source, gender_target, save_original, codeformer_weight, source_hash_check, target_hash_check, device, mask_face, select_source, face_model, source_folder, imgs, ]
@property def upscaler(self) -> UpscalerData: for upscaler in shared.sd_upscalers: if upscaler.name == self.upscaler_name: return upscaler return None
@property def face_restorer(self) -> FaceRestoration: for face_restorer in shared.face_restorers: if face_restorer.name() == self.face_restorer_name: return face_restorer return None
@property def enhancement_options(self) -> EnhancementOptions: return EnhancementOptions( do_restore_first = self.restore_first, scale=self.upscaler_scale, upscaler=self.upscaler, face_restorer=self.face_restorer, upscale_visibility=self.upscaler_visibility, restorer_visibility=self.face_restorer_visibility, codeformer_weight=self.codeformer_weight, )
def process( self, p: StableDiffusionProcessing, img, enable, source_faces_index, faces_index, model, face_restorer_name, face_restorer_visibility, restore_first, upscaler_name, upscaler_scale, upscaler_visibility, swap_in_source, swap_in_generated, console_logging_level, gender_source, gender_target, save_original, codeformer_weight, source_hash_check, target_hash_check, device, mask_face, select_source, face_model, source_folder, imgs, ): self.enable = enable if self.enable:
logger.debug("*** Start process")
reset_messaged() if check_process_halt(): return global SWAPPER_MODELS_PATH self.source = img self.face_restorer_name = face_restorer_name self.upscaler_scale = upscaler_scale self.upscaler_visibility = upscaler_visibility self.face_restorer_visibility = face_restorer_visibility self.restore_first = restore_first self.upscaler_name = upscaler_name self.swap_in_source = swap_in_source self.swap_in_generated = swap_in_generated self.model = os.path.join(SWAPPER_MODELS_PATH,model) self.console_logging_level = console_logging_level self.gender_source = gender_source self.gender_target = gender_target self.save_original = save_original self.codeformer_weight = codeformer_weight self.source_hash_check = source_hash_check self.target_hash_check = target_hash_check self.device = device self.mask_face = mask_face self.select_source = select_source self.face_model = face_model self.source_folder = source_folder self.source_imgs = imgs if self.gender_source is None or self.gender_source == "No": self.gender_source = 0 if self.gender_target is None or self.gender_target == "No": self.gender_target = 0 self.source_faces_index = [ int(x) for x in source_faces_index.strip(",").split(",") if x.isnumeric() ] self.faces_index = [ int(x) for x in faces_index.strip(",").split(",") if x.isnumeric() ] if len(self.source_faces_index) == 0: self.source_faces_index = [0] if len(self.faces_index) == 0: self.faces_index = [0] if self.save_original is None: self.save_original = False if self.source_hash_check is None: self.source_hash_check = True if self.target_hash_check is None: self.target_hash_check = False if self.mask_face is None: self.mask_face = False
logger.debug("*** Set Device") set_Device(self.device) if ((self.source is not None or self.source_imgs is not None) and self.select_source == 0) or ((self.face_model is not None and self.face_model != "None") and self.select_source == 1) or ((self.source_folder is not None and self.source_folder != "") and self.select_source == 2): logger.debug("*** Log patch") apply_logging_patch(console_logging_level) if isinstance(p, StableDiffusionProcessingImg2Img) and self.swap_in_source: logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
for i in range(len(p.init_images)): if len(p.init_images) > 1: logger.status("Swap in %s", i) result, output, swapped = swap_face( self.source, p.init_images[i], source_faces_index=self.source_faces_index, faces_index=self.faces_index, model=self.model, enhancement_options=self.enhancement_options, gender_source=self.gender_source, gender_target=self.gender_target, source_hash_check=self.source_hash_check, target_hash_check=self.target_hash_check, device=self.device, mask_face=self.mask_face, select_source=self.select_source, face_model = self.face_model, source_folder = None, source_imgs = None, ) p.init_images[i] = result # result_path = get_image_path(p.init_images[i], p.outpath_samples, "", p.all_seeds[i], p.all_prompts[i], "txt", p=p, suffix="-swapped") # if len(output) != 0: # with open(result_path, 'w', encoding="utf8") as f: # f.writelines(output)
if shared.state.interrupted or shared.state.skipped: return else: logger.error("Please provide a source face") return
def postprocess(self, p: StableDiffusionProcessing, processed: Processed, *args): if self.enable:
logger.debug("*** Check postprocess")
reset_messaged() if check_process_halt(): return
if self.save_original or ((self.select_source == 2 and self.source_folder is not None and self.source_folder != "") or (self.select_source == 0 and self.source_imgs is not None and self.source is None)):
postprocess_run: bool = True
orig_images : List[Image.Image] = processed.images[processed.index_of_first_image:] orig_infotexts : List[str] = processed.infotexts[processed.index_of_first_image:]
result_images: List = processed.images # result_info: List = processed.infotexts
if self.swap_in_generated:
logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
if self.source is not None: # self.source_folder = None self.source_imgs = None
for i,(img,info) in enumerate(zip(orig_images, orig_infotexts)): if check_process_halt(): postprocess_run = False break if len(orig_images) > 1: logger.status("Swap in %s", i) result, output, swapped = swap_face( self.source, img, source_faces_index=self.source_faces_index, faces_index=self.faces_index, model=self.model, enhancement_options=self.enhancement_options, gender_source=self.gender_source, gender_target=self.gender_target, source_hash_check=self.source_hash_check, target_hash_check=self.target_hash_check, device=self.device, mask_face=self.mask_face, select_source=self.select_source, face_model = self.face_model, source_folder = self.source_folder, source_imgs = self.source_imgs, )
if self.select_source == 2 or (self.select_source == 0 and self.source_imgs is not None and self.source is None): if len(result) > 0 and swapped > 0: result_images.extend(result) suffix = "-swapped" for i,x in enumerate(result): try: img_path = save_image(result[i], p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png",info=info, p=p, suffix=suffix) except: logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)") elif len(result) == 0: logger.error("Cannot create a result image")
else: if result is not None and swapped > 0: result_images.append(result) suffix = "-swapped" try: img_path = save_image(result, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png",info=info, p=p, suffix=suffix) except: logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)") elif result is None: logger.error("Cannot create a result image") # if len(output) != 0: # split_fullfn = os.path.splitext(img_path[0]) # fullfn = split_fullfn[0] + ".txt" # with open(fullfn, 'w', encoding="utf8") as f: # f.writelines(output) if shared.opts.return_grid and len(result_images) > 2 and postprocess_run: grid = make_grid(result_images) result_images.insert(0, grid) try: save_image(grid, p.outpath_grids, "grid", p.all_seeds[0], p.all_prompts[0], shared.opts.grid_format, info=info, short_filename=not shared.opts.grid_extended_filename, p=p, grid=True) except: logger.error("Cannot save a grid - please, check SD WebUI Settings (Saving and Paths)") processed.images = result_images # processed.infotexts = result_info def postprocess_batch(self, p, *args, **kwargs): if self.enable and not self.save_original: logger.debug("*** Check postprocess_batch") images = kwargs["images"]
def postprocess_image(self, p, script_pp: scripts.PostprocessImageArgs, *args): if self.enable and self.swap_in_generated and not self.save_original and ((self.select_source == 0 and self.source is not None) or self.select_source == 1):
logger.debug("*** Check postprocess_image")
current_job_number = shared.state.job_no + 1 job_count = shared.state.job_count if current_job_number == job_count: reset_messaged() if check_process_halt(): return # if (self.source is not None and self.select_source == 0) or ((self.face_model is not None and self.face_model != "None") and self.select_source == 1): logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index) image: Image.Image = script_pp.image result, output, swapped = swap_face( self.source, image, source_faces_index=self.source_faces_index, faces_index=self.faces_index, model=self.model, enhancement_options=self.enhancement_options, gender_source=self.gender_source, gender_target=self.gender_target, source_hash_check=self.source_hash_check, target_hash_check=self.target_hash_check, device=self.device, mask_face=self.mask_face, select_source=self.select_source, face_model = self.face_model, source_folder = None, source_imgs = None, ) try: pp = scripts_postprocessing.PostprocessedImage(result) pp.info = {} p.extra_generation_params.update(pp.info) script_pp.image = pp.image
# if len(output) != 0: # result_path = get_image_path(script_pp.image, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "txt", p=p, suffix="-swapped") # if len(output) != 0: # with open(result_path, 'w', encoding="utf8") as f: # f.writelines(output) except: logger.error("Cannot create a result image")
class FaceSwapScriptExtras(scripts_postprocessing.ScriptPostprocessing): name = 'ReActor' order = 20000
def ui(self): with gr.Accordion(f"{app_title}", open=False):
enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}")
# TAB MAIN msgs: dict = { "extra_multiple_source": " | Сomparison grid as a result", } img, imgs, select_source, face_model, source_folder, save_original, mask_face, source_faces_index, gender_source, faces_index, gender_target, face_restorer_name, face_restorer_visibility, codeformer_weight, swap_in_source, swap_in_generated = ui_main.show(is_img2img=False, show_br=False, **msgs) # TAB UPSCALE restore_first, upscaler_name, upscaler_scale, upscaler_visibility = ui_upscale.show(show_br=False) # TAB TOOLS ui_tools.show() # TAB SETTINGS model, device, console_logging_level, source_hash_check, target_hash_check = ui_settings.show(hash_check_block=False) gr.Markdown("<span style='display:block;text-align:right;padding-right:3px;font-size:0.666em;margin: -9px 0'>by <a style='font-weight:normal' href='https://github.com/Gourieff' target='_blank'>Eugene Gourieff</a></span>")
args = { 'img': img, 'enable': enable, 'source_faces_index': source_faces_index, 'faces_index': faces_index, 'model': model, 'face_restorer_name': face_restorer_name, 'face_restorer_visibility': face_restorer_visibility, 'restore_first': restore_first, 'upscaler_name': upscaler_name, 'upscaler_scale': upscaler_scale, 'upscaler_visibility': upscaler_visibility, 'console_logging_level': console_logging_level, 'gender_source': gender_source, 'gender_target': gender_target, 'codeformer_weight': codeformer_weight, 'device': device, 'mask_face': mask_face, 'select_source': select_source, 'face_model': face_model, 'source_folder': source_folder, 'imgs': imgs, } return args
@property def upscaler(self) -> UpscalerData: for upscaler in shared.sd_upscalers: if upscaler.name == self.upscaler_name: return upscaler return None
@property def face_restorer(self) -> FaceRestoration: for face_restorer in shared.face_restorers: if face_restorer.name() == self.face_restorer_name: return face_restorer return None
@property def enhancement_options(self) -> EnhancementOptions: return EnhancementOptions( do_restore_first=self.restore_first, scale=self.upscaler_scale, upscaler=self.upscaler, face_restorer=self.face_restorer, upscale_visibility=self.upscaler_visibility, restorer_visibility=self.face_restorer_visibility, codeformer_weight=self.codeformer_weight, )
def process(self, pp: scripts_postprocessing.PostprocessedImage, **args): if args['enable']: reset_messaged() if check_process_halt(): return
global SWAPPER_MODELS_PATH self.source = args['img'] self.face_restorer_name = args['face_restorer_name'] self.upscaler_scale = args['upscaler_scale'] self.upscaler_visibility = args['upscaler_visibility'] self.face_restorer_visibility = args['face_restorer_visibility'] self.restore_first = args['restore_first'] self.upscaler_name = args['upscaler_name'] self.model = os.path.join(SWAPPER_MODELS_PATH, args['model']) self.console_logging_level = args['console_logging_level'] self.gender_source = args['gender_source'] self.gender_target = args['gender_target'] self.codeformer_weight = args['codeformer_weight'] self.device = args['device'] self.mask_face = args['mask_face'] self.select_source = args['select_source'] self.face_model = args['face_model'] self.source_folder = args['source_folder'] self.source_imgs = args['imgs'] if self.gender_source is None or self.gender_source == "No": self.gender_source = 0 if self.gender_target is None or self.gender_target == "No": self.gender_target = 0 self.source_faces_index = [ int(x) for x in args['source_faces_index'].strip(",").split(",") if x.isnumeric() ] self.faces_index = [ int(x) for x in args['faces_index'].strip(",").split(",") if x.isnumeric() ] if len(self.source_faces_index) == 0: self.source_faces_index = [0] if len(self.faces_index) == 0: self.faces_index = [0] if self.mask_face is None: self.mask_face = False
current_job_number = shared.state.job_no + 1 job_count = shared.state.job_count if current_job_number == job_count: reset_messaged()
set_Device(self.device)
logger.debug("We're here: process() 1") if (self.source is not None and self.select_source == 0) or ((self.face_model is not None and self.face_model != "None") and self.select_source == 1) or ((self.source_folder is not None and self.source_folder != "") and self.select_source == 2) or ((self.source_imgs is not None and self.source is None) and self.select_source == 0):
logger.debug("We're here: process() 2")
apply_logging_patch(self.console_logging_level) logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index) # if self.select_source != 2: image: Image.Image = pp.image result, output, swapped = swap_face( self.source, image, source_faces_index=self.source_faces_index, faces_index=self.faces_index, model=self.model, enhancement_options=self.enhancement_options, gender_source=self.gender_source, gender_target=self.gender_target, source_hash_check=True, target_hash_check=True, device=self.device, mask_face=self.mask_face, select_source=self.select_source, face_model=self.face_model, source_folder=self.source_folder, source_imgs=self.source_imgs, ) if self.select_source == 2 or (self.select_source == 0 and self.source_imgs is not None and self.source is None): if len(result) > 0 and swapped > 0: image = result[0] if len(result) > 1: grid = make_grid(result) result.insert(0, grid) image = grid pp.info["ReActor"] = True pp.image = image logger.status("---Done!---") else: logger.error("Cannot create a result image") else: try: pp.info["ReActor"] = True pp.image = result logger.status("---Done!---") except Exception: logger.error("Cannot create a result image") else: logger.error("Please provide a source face")12345678910111213141516171819202122232425262728293031323334353637383940import osfrom pathlib import Path
try: from modules.paths_internal import models_pathexcept: try: from modules.paths import models_path except: models_path = os.path.abspath("models")
IS_RUN: bool = FalseBASE_PATH = os.path.join(Path(__file__).parents[1])DEVICE_LIST: list = ["CPU", "CUDA"]
MODELS_PATH = models_pathSWAPPER_MODELS_PATH = os.path.join(MODELS_PATH, "insightface")REACTOR_MODELS_PATH = os.path.join(MODELS_PATH, "reactor")FACE_MODELS_PATH = os.path.join(REACTOR_MODELS_PATH, "faces")
if not os.path.exists(REACTOR_MODELS_PATH): os.makedirs(REACTOR_MODELS_PATH) if not os.path.exists(FACE_MODELS_PATH): os.makedirs(FACE_MODELS_PATH)
def updateDevice(): try: LAST_DEVICE_PATH = os.path.join(BASE_PATH, "last_device.txt") with open(LAST_DEVICE_PATH) as f: device = f.readline().strip() if device not in DEVICE_LIST: print(f"Error: Device {device} is not in DEVICE_LIST") device = DEVICE_LIST[0] print(f"Execution Provider has been set to {device}") except Exception as e: device = DEVICE_LIST[0] print(f"Error: {e}\nExecution Provider has been set to {device}") return device
DEVICE = updateDevice()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209import os, globfrom collections import Counterfrom PIL import Imagefrom math import isqrt, ceilfrom typing import Listimport loggingimport hashlibimport torchfrom safetensors.torch import save_file, safe_openfrom insightface.app.common import Face
from modules.images import FilenameGenerator, get_next_sequence_numberfrom modules import shared, script_callbacksfrom scripts.reactor_globals import DEVICE, BASE_PATH, FACE_MODELS_PATH
try: from modules.paths_internal import models_pathexcept: try: from modules.paths import models_path except: model_path = os.path.abspath("models")
MODELS_PATH = None
def set_Device(value): global DEVICE DEVICE = value with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt: txt.write(DEVICE)
def get_Device(): global DEVICE return DEVICE
def make_grid(image_list: List): # Count the occurrences of each image size in the image_list size_counter = Counter(image.size for image in image_list) # Get the most common image size (size with the highest count) common_size = size_counter.most_common(1)[0][0] # Filter the image_list to include only images with the common size image_list = [image for image in image_list if image.size == common_size] # Get the dimensions (width and height) of the common size size = common_size # If there are more than one image in the image_list if len(image_list) > 1: num_images = len(image_list) # Calculate the number of rows and columns for the grid rows = isqrt(num_images) cols = ceil(num_images / rows)
# Calculate the size of the square image square_size = (cols * size[0], rows * size[1])
# Create a new RGB image with the square size square_image = Image.new("RGB", square_size)
# Paste each image onto the square image at the appropriate position for i, image in enumerate(image_list): row = i // cols col = i % cols
square_image.paste(image, (col * size[0], row * size[1]))
# Return the resulting square image return square_image # Return None if there are no images or only one image in the image_list return None
def get_image_path(image, path, basename, seed=None, prompt=None, extension='png', p=None, suffix=""): namegen = FilenameGenerator(p, seed, prompt, image)
save_to_dirs = shared.opts.save_to_dirs
if save_to_dirs: dirname = namegen.apply(shared.opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /') path = os.path.join(path, dirname)
os.makedirs(path, exist_ok=True)
if seed is None: file_decoration = "" elif shared.opts.save_to_dirs: file_decoration = shared.opts.samples_filename_pattern or "[seed]" else: file_decoration = shared.opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
file_decoration = namegen.apply(file_decoration) + suffix
add_number = shared.opts.save_images_add_number or file_decoration == ''
if file_decoration != "" and add_number: file_decoration = f"-{file_decoration}"
if add_number: basecount = get_next_sequence_number(path, basename) fullfn = None for i in range(500): fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}" fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}") if not os.path.exists(fullfn): break else: fullfn = os.path.join(path, f"{file_decoration}.{extension}")
pnginfo = {}
params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo) # script_callbacks.before_image_saved_callback(params)
fullfn = params.filename
fullfn_without_extension, extension = os.path.splitext(params.filename) if hasattr(os, 'statvfs'): max_name_len = os.statvfs(path).f_namemax fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))] params.filename = fullfn_without_extension + extension fullfn = params.filename
return fullfn
def addLoggingLevel(levelName, levelNum, methodName=None): if not methodName: methodName = levelName.lower()
def logForLevel(self, message, *args, **kwargs): if self.isEnabledFor(levelNum): self._log(levelNum, message, args, **kwargs)
def logToRoot(message, *args, **kwargs): logging.log(levelNum, message, *args, **kwargs)
logging.addLevelName(levelNum, levelName) setattr(logging, levelName, levelNum) setattr(logging.getLoggerClass(), methodName, logForLevel) setattr(logging, methodName, logToRoot)
def get_image_md5hash(image: Image.Image): md5hash = hashlib.md5(image.tobytes()) return md5hash.hexdigest()
def save_face_model(face: Face, filename: str) -> None: try: tensors = { "bbox": torch.tensor(face["bbox"]), "kps": torch.tensor(face["kps"]), "det_score": torch.tensor(face["det_score"]), "landmark_3d_68": torch.tensor(face["landmark_3d_68"]), "pose": torch.tensor(face["pose"]), "landmark_2d_106": torch.tensor(face["landmark_2d_106"]), "embedding": torch.tensor(face["embedding"]), "gender": torch.tensor(face["gender"]), "age": torch.tensor(face["age"]), } save_file(tensors, filename) # print(f"Face model has been saved to '{filename}'") except Exception as e: print(f"Error: {e}")
def get_models(): global MODELS_PATH models_path_init = os.path.join(models_path, "insightface/*") models = glob.glob(models_path_init) models = [x for x in models if x.endswith(".onnx") or x.endswith(".pth")] models_names = [] for model in models: model_path = os.path.split(model) if MODELS_PATH is None: MODELS_PATH = model_path[0] model_name = model_path[1] models_names.append(model_name) return models_names
def load_face_model(filename: str): face = {} model_path = os.path.join(FACE_MODELS_PATH, filename) with safe_open(model_path, framework="pt") as f: for k in f.keys(): face[k] = f.get_tensor(k).numpy() return Face(face)
def get_facemodels(): models_path = os.path.join(FACE_MODELS_PATH, "*") models = glob.glob(models_path) models = [x for x in models if x.endswith(".safetensors")] return models
def get_model_names(get_models): models = get_models() names = ["None"] for x in models: names.append(os.path.basename(x)) return names
def get_images_from_folder(path: str): images_path = os.path.join(path, "*") images = glob.glob(images_path) return [Image.open(x) for x in images if x.endswith(('jpg', 'png', 'jpeg', 'webp', 'bmp'))]
def get_images_from_list(imgs: List): return [Image.open(os.path.abspath(x.name)) for x in imgs]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586from typing import List, Tuple
import cv2import modules.shared as sharedimport numpy as npimport torchfrom facexlib.parsing import init_parsing_modelfrom facexlib.utils.misc import img2tensorfrom torchvision.transforms.functional import normalizefrom scripts.reactor_inferencers.mask_generator import MaskGenerator
class BiSeNetMaskGenerator(MaskGenerator): def __init__(self) -> None: self.mask_model = init_parsing_model(device=shared.device)
def name(self): return "BiSeNet"
def generate_mask( self, face_image: np.ndarray, face_area_on_image: Tuple[int, int, int, int], affected_areas: List[str], mask_size: int, use_minimal_area: bool, fallback_ratio: float = 0.25, **kwargs, ) -> np.ndarray: # original_face_image = face_image face_image = face_image.copy() face_image = face_image[:, :, ::-1]
if use_minimal_area: face_image = MaskGenerator.mask_non_face_areas(face_image, face_area_on_image)
h, w, _ = face_image.shape
if w != 512 or h != 512: rw = (int(w * (512 / w)) // 8) * 8 rh = (int(h * (512 / h)) // 8) * 8 face_image = cv2.resize(face_image, dsize=(rw, rh))
face_tensor = img2tensor(face_image.astype("float32") / 255.0, float32=True) normalize(face_tensor, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True) face_tensor = torch.unsqueeze(face_tensor, 0).to(shared.device)
with torch.no_grad(): face = self.mask_model(face_tensor)[0] face = face.squeeze(0).cpu().numpy().argmax(0) face = face.copy().astype(np.uint8)
mask = self.__to_mask(face, affected_areas) if mask_size > 0: mask = cv2.dilate(mask, np.ones((5, 5), np.uint8), iterations=mask_size) if w != 512 or h != 512: mask = cv2.resize(mask, dsize=(w, h)) # """if MaskGenerator.calculate_mask_coverage(mask) < fallback_ratio: # logger.info("Use fallback mask generator") # mask = self.fallback_mask_generator.generate_mask( # original_face_image, face_area_on_image, use_minimal_area=True # )""" return mask
def __to_mask(self, face: np.ndarray, affected_areas: List[str]) -> np.ndarray: keep_face = "Face" in affected_areas keep_neck = "Neck" in affected_areas keep_hair = "Hair" in affected_areas keep_hat = "Hat" in affected_areas
mask = np.zeros((face.shape[0], face.shape[1], 3), dtype=np.uint8) num_of_class = np.max(face) for i in range(1, num_of_class + 1): index = np.where(face == i) if i < 14 and keep_face: mask[index[0], index[1], :] = [255, 255, 255] elif i == 14 and keep_neck: mask[index[0], index[1], :] = [255, 255, 255] elif i == 17 and keep_hair: mask[index[0], index[1], :] = [255, 255, 255] elif i == 18 and keep_hat: mask[index[0], index[1], :] = [255, 255, 255] return mask123456789101112131415161718192021222324252627282930313233343536from abc import ABC, abstractmethodfrom typing import Tuple
import cv2import numpy as np
class MaskGenerator(ABC): @abstractmethod def name(self) -> str: pass
@abstractmethod def generate_mask( self, face_image: np.ndarray, face_area_on_image: Tuple[int, int, int, int], **kwargs, ) -> np.ndarray: pass
@staticmethod def mask_non_face_areas(image: np.ndarray, face_area_on_image: Tuple[int, int, int, int]) -> np.ndarray: left, top, right, bottom = face_area_on_image image = image.copy() image[:top, :] = 0 image[bottom:, :] = 0 image[:, :left] = 0 image[:, right:] = 0 return image
@staticmethod def calculate_mask_coverage(mask: np.ndarray): gray_mask = cv2.cvtColor(mask, cv2.COLOR_RGB2GRAY) non_black_pixels = np.count_nonzero(gray_mask) total_pixels = gray_mask.size return non_black_pixels / total_pixels12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import loggingimport copyimport sys
from modules import sharedfrom scripts.reactor_globals import IS_RUNfrom scripts.reactor_helpers import addLoggingLevel
class ColoredFormatter(logging.Formatter): COLORS = { "DEBUG": "\033[0;36m", # CYAN "STATUS": "\033[38;5;173m", # Calm ORANGE "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 loggerlogger = logging.getLogger("ReActor")logger.propagate = False
# Add Custom LeveladdLoggingLevel("STATUS", logging.INFO + 5)
# Add handler if we don't have one.if not logger.handlers: handler = logging.StreamHandler(sys.stdout) handler.setFormatter( ColoredFormatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s","%H:%M:%S") ) logger.addHandler(handler)
# Configure loggerloglevel_string = getattr(shared.cmd_opts, "reactor_loglevel", "INFO")loglevel = getattr(logging, loglevel_string.upper(), "info")logger.setLevel(loglevel)
def set_Run(value): global IS_RUN IS_RUN = value
def get_Run(): global IS_RUN return IS_RUN123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715import copyimport osfrom dataclasses import dataclassfrom typing import List, Union
import cv2import numpy as npfrom PIL import Image
import insightfacefrom insightface.app.common import Face
from scripts.reactor_globals import FACE_MODELS_PATHfrom scripts.reactor_helpers import ( get_image_md5hash, get_Device, save_face_model, load_face_model, get_images_from_folder, get_images_from_list)from scripts.console_log_patch import apply_logging_patch
from modules.face_restoration import FaceRestorationtry: # A1111 from modules import codeformer_modelexcept: # SD.Next from modules.postprocess import codeformer_modelfrom modules.upscaler import UpscalerDatafrom modules.shared import statefrom scripts.reactor_logger import loggerfrom reactor_modules.reactor_mask import apply_face_mask
try: from modules.paths_internal import models_pathexcept: try: from modules.paths import models_path except: models_path = os.path.abspath("models")
import warnings
np.warnings = warningsnp.warnings.filterwarnings('ignore')
DEVICE = get_Device()if DEVICE == "CUDA": PROVIDERS = ["CUDAExecutionProvider"]else: PROVIDERS = ["CPUExecutionProvider"]
@dataclassclass EnhancementOptions: do_restore_first: bool = True scale: int = 1 upscaler: UpscalerData = None upscale_visibility: float = 0.5 face_restorer: FaceRestoration = None restorer_visibility: float = 0.5 codeformer_weight: float = 0.5
MESSAGED_STOPPED = FalseMESSAGED_SKIPPED = False
def reset_messaged(): global MESSAGED_STOPPED, MESSAGED_SKIPPED if not state.interrupted: MESSAGED_STOPPED = False if not state.skipped: MESSAGED_SKIPPED = False
def check_process_halt(msgforced: bool = False): global MESSAGED_STOPPED, MESSAGED_SKIPPED if state.interrupted: if not MESSAGED_STOPPED or msgforced: logger.status("Stopped by User") MESSAGED_STOPPED = True return True if state.skipped: if not MESSAGED_SKIPPED or msgforced: logger.status("Skipped by User") MESSAGED_SKIPPED = True return True return False
FS_MODEL = NoneANALYSIS_MODEL = NoneMASK_MODEL = None
CURRENT_FS_MODEL_PATH = NoneCURRENT_MASK_MODEL_PATH = None
SOURCE_FACES = NoneSOURCE_IMAGE_HASH = NoneTARGET_FACES = NoneTARGET_IMAGE_HASH = NoneSOURCE_FACES_LIST = []SOURCE_IMAGE_LIST_HASH = []
def clear_faces_list(): global SOURCE_FACES_LIST, SOURCE_IMAGE_LIST_HASH SOURCE_FACES_LIST = [] SOURCE_IMAGE_LIST_HASH = [] logger.status("Source Images Hash has been reset (for Multiple or Folder Source)")
def getAnalysisModel(): global ANALYSIS_MODEL if ANALYSIS_MODEL is None: ANALYSIS_MODEL = insightface.app.FaceAnalysis( name="buffalo_l", providers=PROVIDERS, root=os.path.join(models_path, "insightface") # note: allowed_modules=['detection', 'genderage'] ) return ANALYSIS_MODEL
def getFaceSwapModel(model_path: str): global FS_MODEL global CURRENT_FS_MODEL_PATH if CURRENT_FS_MODEL_PATH is None or CURRENT_FS_MODEL_PATH != model_path: CURRENT_FS_MODEL_PATH = model_path FS_MODEL = insightface.model_zoo.get_model(model_path, providers=PROVIDERS)
return FS_MODEL
def restore_face(image: Image, enhancement_options: EnhancementOptions): result_image = image
if check_process_halt(msgforced=True): return result_image if enhancement_options.face_restorer is not None: original_image = result_image.copy() logger.status("Restoring the face with %s", enhancement_options.face_restorer.name()) numpy_image = np.array(result_image) if enhancement_options.face_restorer.name() == "CodeFormer": numpy_image = codeformer_model.codeformer.restore( numpy_image, w=enhancement_options.codeformer_weight ) else: numpy_image = enhancement_options.face_restorer.restore(numpy_image) restored_image = Image.fromarray(numpy_image) result_image = Image.blend( original_image, restored_image, enhancement_options.restorer_visibility ) return result_image
def upscale_image(image: Image, enhancement_options: EnhancementOptions): result_image = image
if check_process_halt(msgforced=True): return result_image if enhancement_options.upscaler is not None and enhancement_options.upscaler.name != "None": original_image = result_image.copy() logger.status( "Upscaling with %s scale = %s", enhancement_options.upscaler.name, enhancement_options.scale, ) result_image = enhancement_options.upscaler.scaler.upscale( original_image, enhancement_options.scale, enhancement_options.upscaler.data_path ) if enhancement_options.scale == 1: result_image = Image.blend( original_image, result_image, enhancement_options.upscale_visibility ) return result_image
def enhance_image(image: Image, enhancement_options: EnhancementOptions): result_image = image if check_process_halt(msgforced=True): return result_image if enhancement_options.do_restore_first: result_image = restore_face(result_image, enhancement_options) result_image = upscale_image(result_image, enhancement_options)
else:
result_image = upscale_image(result_image, enhancement_options) result_image = restore_face(result_image, enhancement_options)
return result_image
def enhance_image_and_mask(image: Image.Image, enhancement_options: EnhancementOptions,target_img_orig:Image.Image,entire_mask_image:Image.Image)->Image.Image: result_image = image if check_process_halt(msgforced=True): return result_image if enhancement_options.do_restore_first: result_image = restore_face(result_image, enhancement_options) result_image = Image.composite(result_image,target_img_orig,entire_mask_image) result_image = upscale_image(result_image, enhancement_options)
else:
result_image = upscale_image(result_image, enhancement_options) entire_mask_image = Image.fromarray(cv2.resize(np.array(entire_mask_image),result_image.size, interpolation=cv2.INTER_AREA)).convert("L") result_image = Image.composite(result_image,target_img_orig,entire_mask_image) result_image = restore_face(result_image, enhancement_options)
return result_image
def get_gender(face, face_index): gender = [ x.sex for x in face ] gender.reverse() try: face_gender = gender[face_index] except: logger.error("Gender Detection: No face with index = %s was found", face_index) return "None" return face_gender
def get_face_gender( face, face_index, gender_condition, operated: str, gender_detected,): face_gender = gender_detected if face_gender == "None": return None, 0 logger.status("%s Face %s: Detected Gender -%s-", operated, face_index, face_gender) if (gender_condition == 1 and face_gender == "F") or (gender_condition == 2 and face_gender == "M"): logger.status("OK - Detected Gender matches Condition") try: return sorted(face, key=lambda x: x.bbox[0])[face_index], 0 except IndexError: return None, 0 else: logger.status("WRONG - Detected Gender doesn't match Condition") return sorted(face, key=lambda x: x.bbox[0])[face_index], 1
def get_face_age(face, face_index): age = [ x.age for x in face ] age.reverse() try: face_age = age[face_index] except: logger.error("Age Detection: No face with index = %s was found", face_index) return "None" return face_age
def half_det_size(det_size): logger.status("Trying to halve 'det_size' parameter") return (det_size[0] // 2, det_size[1] // 2)
def analyze_faces(img_data: np.ndarray, det_size=(640, 640)): logger.info("Applied Execution Provider: %s", PROVIDERS[0]) face_analyser = copy.deepcopy(getAnalysisModel()) face_analyser.prepare(ctx_id=0, det_size=det_size) return face_analyser.get(img_data)
def get_face_single(img_data: np.ndarray, face, face_index=0, det_size=(640, 640), gender_source=0, gender_target=0):
buffalo_path = os.path.join(models_path, "insightface/models/buffalo_l.zip") if os.path.exists(buffalo_path): os.remove(buffalo_path)
face_age = "None" try: face_age = get_face_age(face, face_index) except: logger.error("Cannot detect any Age for Face index = %s", face_index) face_gender = "None" try: face_gender = get_gender(face, face_index) gender_detected = face_gender face_gender = "Female" if face_gender == "F" else ("Male" if face_gender == "M" else "None") except: logger.error("Cannot detect any Gender for Face index = %s", face_index) if gender_source != 0: if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320: det_size_half = half_det_size(det_size) return get_face_single(img_data, analyze_faces(img_data, det_size_half), face_index, det_size_half, gender_source, gender_target) faces, wrong_gender = get_face_gender(face,face_index,gender_source,"Source",gender_detected) return faces, wrong_gender, face_age, face_gender
if gender_target != 0: if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320: det_size_half = half_det_size(det_size) return get_face_single(img_data, analyze_faces(img_data, det_size_half), face_index, det_size_half, gender_source, gender_target) faces, wrong_gender = get_face_gender(face,face_index,gender_target,"Target",gender_detected) return faces, wrong_gender, face_age, face_gender if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320: det_size_half = half_det_size(det_size) return get_face_single(img_data, analyze_faces(img_data, det_size_half), face_index, det_size_half, gender_source, gender_target)
try: return sorted(face, key=lambda x: x.bbox[0])[face_index], 0, face_age, face_gender except IndexError: return None, 0, face_age, face_gender
def swap_face( source_img: Image.Image, target_img: Image.Image, model: Union[str, None] = None, source_faces_index: List[int] = [0], faces_index: List[int] = [0], enhancement_options: Union[EnhancementOptions, None] = None, gender_source: int = 0, gender_target: int = 0, source_hash_check: bool = True, target_hash_check: bool = False, device: str = "CPU", mask_face: bool = False, select_source: int = 0, face_model: str = "None", source_folder: str = "", source_imgs: Union[List, None] = None,): global SOURCE_FACES, SOURCE_IMAGE_HASH, TARGET_FACES, TARGET_IMAGE_HASH, PROVIDERS, SOURCE_FACES_LIST, SOURCE_IMAGE_LIST_HASH
result_image = target_img
PROVIDERS = ["CUDAExecutionProvider"] if device == "CUDA" else ["CPUExecutionProvider"] if check_process_halt(): return result_image, [], 0 if model is not None:
if isinstance(source_img, str): # source_img is a base64 string import base64, io if 'base64,' in source_img: # check if the base64 string has a data URL scheme # split the base64 string to get the actual base64 encoded image data base64_data = source_img.split('base64,')[-1] # decode base64 string to bytes img_bytes = base64.b64decode(base64_data) else: # if no data URL scheme, just decode img_bytes = base64.b64decode(source_img) source_img = Image.open(io.BytesIO(img_bytes))
target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
target_img_orig = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR) entire_mask_image = np.zeros_like(np.array(target_img))
output: List = [] output_info: str = "" swapped = 0
# ***************** # SWAP from FOLDER or MULTIPLE images: if (select_source == 0 and source_imgs is not None) or (select_source == 2 and (source_folder is not None and source_folder != "")):
result = []
source_images = get_images_from_folder(source_folder) if select_source == 2 else get_images_from_list(source_imgs)
if len(source_images) > 0: source_img_ff = [] source_faces_ff = [] for i, source_image in enumerate(source_images):
source_image = cv2.cvtColor(np.array(source_image), cv2.COLOR_RGB2BGR) source_img_ff.append(source_image)
if source_hash_check:
source_image_md5hash = get_image_md5hash(source_image)
if len(SOURCE_IMAGE_LIST_HASH) == 0: SOURCE_IMAGE_LIST_HASH = [source_image_md5hash] source_image_same = False elif len(SOURCE_IMAGE_LIST_HASH) == i: SOURCE_IMAGE_LIST_HASH.append(source_image_md5hash) source_image_same = False else: source_image_same = True if SOURCE_IMAGE_LIST_HASH[i] == source_image_md5hash else False if not source_image_same: SOURCE_IMAGE_LIST_HASH[i] = source_image_md5hash
logger.info("(Image %s) Source Image MD5 Hash = %s", i, SOURCE_IMAGE_LIST_HASH[i]) logger.info("(Image %s) Source Image the Same? %s", i, source_image_same)
if len(SOURCE_FACES_LIST) == 0: logger.status(f"Analyzing Source Image {i}...") source_faces = analyze_faces(source_image) SOURCE_FACES_LIST = [source_faces] elif len(SOURCE_FACES_LIST) == i and not source_image_same: logger.status(f"Analyzing Source Image {i}...") source_faces = analyze_faces(source_image) SOURCE_FACES_LIST.append(source_faces) elif len(SOURCE_FACES_LIST) != i and not source_image_same: logger.status(f"Analyzing Source Image {i}...") source_faces = analyze_faces(source_image) SOURCE_FACES_LIST[i] = source_faces elif source_image_same: logger.status("(Image %s) Using Hashed Source Face(s) Model...", i) source_faces = SOURCE_FACES_LIST[i]
else: logger.status(f"Analyzing Source Image {i}...") source_faces = analyze_faces(source_image)
if source_faces is not None: source_faces_ff.append(source_faces) if len(source_faces_ff) > 0:
if target_hash_check: target_image_md5hash = get_image_md5hash(target_img)
if TARGET_IMAGE_HASH is None: TARGET_IMAGE_HASH = target_image_md5hash target_image_same = False else: target_image_same = True if TARGET_IMAGE_HASH == target_image_md5hash else False if not target_image_same: TARGET_IMAGE_HASH = target_image_md5hash
logger.info("Target Image MD5 Hash = %s", TARGET_IMAGE_HASH) logger.info("Target Image the Same? %s", target_image_same) if TARGET_FACES is None or not target_image_same: logger.status("Analyzing Target Image...") target_faces = analyze_faces(target_img) TARGET_FACES = target_faces elif target_image_same: logger.status("Using Hashed Target Face(s) Model...") target_faces = TARGET_FACES else: logger.status("Analyzing Target Image...") target_faces = analyze_faces(target_img)
for i,source_faces in enumerate(source_faces_ff):
logger.status("(Image %s) Detecting Source Face, Index = %s", i, source_faces_index[0]) source_face, wrong_gender, source_age, source_gender = get_face_single(source_img_ff[i], source_faces, face_index=source_faces_index[0], gender_source=gender_source) if source_age != "None" or source_gender != "None": logger.status("(Image %s) Detected: -%s- y.o. %s", i, source_age, source_gender)
if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index): logger.status("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.") elif source_face is not None:
result_image, output, swapped = operate(source_img_ff[i],target_img,target_img_orig,model,source_faces_index,faces_index,source_faces,target_faces,gender_source,gender_target,source_face,wrong_gender,source_age,source_gender,output,swapped,mask_face,entire_mask_image,enhancement_options)
result.append(result_image)
result = [result_image] if len(result) == 0 else result return result, output, swapped # END # ***************** # *********************** # SWAP from IMG or MODEL:
else: if select_source == 0 and source_img is not None: source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
if source_hash_check:
source_image_md5hash = get_image_md5hash(source_img)
if SOURCE_IMAGE_HASH is None: SOURCE_IMAGE_HASH = source_image_md5hash source_image_same = False else: source_image_same = True if SOURCE_IMAGE_HASH == source_image_md5hash else False if not source_image_same: SOURCE_IMAGE_HASH = source_image_md5hash
logger.info("Source Image MD5 Hash = %s", SOURCE_IMAGE_HASH) logger.info("Source Image the Same? %s", source_image_same)
if SOURCE_FACES is None or not source_image_same: logger.status("Analyzing Source Image...") source_faces = analyze_faces(source_img) SOURCE_FACES = source_faces elif source_image_same: logger.status("Using Hashed Source Face(s) Model...") source_faces = SOURCE_FACES
else: logger.status("Analyzing Source Image...") source_faces = analyze_faces(source_img) elif select_source == 1 and (face_model is not None and face_model != "None"): source_face_model = [load_face_model(face_model)] if source_face_model is not None: source_faces_index = [0] source_faces = source_face_model logger.status("Using Loaded Source Face Model...") else: logger.error(f"Cannot load Face Model File: {face_model}.safetensors") else: logger.error("Cannot detect any Source") return result_image, [], 0
if source_faces is not None:
if target_hash_check: target_image_md5hash = get_image_md5hash(target_img)
if TARGET_IMAGE_HASH is None: TARGET_IMAGE_HASH = target_image_md5hash target_image_same = False else: target_image_same = True if TARGET_IMAGE_HASH == target_image_md5hash else False if not target_image_same: TARGET_IMAGE_HASH = target_image_md5hash
logger.info("Target Image MD5 Hash = %s", TARGET_IMAGE_HASH) logger.info("Target Image the Same? %s", target_image_same) if TARGET_FACES is None or not target_image_same: logger.status("Analyzing Target Image...") target_faces = analyze_faces(target_img) TARGET_FACES = target_faces elif target_image_same: logger.status("Using Hashed Target Face(s) Model...") target_faces = TARGET_FACES else: logger.status("Analyzing Target Image...") target_faces = analyze_faces(target_img)
logger.status("Detecting Source Face, Index = %s", source_faces_index[0]) if select_source == 0 and source_img is not None: source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, source_faces, face_index=source_faces_index[0], gender_source=gender_source) else: source_face = sorted(source_faces, key=lambda x: x.bbox[0])[source_faces_index[0]] wrong_gender = 0 source_age = source_face["age"] source_gender = "Female" if source_face["gender"] == 0 else "Male" if source_age != "None" or source_gender != "None": logger.status("Detected: -%s- y.o. %s", source_age, source_gender)
output_info = f"SourceFaceIndex={source_faces_index[0]};Age={source_age};Gender={source_gender}\n" output.append(output_info) if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index): logger.status("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.") elif source_face is not None:
result_image, output, swapped = operate(source_img,target_img,target_img_orig,model,source_faces_index,faces_index,source_faces,target_faces,gender_source,gender_target,source_face,wrong_gender,source_age,source_gender,output,swapped,mask_face,entire_mask_image,enhancement_options) else: logger.status("No source face(s) in the provided Index") else: logger.status("No source face(s) found") return result_image, output, swapped # END # ********************** return result_image, [], 0
def build_face_model(image: Image.Image, name: str): if image is None: error_msg = "Please load an Image" logger.error(error_msg) return error_msg if name is None: error_msg = "Please filled out the 'Face Model Name' field" logger.error(error_msg) return error_msg apply_logging_patch(1) image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) logger.status("Building Face Model...") face_model = analyze_faces(image) if face_model is not None and len(face_model) > 0: face_model_path = os.path.join(FACE_MODELS_PATH, name + ".safetensors") save_face_model(face_model[0],face_model_path) logger.status("--Done!--") done_msg = f"Face model has been saved to '{face_model_path}'" logger.status(done_msg) return done_msg else: no_face_msg = "No face found, please try another image" logger.error(no_face_msg) return no_face_msg
def operate( source_img, target_img, target_img_orig, model, source_faces_index, faces_index, source_faces, target_faces, gender_source, gender_target, source_face, wrong_gender, source_age, source_gender, output, swapped, mask_face, entire_mask_image, enhancement_options, ): result = target_img face_swapper = getFaceSwapModel(model)
source_face_idx = 0
for face_num in faces_index: if check_process_halt(): return result_image, [], 0 if len(source_faces_index) > 1 and source_face_idx > 0: logger.status("Detecting Source Face, Index = %s", source_faces_index[source_face_idx]) source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, source_faces, face_index=source_faces_index[source_face_idx], gender_source=gender_source) if source_age != "None" or source_gender != "None": logger.status("Detected: -%s- y.o. %s", source_age, source_gender)
output_info = f"SourceFaceIndex={source_faces_index[source_face_idx]};Age={source_age};Gender={source_gender}\n" output.append(output_info)
source_face_idx += 1
if source_face is not None and wrong_gender == 0: logger.status("Detecting Target Face, Index = %s", face_num) target_face, wrong_gender, target_age, target_gender = get_face_single(target_img, target_faces, face_index=face_num, gender_target=gender_target) if target_age != "None" or target_gender != "None": logger.status("Detected: -%s- y.o. %s", target_age, target_gender)
output_info = f"TargetFaceIndex={face_num};Age={target_age};Gender={target_gender}\n" output.append(output_info) if target_face is not None and wrong_gender == 0: logger.status("Swapping Source into Target") swapped_image = face_swapper.get(result, target_face, source_face) if mask_face: result = apply_face_mask(swapped_image=swapped_image,target_image=result,target_face=target_face,entire_mask_image=entire_mask_image) else: result = swapped_image swapped += 1 elif wrong_gender == 1: wrong_gender = 0 if source_face_idx == len(source_faces_index): result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB)) if enhancement_options is not None and len(source_faces_index) > 1: result_image = enhance_image(result_image, enhancement_options) return result_image, output, swapped else: logger.status(f"No target face found for {face_num}") elif wrong_gender == 1: wrong_gender = 0 if source_face_idx == len(source_faces_index): result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB)) if enhancement_options is not None and len(source_faces_index) > 1: result_image = enhance_image(result_image, enhancement_options) return result_image, output, swapped else: logger.status(f"No source face found for face number {source_face_idx}.")
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB)) if enhancement_options is not None and swapped > 0: if mask_face and entire_mask_image is not None: result_image = enhance_image_and_mask(result_image, enhancement_options,Image.fromarray(target_img_orig),Image.fromarray(entire_mask_image).convert("L")) else: result_image = enhance_image(result_image, enhancement_options) elif mask_face and entire_mask_image is not None and swapped > 0: result_image = Image.composite(result_image,Image.fromarray(target_img_orig),Image.fromarray(entire_mask_image).convert("L")) return result_image, output, swapped12345678910app_title = "ReActor"version_flag = "v0.6.0-a1"
from scripts.reactor_logger import logger, get_Run, set_Run
is_run = get_Run()
if not is_run: logger.status(f"Running {version_flag}") set_Run(True)sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/bug_report.ymlAdded+58
sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/config.ymlAdded+5
sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/feature_request.ymlAdded+16
sd-webui-reactor-main/sd-webui-reactor-main/.gitignoreAdded+10
sd-webui-reactor-main/sd-webui-reactor-main/API.mdAdded+71
sd-webui-reactor-main/sd-webui-reactor-main/LICENSEAdded+661
sd-webui-reactor-main/sd-webui-reactor-main/README.mdAdded+361
sd-webui-reactor-main/sd-webui-reactor-main/README_RU.mdAdded+370
sd-webui-reactor-main/sd-webui-reactor-main/example/IamSFW.jpgAdded

sd-webui-reactor-main/sd-webui-reactor-main/example/api_example.pyAdded+103
sd-webui-reactor-main/sd-webui-reactor-main/example/api_external.curlAdded
sd-webui-reactor-main/sd-webui-reactor-main/example/api_external.jsonAdded
sd-webui-reactor-main/sd-webui-reactor-main/example/insightface-0.7.3-cp310-cp310-win_amd64.whlAdded
sd-webui-reactor-main/sd-webui-reactor-main/install.pyAdded+147
sd-webui-reactor-main/sd-webui-reactor-main/reactor_modules/reactor_mask.pyAdded+176
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/__init__.pyAdded+4
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_main_ui.pyAdded+182
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_settings_ui.pyAdded+77
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_tools_ui.pyAdded+25
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_upscale_ui.pyAdded+39
sd-webui-reactor-main/sd-webui-reactor-main/requirements.txtAdded+3
sd-webui-reactor-main/sd-webui-reactor-main/scripts/console_log_patch.pyAdded+120
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_api.pyAdded+118
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_entities/face.pyAdded+147
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_entities/rect.pyAdded+78
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_faceswap.pyAdded+577
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_globals.pyAdded+40
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_helpers.pyAdded+209
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_inferencers/bisenet_mask_generator.pyAdded+86
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_inferencers/mask_generator.pyAdded+36
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_logger.pyAdded+55
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_swapper.pyAdded+715
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_version.pyAdded+10