Jupy commited on
Commit
25b978a
1 Parent(s): a49548b

Upload 33 files

Browse files
Files changed (33) hide show
  1. sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/bug_report.yml +58 -0
  2. sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/config.yml +5 -0
  3. sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/feature_request.yml +16 -0
  4. sd-webui-reactor-main/sd-webui-reactor-main/.gitignore +10 -0
  5. sd-webui-reactor-main/sd-webui-reactor-main/API.md +71 -0
  6. sd-webui-reactor-main/sd-webui-reactor-main/LICENSE +661 -0
  7. sd-webui-reactor-main/sd-webui-reactor-main/README.md +361 -0
  8. sd-webui-reactor-main/sd-webui-reactor-main/README_RU.md +370 -0
  9. sd-webui-reactor-main/sd-webui-reactor-main/example/IamSFW.jpg +0 -0
  10. sd-webui-reactor-main/sd-webui-reactor-main/example/api_example.py +103 -0
  11. sd-webui-reactor-main/sd-webui-reactor-main/example/api_external.curl +0 -0
  12. sd-webui-reactor-main/sd-webui-reactor-main/example/api_external.json +0 -0
  13. sd-webui-reactor-main/sd-webui-reactor-main/example/insightface-0.7.3-cp310-cp310-win_amd64.whl +0 -0
  14. sd-webui-reactor-main/sd-webui-reactor-main/install.py +147 -0
  15. sd-webui-reactor-main/sd-webui-reactor-main/reactor_modules/reactor_mask.py +176 -0
  16. sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/__init__.py +4 -0
  17. sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_main_ui.py +182 -0
  18. sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_settings_ui.py +77 -0
  19. sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_tools_ui.py +25 -0
  20. sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_upscale_ui.py +39 -0
  21. sd-webui-reactor-main/sd-webui-reactor-main/requirements.txt +3 -0
  22. sd-webui-reactor-main/sd-webui-reactor-main/scripts/console_log_patch.py +120 -0
  23. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_api.py +118 -0
  24. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_entities/face.py +147 -0
  25. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_entities/rect.py +78 -0
  26. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_faceswap.py +577 -0
  27. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_globals.py +40 -0
  28. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_helpers.py +209 -0
  29. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_inferencers/bisenet_mask_generator.py +86 -0
  30. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_inferencers/mask_generator.py +36 -0
  31. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_logger.py +55 -0
  32. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_swapper.py +715 -0
  33. sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_version.py +10 -0
sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/bug_report.yml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Bug Report
2
+ description: You think somethings is broken
3
+ labels: ["bug", "new"]
4
+
5
+ body:
6
+ - type: checkboxes
7
+ attributes:
8
+ label: First, confirm
9
+ 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.
10
+ options:
11
+ - label: I have read the [instruction](https://github.com/Gourieff/sd-webui-reactor/blob/main/README.md) carefully
12
+ required: true
13
+ - label: I have searched the existing issues
14
+ required: true
15
+ - label: I have updated the extension to the latest version
16
+ required: true
17
+ - type: markdown
18
+ attributes:
19
+ value: |
20
+ *Please fill this form with as much information as possible and *provide screenshots if possible**
21
+ - type: textarea
22
+ id: what-did
23
+ attributes:
24
+ label: What happened?
25
+ description: Tell what happened in a very clear and simple way
26
+ validations:
27
+ required: true
28
+ - type: textarea
29
+ id: steps
30
+ attributes:
31
+ label: Steps to reproduce the problem
32
+ description: Please provide with precise step by step instructions on how to reproduce the bug
33
+ value: |
34
+ 1. Go to ....
35
+ 2. Press ....
36
+ 3. ...
37
+ validations:
38
+ required: true
39
+ - type: textarea
40
+ id: sysinfo
41
+ attributes:
42
+ label: Sysinfo
43
+ 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.
44
+ validations:
45
+ required: true
46
+ - type: textarea
47
+ id: logs
48
+ attributes:
49
+ label: Relevant console log
50
+ 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.
51
+ render: Shell
52
+ validations:
53
+ required: true
54
+ - type: textarea
55
+ id: misc
56
+ attributes:
57
+ label: Additional information
58
+ description: Please provide with any relevant additional info or context.
sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ blank_issues_enabled: false
2
+ contact_links:
3
+ - name: ReActor Extension Community Support
4
+ url: https://github.com/Gourieff/sd-webui-reactor/discussions
5
+ about: Please ask and answer questions here.
sd-webui-reactor-main/sd-webui-reactor-main/.github/ISSUE_TEMPLATE/feature_request.yml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Feature request
2
+ description: Suggest an idea for this project
3
+ title: "[Feature]: "
4
+ labels: ["enhancement", "new"]
5
+
6
+ body:
7
+ - type: textarea
8
+ id: description
9
+ attributes:
10
+ label: Feature description
11
+ description: Describe the feature in a clear and simple way
12
+ value:
13
+ - type: markdown
14
+ attributes:
15
+ value: |
16
+ 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)
sd-webui-reactor-main/sd-webui-reactor-main/.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.pyc
5
+
6
+ .vscode/
7
+
8
+ example
9
+ *.txt
10
+ !requirements.txt
sd-webui-reactor-main/sd-webui-reactor-main/API.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # <div align="center">ReActor Extension API</div>
2
+
3
+ <div align="center">
4
+
5
+ [Built-in SD WebUI API](#built-in-sd-webui-api) | [External ReActor API](#external-reactor-api)
6
+
7
+ ---
8
+ </div>
9
+
10
+ Gourieff's **ReActor** SD WebUI Extension allows to operate via API: both built-in and external (POST and GET requests).
11
+
12
+
13
+ ## Built-in SD WebUI API
14
+
15
+ This API is actual if you use Automatic1111 stable-diffusion-webui.
16
+
17
+ First of all - check the [SD Web API Wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/API) for how to use the API.
18
+
19
+ * Call `requests.get(url=f'{address}/sdapi/v1/script-info')` to find the args that ReActor needs;
20
+ * Define ReActor script args and add like this `"alwayson_scripts": {"reactor":{"args":args}}` in the payload;
21
+ * Call the API.
22
+
23
+ You can find the [full usage example](./example/api_example.py) with all the available parameters and discriptions in the "example" folder.
24
+
25
+ ## External ReActor API
26
+
27
+ ReActor extension supports for external calls via POST or GET requests while your SD WebUI server is working.
28
+
29
+ > :warning: Source and Target images must be "base64".
30
+
31
+ Example:
32
+
33
+ ```
34
+ curl -X POST \
35
+ 'http://127.0.0.1:7860/reactor/image' \
36
+ -H 'accept: application/json' \
37
+ -H 'Content-Type: application/json' \
38
+ -d '{
39
+ "source_image": "data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABQAAD/7g...",
40
+ "target_image": "data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABCAAD/7g...",
41
+ "source_faces_index": [0],
42
+ "face_index": [0],
43
+ "upscaler": "4x_Struzan_300000",
44
+ "scale": 2,
45
+ "upscale_visibility": 1,
46
+ "face_restorer": "CodeFormer",
47
+ "restorer_visibility": 1,
48
+ "restore_first": 1,
49
+ "model": "inswapper_128.onnx",
50
+ "gender_source": 0,
51
+ "gender_target": 0,
52
+ "save_to_file": 0,
53
+ "result_file_path": ""
54
+ }'
55
+ ```
56
+
57
+ * Set `"upscaler"` to `"None"` and `"scale"` to `1` if you don't need to upscale;
58
+ * Set `"save_to_file"` to `1` if you need to save result to a file;
59
+ * `"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"`.
60
+
61
+ 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).
62
+
63
+ As a result you recieve a "base64" image:
64
+
65
+ ```
66
+ {"image":"iVBORw0KGgoAAAANSUhEUgAABlAAAARQCAIAAAAdiYuqAAEAAElEQVR4nOz9+ZMlSXImBn6qau4vIjKzzr5wzwBCDrm/7f+/K7IHV3ZkhUIuyZHlkBhiMGig0Y0..."}
67
+ ```
68
+
69
+ A list of available models can be seen by GET:
70
+ * http://127.0.0.1:7860/reactor/models
71
+ * http://127.0.0.1:7860/reactor/upscalers
sd-webui-reactor-main/sd-webui-reactor-main/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
sd-webui-reactor-main/sd-webui-reactor-main/README.md ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_EN.png?raw=true" alt="logo" width="180px"/>
4
+
5
+ ![Version](https://img.shields.io/badge/version-0.6.0_alpha1-lightgreen?style=for-the-badge&labelColor=darkgreen)
6
+
7
+ <a href="https://boosty.to/artgourieff" target="_blank">
8
+ <img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/>
9
+ <br>
10
+ <sup>
11
+ Support This Project
12
+ </sup>
13
+ </a>
14
+
15
+ <hr>
16
+
17
+ [![Commit activity](https://img.shields.io/github/commit-activity/t/Gourieff/sd-webui-reactor/main?cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/commits/main)
18
+ ![Last commit](https://img.shields.io/github/last-commit/Gourieff/sd-webui-reactor/main?cacheSeconds=0)
19
+ [![Opened issues](https://img.shields.io/github/issues/Gourieff/sd-webui-reactor?color=red)](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
20
+ [![Closed issues](https://img.shields.io/github/issues-closed/Gourieff/sd-webui-reactor?color=green&cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/issues?q=is%3Aissue+is%3Aclosed)
21
+ ![License](https://img.shields.io/github/license/Gourieff/sd-webui-reactor)
22
+
23
+ English | [Русский](/README_RU.md)
24
+
25
+ # ReActor for Stable Diffusion
26
+
27
+ ### The Fast and Simple FaceSwap Extension with a lot of improvements and without NSFW filter (uncensored, use it on your own [responsibility](#disclaimer))
28
+
29
+ ---
30
+ <b>
31
+ <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>
32
+ </b>
33
+ </div>
34
+
35
+ ---
36
+
37
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
38
+
39
+ <a name="latestupdate">
40
+
41
+ ## What's new in the latest updates
42
+
43
+ ### 0.6.0 <sub><sup>ALPHA1
44
+
45
+ - UI reworked
46
+ - You can now load several source images (with reference faces) or set the path to the folder containing faces images
47
+
48
+ <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%"/>
49
+
50
+ <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%"/>
51
+
52
+ ### 0.5.1
53
+
54
+ - 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;
55
+ - "Face Mask Correction" option - if you encounter some pixelation around face contours, this option will be useful;
56
+
57
+ <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%"/>
58
+
59
+ ## Installation
60
+
61
+ [Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
62
+
63
+ <a name="a1111">If you use [AUTOMATIC1111 web-ui](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
64
+
65
+ 1. (For Windows Users):
66
+ - Install **Visual Studio 2022** (Community version, for example - you need this step to build some of dependencies):
67
+ https://visualstudio.microsoft.com/downloads/
68
+ - 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":
69
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/
70
+ - OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. VIII)](#insightfacebuild)
71
+ 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"
72
+ 3. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
73
+ 4. Check the last message in your SD-WebUI Console:
74
+ * 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"
75
+ * If you see the message "Done!", just reload the UI
76
+ 5. Enjoy!
77
+
78
+ <a name="sdnext">If you use [SD.Next](https://github.com/vladmandic/automatic):
79
+
80
+ 1. Close (stop) your SD WebUI Server if it's running
81
+ 2. (For Windows Users) See the [1st step](#a1111) for Automatic1111 (if you followed [this steps (sec. VIII)](#insightfacebuild) instead - go to the Step 5)
82
+ 3. Go to (Windows)`automatic\venv\Scripts` or (MacOS/Linux)`automatic/venv/bin`, run Terminal or Console (cmd) for that folder and type `activate`
83
+ 4. Run `pip install insightface==0.7.3`
84
+ 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"
85
+ 6. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
86
+ 7. Check the last message in your SD.Next Console:
87
+ * If you see the message "--- PLEASE, RESTART the Server! ---" - stop the Server (CTRL+C or CMD+C) or just close your console
88
+ 8. 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` folder
89
+ 9. Run your SD.Next WebUI and enjoy!
90
+
91
+ <a name="colab">If you use [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
92
+
93
+ 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"
94
+ 2. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
95
+ 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"
96
+ 4. Enjoy!
97
+
98
+ ## Features
99
+
100
+ - Very fast and accurate **face replacement (face swap)** in images
101
+ - **Multiple faces support**
102
+ - **Gender detection**
103
+ - Ability to **save original images** (made before swapping)
104
+ - **Face restoration** of a swapped face
105
+ - **Upscaling** of a resulting image
106
+ - Saving ans loading **Safetensors Face Models**
107
+ - **Facial Mask Correction** to avoid any pixelation around face contours
108
+ - Ability to set the **Postprocessing order**
109
+ - **100% compatibility** with different **SD WebUIs**: Automatic1111, SD.Next, Cagliostro Colab UI
110
+ - **Fast performance** even with CPU, ReActor for SD WebUI is absolutely not picky about how powerful your GPU is
111
+ - **CUDA** acceleration support since version 0.5.0
112
+ - **[API](/API.md) support**: both SD WebUI built-in and external (via POST/GET requests)
113
+ - **ComfyUI [support](https://github.com/Gourieff/comfyui-reactor-node)**
114
+ - **Mac M1/M2 [support](https://github.com/Gourieff/sd-webui-reactor/issues/42)**
115
+ - Console **log level control**
116
+ - **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)
117
+
118
+ ## Usage
119
+
120
+ > Using this software you are agree with [disclaimer](#disclaimer)
121
+
122
+ 1. Under "ReActor" drop-down menu, import an image containing a face;
123
+ 2. Turn on the "Enable" checkbox;
124
+ 3. That's it, now the generated result will have the face you selected.
125
+
126
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
127
+
128
+ ### Face Indexes
129
+
130
+ ReActor detects faces in images in the following order:<br>
131
+ left->right, top->bottom
132
+
133
+ And if you need to specify faces, you can set indexes for source and input images.
134
+
135
+ Index of the first detected face is 0.
136
+
137
+ You can set indexes in the order you need.<br>
138
+ E.g.: 0,1,2 (for Source); 1,0,2 (for Input).<br>
139
+ This means: the second Input face (index = 1) will be swapped by the first Source face (index = 0) and so on.
140
+
141
+ ### Genders
142
+
143
+ You can specify the gender to detect in images.<br>
144
+ ReActor will swap a face only if it meets the given condition.
145
+
146
+ ### The result face is blurry
147
+ Use the "Restore Face" option. You can also try the "Upscaler" option or for more finer control, use an upscaler from the "Extras" tab.
148
+ You can also set the postproduction order (from 0.1.0 version):
149
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
150
+
151
+ *The old logic was the opposite (Upscale -> then Restore), resulting in worse face quality (and big texture differences) after upscaling.*
152
+
153
+ ### There are multiple faces in result
154
+ Select 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.
155
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
156
+
157
+ ### ~~The result is totally black~~
158
+ ~~This means NSFW filter detected that your image is NSFW.~~
159
+
160
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
161
+
162
+ ### Img2Img
163
+
164
+ 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.
165
+
166
+ 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".
167
+
168
+ ### Extras Tab
169
+
170
+ 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
171
+
172
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
173
+
174
+ ## API
175
+
176
+ You can use ReActor with the built-in Webui API or via an external API.
177
+
178
+ Please follow **[this](/API.md)** page for the detailed instruction.
179
+
180
+ ## Troubleshooting
181
+
182
+ ### **I. "You should at least have one model in models directory"**
183
+
184
+ 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.
185
+
186
+ ### **II. Any problems with installing Insightface or other dependencies**
187
+
188
+ (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
189
+
190
+ (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:
191
+ 1. Close (stop) your SD WebUI Server and start it again
192
+
193
+ (for Any OS Users) If the problem still there, then do the following:
194
+ 1. Close (stop) your SD WebUI Server if it's running
195
+ 2. Go to (Windows)`venv\Lib\site-packages` folder or (MacOS/Linux)`venv/lib/python3.10/site-packages`
196
+ 3. If you see any folders with names start from `~` (e.g. "~rotobuf") - delete them
197
+ 4. Go to (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin`
198
+ 5. Run Terminal or Console (cmd) for that folder and type `activate`
199
+ 6. Update your pip at first: `pip install -U pip`
200
+ 7. Then one-by-one:
201
+ - `pip install insightface==0.7.3`
202
+ - `pip install onnx`
203
+ - `pip install "onnxruntime-gpu>=1.16.1"`
204
+ - `pip install opencv-python`
205
+ - `pip install tqdm`
206
+ 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.
207
+
208
+ ### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
209
+
210
+ First of all - you need to disable any other Roop-based extensions:
211
+ - Go to 'Extensions -> Installed' tab and uncheck any Roop-based extensions except this one
212
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>
213
+ - Click 'Apply and restart UI'
214
+
215
+ Alternative solutions:
216
+ - https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243
217
+ - https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (can be actual, if you use Vladmandic SD.Next)
218
+
219
+ ### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
220
+
221
+ Probably, you need to disable the "SD-CN-Animation" extension (or perhaps some another that causes the conflict)
222
+
223
+ ### **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'"**
224
+
225
+ This error may occur if there's smth wrong with the model file `inswapper_128.onnx`
226
+
227
+ Try to download it manually from [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)
228
+ and put it to the `stable-diffusion-webui\models\insightface` replacing existing one
229
+
230
+ ### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" OR "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
231
+
232
+ 1. Close (stop) your SD WebUI Server if it's running
233
+ 2. 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 them
234
+ 3. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
235
+ 4. Then:
236
+ - `python -m pip install -U pip`
237
+ - `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`
238
+ - `pip install "onnxruntime-gpu>=1.16.1"`
239
+
240
+ 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!
241
+
242
+ ### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
243
+
244
+ 1. Close (stop) your SD WebUI Server if it's running
245
+ 2. 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 them
246
+ 3. Go to the "google" folder (inside the "site-packages") and delete any folders there with names start from "~"
247
+ 4. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
248
+ 5. Then:
249
+ - `python -m pip install -U pip`
250
+ - `pip uninstall protobuf`
251
+ - `pip install "protobuf>=3.20.3"`
252
+
253
+ 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
254
+
255
+ <a name="insightfacebuild">
256
+
257
+ ### **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:**
258
+
259
+ 1. Close (stop) your SD WebUI Server if it's running
260
+ 2. 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)
261
+ 3. From stable-diffusion-webui (or SD.Next) root folder run CMD and `.\venv\Scripts\activate`
262
+ 4. Then update your PIP: `python -m pip install -U pip`
263
+ 5. Then install Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`
264
+ 6. Enjoy!
265
+
266
+ ### **IX. 07-August-23 Update problem**
267
+
268
+ 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`
269
+
270
+ Please do the next:
271
+
272
+ Inside the folder `extensions\sd-webui-reactor` run Terminal or Console (cmd) and then:
273
+ - `git reset f48bdf1 --hard`
274
+ - `git pull`
275
+
276
+ OR
277
+
278
+ 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`
279
+
280
+ ### **X. StabilityMatrix Issues**
281
+
282
+ 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
283
+
284
+ ## Updating
285
+
286
+ A good and quick way to check for Extensions updates: https://github.com/Gourieff/sd-webui-extensions-updater
287
+
288
+ ## ComfyUI
289
+
290
+ You can use ReActor with ComfyUI.<br>
291
+ For the installation instruction follow the [ReActor Node repo](https://github.com/Gourieff/comfyui-reactor-node)
292
+
293
+ ## Disclaimer
294
+
295
+ 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.
296
+
297
+ 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.
298
+
299
+ 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.**
300
+
301
+ By using this extension you are agree not to create any content that:
302
+ - violates any laws;
303
+ - causes any harm to a person or persons;
304
+ - propogates (spreads) any information (both public or personal) or images (both public or personal) which could be meant for harm;
305
+ - spreads misinformation;
306
+ - targets vulnerable groups of people.
307
+
308
+ 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:
309
+
310
+ [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.
311
+
312
+ 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.
313
+
314
+ 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.
315
+
316
+ ### Models Hashsum
317
+
318
+ #### Safe-to-use models have the folowing hash:
319
+
320
+ inswapper_128.onnx
321
+ ```
322
+ MD5:a3a155b90354160350efd66fed6b3d80
323
+ SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
324
+ ```
325
+
326
+ 1k3d68.onnx
327
+
328
+ ```
329
+ MD5:6fb94fcdb0055e3638bf9158e6a108f4
330
+ SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
331
+ ```
332
+
333
+ 2d106det.onnx
334
+
335
+ ```
336
+ MD5:a3613ef9eb3662b4ef88eb90db1fcf26
337
+ SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
338
+ ```
339
+
340
+ det_10g.onnx
341
+
342
+ ```
343
+ MD5:4c10eef5c9e168357a16fdd580fa8371
344
+ SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
345
+ ```
346
+
347
+ genderage.onnx
348
+
349
+ ```
350
+ MD5:81c77ba87ab38163b0dec6b26f8e2af2
351
+ SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
352
+ ```
353
+
354
+ w600k_r50.onnx
355
+
356
+ ```
357
+ MD5:80248d427976241cbd1343889ed132b3
358
+ SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
359
+ ```
360
+
361
+ **Please check hashsums if you download these models from unverified (or untrusted) sources**
sd-webui-reactor-main/sd-webui-reactor-main/README_RU.md ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_RU.png?raw=true" alt="logo" width="180px"/>
4
+
5
+ ![Version](https://img.shields.io/badge/версия-0.6.0_alpha1-lightgreen?style=for-the-badge&labelColor=darkgreen)
6
+
7
+ <a href="https://boosty.to/artgourieff" target="_blank">
8
+ <img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Поддержать проект на Boosty"/>
9
+ <br>
10
+ <sup>
11
+ Поддержать проект
12
+ </sup>
13
+ </a>
14
+
15
+ <hr>
16
+
17
+ [![Commit activity](https://img.shields.io/github/commit-activity/t/Gourieff/sd-webui-reactor/main?cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/commits/main)
18
+ ![Last commit](https://img.shields.io/github/last-commit/Gourieff/sd-webui-reactor/main?cacheSeconds=0)
19
+ [![Opened issues](https://img.shields.io/github/issues/Gourieff/sd-webui-reactor?color=red)](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
20
+ [![Closed issues](https://img.shields.io/github/issues-closed/Gourieff/sd-webui-reactor?color=green&cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/issues?q=is%3Aissue+is%3Aclosed)
21
+ ![License](https://img.shields.io/github/license/Gourieff/sd-webui-reactor)
22
+
23
+ [English](/README.md) | Русский
24
+
25
+ # ReActor для Stable Diffusion
26
+ ### Расширение для быстрой и простой замены лиц на любых изображениях. Без фильтра цензуры, 18+, используйте под вашу собственную [ответственность](#disclaimer)
27
+
28
+ ---
29
+ <b>
30
+ <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>
31
+ </b>
32
+ </div>
33
+
34
+ ---
35
+
36
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
37
+
38
+ <a name="latestupdate">
39
+
40
+ ## Что нового в последних обновлениях
41
+
42
+ ### 0.6.0 <sub><sup>ALPHA1
43
+
44
+ - UI переработан
45
+ - Появилась возможность загружать несколько исходных изображений с лицами или задавать путь к папке, содержащей такие изображения
46
+
47
+ <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%"/>
48
+
49
+ ### 0.5.1
50
+
51
+ - Теперь можно сохранять модели лиц в качестве файлов "safetensors" (находятся в `<sd-web-ui-folder>\models\reactor\faces`) и загружать их с ReActor, храня супер легкие модели лиц, которые вы чаще всего используете;
52
+ - Новые опция "Face Mask Correction" - если вы сталкиваетесь с пикселизацией вокруг контуров лица, эта опция будет полезной;
53
+
54
+ <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%"/>
55
+
56
+ <a name="installation">
57
+
58
+ ## Установка
59
+
60
+ [Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
61
+
62
+ <a name="a1111">Если вы используете [AUTOMATIC1111 Web-UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
63
+
64
+ 1. (Для пользователей Windows):
65
+ - Установите **Visual Studio 2022** (Например, версию Community - этот шаг нужен для правильной компиляции библиотеки Insightface):
66
+ https://visualstudio.microsoft.com/downloads/
67
+ - ИЛИ только **VS C++ Build Tools** (если вам не нужен весь пакет Visual Studio), выберите "Desktop Development with C++" в разделе "Workloads -> Desktop & Mobile":
68
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/
69
+ - ИЛИ если же вы не хотите устанавливать что-либо из вышеуказанного - выполните [следующие шаги (пункт VIII)](#insightfacebuild)
70
+ 2. Внутри SD Web-UI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"
71
+ 3. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
72
+ 4. Проверьте последнее сообщение в консоли SD-WebUI:
73
+ * Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) и запустите его заново - ИЛИ же перейдите во вкладку "Installed", нажмите "Apply and restart UI"
74
+ * Если вы видите "Done!", просто перезагрузите UI, нажав на "Reload UI"
75
+ 5. Готово!
76
+
77
+ <a name="sdnext">Если вы используете [SD.Next](https://github.com/vladmandic/automatic):
78
+
79
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
80
+ 2. (Для пользователей Windows) Смотрите [Шаг 1](#a1111) для Automatic1111 (если же вы следовали [данным шагам (пункт VIII)](#insightfacebuild) вместо этого - переходите к Шагу 5)
81
+ 3. Перейдите в (Windows)`automatic\venv\Scripts` или (MacOS/Linux)`automatic/venv/bin`, запустите Терминал или Консоль (cmd) для данной папки и выполните `activate`
82
+ 4. Выполните `pip install insightface==0.7.3`
83
+ 5. Запустите SD.Next, перейдите во вкладку "Extensions", вставьте эту ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
84
+ 6. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
85
+ 7. Проверьте последнее сообщение в консоли SD.Next:
86
+ * Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) или просто закройте консоль
87
+ 8. Перейдите в директорию `automatic\extensions\sd-webui-reactor` - если вы видите там папку `models\insightface` с файлом `inswapper_128.onnx` внутри, переместите его в папку `automatic\models\insightface`
88
+ 9. Готово, можете запустить SD.Next WebUI!
89
+
90
+ <a name="colab">Если вы используете [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
91
+
92
+ 1. В активном WebUI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"
93
+ 2. Пожалуйста, подождите некоторое время, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
94
+ 3. Когда вы увидите сообщение "--- PLEASE, RESTART the Server! ---" (в секции "Start UI" вашего ноутбука "Start Cagliostro Colab UI") - перейдите во вкладку "Installed" и нажмите "Apply and restart UI"
95
+ 4. Готово!
96
+
97
+ <a name="features">
98
+
99
+ ## Возможности
100
+
101
+ - Быстрая и точна **замена лиц (faceswap)** на изображении
102
+ - **Поддержка нескольких лиц**
103
+ - **Определение пола**
104
+ - Функция **сохранения оригинального изображения** (сгенерированного до замены лица)
105
+ - **Восстановление лица** после замены
106
+ - **Увеличение размера** полученного изображения
107
+ - Сохранение и загрузка **Моделей Лиц типа Safetensors**
108
+ - **Коррекция Маски Лица** для предотвращения какой-либо пикселизации вокруг контуров лиц
109
+ - Возможность задать **порядок постобработки**
110
+ - **100% совместимость** с разными **SD WebUI**: Automatic1111, SD.Next, Cagliostro Colab UI
111
+ - **Отличная производительность** даже с использованием ЦПУ, ReActor для SD WebUI абсолютно не требователен к мощности вашей видеокарты
112
+ - **Поддержка CUDA**, начиная с версии 0.5.0
113
+ - **Поддержка [API](/API.md)**: как встроенного в SD WebUI, так и внешнего (через POST/GET запросы)
114
+ - **[Поддержка](https://github.com/Gourieff/comfyui-reactor-node) ComfyUI**
115
+ - **[Поддержка](https://github.com/Gourieff/sd-webui-reactor/issues/42) ��омпьютеров Mac M1/M2**
116
+ - **Регулировка уровня логов** консоли
117
+ - **Без NSFW фильтров** (данное расширение адресовано высокоразвитым интеллектуальным людям, а не извращенцам; наше общество должно быть ориентировано на своём пути на высшие стандарты, а не на низшие - в этом состоит суть развития и эволюции человеческого общества; поэтому, моя позиция такова - что зрелые умом люди достаточно разумны, чтобы понимать, что есть хорошо, а что плохо и нести полную ответственность за собственные действия; для прочих - никакие "фильтры" не помогут, пока эти люди сами не поймут, как работает Вселенная)
118
+
119
+ <a name="usage">
120
+
121
+ ## Использование
122
+
123
+ > Используя данное программное обеспечение, вы соглашаетесь с [ответственностью](#disclaimer)
124
+
125
+ 1. В раскрывающимся меню "ReActor" импортируйте изображение, содержащее лицо;
126
+ 2. Установите флажок "Enable";
127
+ 3. Готово, теперь результат будет иметь то лицо, которое вы выбрали.
128
+
129
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
130
+
131
+ ### Индексы Лиц (Face Indexes)
132
+
133
+ ReActor определяет лица на изображении в следующей последовательности:<br>
134
+ слева-направо, сверху-вниз.
135
+
136
+ Если вам нужно заменить определенное лицо, вы можете указать индекс для исходного (source, с лицом) и входного (input, где будет замена лица) изображений.
137
+
138
+ Индекс первого обнаруженного лица - 0.
139
+
140
+ Вы можете задать индексы в том порядке, который вам нужен.<br>
141
+ Например: 0,1,2 (для Source); 1,0,2 (для Input).<br>
142
+ Это означает, что: второе лицо из Input (индекс = 1) будет заменено первым лицом из Source (индекс = 0) и так далее.
143
+
144
+ ### Определение Пола
145
+
146
+ Вы можете обозначить, какой пол нужно определять на изображении.<br>
147
+ ReActor заменит только то лицо, которое удовлетворяет заданному условию.
148
+
149
+ ### Если лицо получилось нечётким
150
+ Используйте опцию "Restore Face". Также можете попробовать опцию "Upscaler". Для более точного контроля параметров используйте Upscaler во вкладке "Extras".
151
+ Также вы можете установить порядок постобработки (начиная с версии 0.1.0):
152
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
153
+
154
+ *Прежняя логика была противоположенной (Upscale -> затем Restore), что приводило к более худшему качеству изображения лица (а также к значительной разнице текстур) после увеличения.*
155
+
156
+ ### Результат имеет несколько лиц
157
+ Выберите номера лиц, которые нужно поменять, используя поля "Comma separated face number(s)" для исходного изображения лица и для результата. Можно устанавливать любой, необходимый вам, порядок лиц.
158
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
159
+
160
+ ### ~~Результат получился чёрным~~
161
+ ~~Это значит, что сработал NSFW фильтр.~~
162
+
163
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
164
+
165
+ ### Img2Img
166
+
167
+ Используйте эту вкладку, чтобы заменить лицо на уже готовом изображении (флажок "Swap in source image") или на сгенерированном на основе готового (флажок "Swap in generated image").
168
+
169
+ Inpainting также работает, но замена лица происходит только в области маски.<br>Пожалуйста, используйте с опцией "Only masked" для "Inpaint area", если вы применяете "Upscaler". Иначе, используйте функцию увеличения (апскейла) через вкладку "Extras" или через опциональный загрузчик "Script" (внизу экрана), применив "SD upscale" или "Ultimate SD upscale".
170
+
171
+ ### Extras
172
+
173
+ Начиная с версии 0.5.0, вы можете использовать ReActor через вкладку Extras, что даёт очень быструю производительность и возможность замены лиц в обход пайплайна SD, что иногда вызывает размытие или искажение деталей оригинального изображения
174
+
175
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
176
+
177
+ ## API
178
+
179
+ Вы можете использовать ReActor как со встроенным SD Webui API так и через внешнее API.
180
+
181
+ Подробная инструкция **[здесь](/API.md)**.
182
+
183
+ <a name="troubleshooting">
184
+
185
+ ## Устранение проблем
186
+
187
+ ### **I. "You should at least have one model in models directory"**
188
+
189
+ Проверьте путь, где хранится модель "inswapper_128.onnx". Файл должен находиться в папке `stable-diffusion-webui\models\insightface`. Переместите модель туда, если она находится в какой-то иной директории.
190
+
191
+ ### **II. Какие-либо проблемы с установкой Insightface или прочих пакетов**
192
+
193
+ (Для пользователей Mac M1/M2) Если вы получаете ошибки в ходе установки Insightface - читайте https://github.com/Gourieff/sd-webui-reactor/issues/42
194
+
195
+ (Для пользователей Windows) Если VS C++ Build Tools или MS VS 2022 установлены но вы видите ошибки, связанные с отсутствием Insightface, попробуйте следующее:
196
+ 1. Закройте (остановите) SD WebUI Сервер и запустите его снова (возможно, не прошла инициализация пакета после его установки)
197
+
198
+ (Для пользователей любых ОС) Попробуйте следующее:
199
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
200
+ 2. Перейдите в папку (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages`
201
+ 3. Если вы видите к-л папки с именами, начинающимися с `~` (например, "~rotobuf") - удалите их
202
+ 4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`
203
+ 5. Откройте Терминал или Консоль (cmd) для этой папки и выполните `activate`
204
+ 6. Для начала обновите pip: `pip install -U pip`
205
+ 7. Далее:
206
+ - `pip install insightface==0.7.3`
207
+ - `pip install onnx`
208
+ - `pip install "onnxruntime-gpu>=1.16.1"`
209
+ - `pip install opencv-python`
210
+ - `pip install tqdm`
211
+ 8. Выполните `deactivate`, закройте Терминал или Консоль и запустите SD WebUI, ReActor должен запуститься без к-л проблем - если же нет, добро пожаловать в раздел "Issues".
212
+
213
+ ### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
214
+
215
+ Для начала отключите любые другие Roop-подобные расширения:
216
+ - Перейдите в 'Extensions -> Installed' и снимите флажок с ненужных:
217
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>
218
+ - Нажмите 'Apply and restart UI'
219
+
220
+ Альтернативные решения:
221
+ - https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243
222
+ - https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (актуально для Vladmandic SD.Next)
223
+
224
+ ### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
225
+
226
+ Отключите расширение "SD-CN-Animation" (или какое-либо другое, вызывающее конфликт)
227
+
228
+ ### **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'"**
229
+
230
+ Эта ошибка появляется, если что-то не так с файлом модели `inswapper_128.onnx`.
231
+
232
+ Скачайте вручную по ссылке [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)
233
+ и сохраните в директорию `stable-diffusion-webui\models\insightface`, заменив имеющийся файл.
234
+
235
+ ### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" ИЛИ "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
236
+
237
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
238
+ 2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
239
+ 3. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
240
+ 4. Затем:
241
+ - `python -m pip install -U pip`
242
+ - `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`
243
+ - `pip install "onnxruntime-gpu>=1.16.1"`
244
+
245
+ Если это не помогло - значит какое-то другое расширение переустанавливает `onnxruntime` всякий раз, когда SD WebUI проверяет требования пакетов. Внимательно посмотрите список активных расширений. Некоторые расширения могут вызывать переустановку `onnxruntime-gpu` на версию `onnxruntime<1.16.1` при каждом запуске SD WebUI.<br>ORT 1.16.0 выкатили с ошибкой https://github.com/microsoft/onnxruntime/issues/17631 - не устанавливайте её!
246
+
247
+ ### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
248
+
249
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
250
+ 2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
251
+ 3. Перейдите в папку "google" (внутри "site-packages") и удалите любые папки с именам, начинающимися на "~"
252
+ 4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
253
+ 5. Затем:
254
+ - `python -m pip install -U pip`
255
+ - `pip uninstall protobuf`
256
+ - `pip install "protobuf>=3.20.3"`
257
+
258
+ Если это не помгло - значит, есть к-л другое расширение, которое использует неподходящую версию пакета protobuf, и SD WebUI устанавливает эту версию при каждом запуске.
259
+
260
+ <a name="insightfacebuild">
261
+
262
+ ### **VIII. (Для пользователей Windows) Если вы до сих пор не можете установить пакет Insightface по каким-то причинам или же просто не желаете устанавливать Visual Studio или VS C++ Build Tools - сделайте следующее:**
263
+
264
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
265
+ 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"
266
+ 3. Из корневой директории откройте Консоль (CMD) и выполните `.\venv\Scripts\activate`
267
+ 4. Обновите PIP: `python -m pip install -U pip`
268
+ 5. Затем установите Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`
269
+ 6. Готово!
270
+
271
+ ### **IX. Ошибка обновления 07-Август-23**
272
+
273
+ Если после очередного `git pull` вы получили сообщение: `Merge made by the 'recursive' strategy` и затем, когда проверяете статус репозитория через `git status`, вы видите `Your branch is ahead of 'origin/main' by`
274
+
275
+ Выполните следующее:
276
+
277
+ Внутри папки `extensions\sd-webui-reactor` запустите Терминал или Консоль (cmd) и затем:
278
+ - `git reset f48bdf1 --hard`
279
+ - `git pull`
280
+
281
+ ИЛИ:
282
+
283
+ Полностью удалите папку `sd-webui-reactor` внутри директории `extensions`, запустите Терминал или Консоль (cmd) и выполните `git clone https://github.com/Gourieff/sd-webui-reactor`
284
+
285
+ ### **X. Ошибки установки в StabilityMatrix**
286
+
287
+ Если вы столкнулись с ошибками при установки данного расширения в пакетном менеджере StabilityMatrix - изучите информацию по ссылке: https://github.com/Gourieff/sd-webui-reactor/issues/129#issuecomment-1768210875
288
+
289
+ <a name="updating">
290
+
291
+ ## Обновление
292
+
293
+ Самый простой и удобный способ обновления SD WebUI и расширений: https://github.com/Gourieff/sd-webui-extensions-updater
294
+
295
+ ## ComfyUI
296
+
297
+ Вы можете использовать ReActor с ComfyUI<br>
298
+ Инструкция здесь: [ReActor Node](https://github.com/Gourieff/comfyui-reactor-node)
299
+
300
+ <a name="disclaimer">
301
+
302
+ ## Ответственность
303
+
304
+ Это программное обеспечение призвано стать продуктивным вкладом в быстрорастущую медиаиндустрию на основе генеративных сетей и искусственного интеллекта. Данное ПО поможет художникам в решении таких задач, как анимация собственного персонажа или использование персонажа в качестве модели для одежды и т.д.
305
+
306
+ Разработчики этого программного обеспечения осведомлены о возможных неэтичных применениях и обязуются принять против этого превентивные меры. Мы продолжим развивать этот проект в позитивном направлении, придерживаясь закона и этики.
307
+
308
+ Подразумевается, что пользователи этого программного обеспечения будут использовать его ответственно, соблюдая локальное законодательство. Если используется лицо реального человека, пользователь обязан получить согласие заинтересованного лица и четко указать, что это дипфейк при размещении контента в Интернете. **Разработчики и Со-авторы данного программного обеспечения не несут ответственности за действия конечных пользователей.**
309
+
310
+ Используя данное расширение, вы соглашаетесь не создавать материалы, которые:
311
+ - нарушают какие-либо действующие законы тех или иных государств или международных организаций;
312
+ - причиняют какой-либо вред человеку или лицам;
313
+ - пропагандируют любую информацию (как общедоступную, так и личную) или изображения (как общедоступные, так и личные), которые могут быть направлены на причинение вреда;
314
+ - используются для распространения дезинформации;
315
+ - нацелены на уязвимые группы людей.
316
+
317
+ Данное программное обеспечение использует предварительно обученные модели `buffalo_l` и `inswapper_128.onnx`, представленные разработчиками [InsightFace](https://github.com/deepinsight/insightface/). Эти модели распространяются при следующих условиях:
318
+
319
+ [Перевод из текста лицензии insighface](https://github.com/deepinsight/insightface/tree/master/python-package): Предварительно обученные модели InsightFace доступны только для некоммерческих исследовательских целей. Сюда входят как модели с автоматической загрузкой, так и модели, загруженные вручную.
320
+
321
+ Пользователи данного программного обеспечения должны строго соблюдать данные условия использования. Разработчики и Со-авторы данного программного продукта не несут ответственности за неправильное использование предварительно обученных моделей InsightFace.
322
+
323
+ Обратите внимание: если вы собираетесь использовать это программное обеспечение в каких-либо коммерческих целях, вам необходимо будет обучить свои собстве��ные модели или найти модели, которые можно использовать в коммерческих целях.
324
+
325
+ ### Хэш файлов моделей
326
+
327
+ #### Безопасные для использования модели имеют следующий хэш:
328
+
329
+ inswapper_128.onnx
330
+ ```
331
+ MD5:a3a155b90354160350efd66fed6b3d80
332
+ SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
333
+ ```
334
+
335
+ 1k3d68.onnx
336
+
337
+ ```
338
+ MD5:6fb94fcdb0055e3638bf9158e6a108f4
339
+ SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
340
+ ```
341
+
342
+ 2d106det.onnx
343
+
344
+ ```
345
+ MD5:a3613ef9eb3662b4ef88eb90db1fcf26
346
+ SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
347
+ ```
348
+
349
+ det_10g.onnx
350
+
351
+ ```
352
+ MD5:4c10eef5c9e168357a16fdd580fa8371
353
+ SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
354
+ ```
355
+
356
+ genderage.onnx
357
+
358
+ ```
359
+ MD5:81c77ba87ab38163b0dec6b26f8e2af2
360
+ SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
361
+ ```
362
+
363
+ w600k_r50.onnx
364
+
365
+ ```
366
+ MD5:80248d427976241cbd1343889ed132b3
367
+ SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
368
+ ```
369
+
370
+ **Пожалуйста, сравните хэш, если вы скачиваете данные модели из непроверенных источников**
sd-webui-reactor-main/sd-webui-reactor-main/example/IamSFW.jpg ADDED
sd-webui-reactor-main/sd-webui-reactor-main/example/api_example.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64, io, requests, json
2
+ from PIL import Image, PngImagePlugin
3
+ from datetime import datetime, date
4
+
5
+ address = 'http://127.0.0.1:7860'
6
+ input_file = "extensions\sd-webui-reactor\example\IamSFW.jpg" # Input file path
7
+ time = datetime.now()
8
+ today = date.today()
9
+ current_date = today.strftime('%Y-%m-%d')
10
+ current_time = time.strftime('%H-%M-%S')
11
+ output = 'outputs/api/output_'+current_date+'_'+current_time # Output file path + name index
12
+ try:
13
+ im = Image.open(input_file)
14
+ except Exception as e:
15
+ print(e)
16
+ finally:
17
+ print(im)
18
+
19
+ img_bytes = io.BytesIO()
20
+ im.save(img_bytes, format='PNG')
21
+ img_base64 = base64.b64encode(img_bytes.getvalue()).decode('utf-8')
22
+
23
+ # ReActor arguments:
24
+ args=[
25
+ img_base64, #0
26
+ True, #1 Enable ReActor
27
+ '0', #2 Comma separated face number(s) from swap-source image
28
+ '0', #3 Comma separated face number(s) for target image (result)
29
+ 'C:\stable-diffusion-webui\models\insightface\inswapper_128.onnx', #4 model path
30
+ 'CodeFormer', #4 Restore Face: None; CodeFormer; GFPGAN
31
+ 1, #5 Restore visibility value
32
+ True, #7 Restore face -> Upscale
33
+ '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
34
+ 2, #9 Upscaler scale value
35
+ 1, #10 Upscaler visibility (if scale = 1)
36
+ False, #11 Swap in source image
37
+ True, #12 Swap in generated image
38
+ 1, #13 Console Log Level (0 - min, 1 - med or 2 - max)
39
+ 0, #14 Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)
40
+ 0, #15 Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)
41
+ False, #16 Save the original image(s) made before swapping
42
+ 0.8, #17 CodeFormer Weight (0 = maximum effect, 1 = minimum effect), 0.5 - by default
43
+ False, #18 Source Image Hash Check, True - by default
44
+ False, #19 Target Image Hash Check, False - by default
45
+ "CUDA", #20 CPU or CUDA (if you have it), CPU - by default
46
+ True, #21 Face Mask Correction
47
+ 1, #22 Select Source, 0 - Image, 1 - Face Model, 2 - Source Folder
48
+ "elena.safetensors", #23 Filename of the face model (from "models/reactor/faces"), e.g. elena.safetensors, don't forger to set #22 to 1
49
+ "C:\PATH_TO_FACES_IMAGES", #24 The path to the folder containing source faces images, don't forger to set #22 to 2
50
+ ]
51
+
52
+ # The args for ReActor can be found by
53
+ # requests.get(url=f'{address}/sdapi/v1/script-info')
54
+
55
+ 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"
56
+
57
+ 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))"
58
+
59
+ payload = {
60
+ "prompt": prompt,
61
+ "negative_prompt": neg,
62
+ "seed": -1,
63
+ "sampler_name": "DPM++ 2M Karras",
64
+ "steps": 15,
65
+ "cfg_scale": 7,
66
+ "width": 512,
67
+ "height": 768,
68
+ "restore_faces": False,
69
+ "alwayson_scripts": {"reactor":{"args":args}}
70
+ }
71
+
72
+ try:
73
+ print('Working... Please wait...')
74
+ result = requests.post(url=f'{address}/sdapi/v1/txt2img', json=payload)
75
+ except Exception as e:
76
+ print(e)
77
+ finally:
78
+ print('Done! Saving file...')
79
+
80
+ if result is not None:
81
+ r = result.json()
82
+ n = 0
83
+
84
+ for i in r['images']:
85
+ image = Image.open(io.BytesIO(base64.b64decode(i.split(",",1)[0])))
86
+
87
+ png_payload = {
88
+ "image": "data:image/png;base64," + i
89
+ }
90
+ response2 = requests.post(url=f'{address}/sdapi/v1/png-info', json=png_payload)
91
+
92
+ pnginfo = PngImagePlugin.PngInfo()
93
+ pnginfo.add_text("parameters", response2.json().get("info"))
94
+ output_file = output+'_'+str(n)+'_.png'
95
+ try:
96
+ image.save(output_file, pnginfo=pnginfo)
97
+ except Exception as e:
98
+ print(e)
99
+ finally:
100
+ print(f'{output_file} is saved\nAll is done!')
101
+ n += 1
102
+ else:
103
+ print('Something went wrong...')
sd-webui-reactor-main/sd-webui-reactor-main/example/api_external.curl ADDED
The diff for this file is too large to render. See raw diff
 
sd-webui-reactor-main/sd-webui-reactor-main/example/api_external.json ADDED
The diff for this file is too large to render. See raw diff
 
sd-webui-reactor-main/sd-webui-reactor-main/example/insightface-0.7.3-cp310-cp310-win_amd64.whl ADDED
Binary file (842 kB). View file
 
sd-webui-reactor-main/sd-webui-reactor-main/install.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import os, sys
3
+ from typing import Any
4
+ import pkg_resources
5
+ from tqdm import tqdm
6
+ import urllib.request
7
+ from packaging import version as pv
8
+
9
+ try:
10
+ from modules.paths_internal import models_path
11
+ except:
12
+ try:
13
+ from modules.paths import models_path
14
+ except:
15
+ model_path = os.path.abspath("models")
16
+
17
+
18
+ BASE_PATH = os.path.dirname(os.path.realpath(__file__))
19
+
20
+ req_file = os.path.join(BASE_PATH, "requirements.txt")
21
+
22
+ models_dir = os.path.join(models_path, "insightface")
23
+
24
+ # DEPRECATED:
25
+ # models_dir_old = os.path.join(models_path, "roop")
26
+ # if os.path.exists(models_dir_old):
27
+ # if not os.listdir(models_dir_old) and (not os.listdir(models_dir) or not os.path.exists(models_dir)):
28
+ # os.rename(models_dir_old, models_dir)
29
+ # else:
30
+ # import shutil
31
+ # for file in os.listdir(models_dir_old):
32
+ # shutil.move(os.path.join(models_dir_old, file), os.path.join(models_dir, file))
33
+ # try:
34
+ # os.rmdir(models_dir_old)
35
+ # except Exception as e:
36
+ # print(f"OSError: {e}")
37
+
38
+ model_url = "https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx"
39
+ model_name = os.path.basename(model_url)
40
+ model_path = os.path.join(models_dir, model_name)
41
+
42
+ def pip_install(*args):
43
+ subprocess.run([sys.executable, "-m", "pip", "install", *args])
44
+
45
+ def pip_uninstall(*args):
46
+ subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", *args])
47
+
48
+ def is_installed (
49
+ package: str, version: str | None = None, strict: bool = True
50
+ ):
51
+ has_package = None
52
+ try:
53
+ has_package = pkg_resources.get_distribution(package)
54
+ if has_package is not None:
55
+ installed_version = has_package.version
56
+ if (installed_version != version and strict == True) or (pv.parse(installed_version) < pv.parse(version) and strict == False):
57
+ return False
58
+ else:
59
+ return True
60
+ else:
61
+ return False
62
+ except Exception as e:
63
+ print(f"Error: {e}")
64
+ return False
65
+
66
+ def download(url, path):
67
+ request = urllib.request.urlopen(url)
68
+ total = int(request.headers.get('Content-Length', 0))
69
+ with tqdm(total=total, desc='Downloading...', unit='B', unit_scale=True, unit_divisor=1024) as progress:
70
+ urllib.request.urlretrieve(url, path, reporthook=lambda count, block_size, total_size: progress.update(block_size))
71
+
72
+ if not os.path.exists(models_dir):
73
+ os.makedirs(models_dir)
74
+
75
+ if not os.path.exists(model_path):
76
+ download(model_url, model_path)
77
+
78
+ print("ReActor preheating...", end=' ')
79
+
80
+ last_device = None
81
+ first_run = False
82
+ available_devices = ["CPU", "CUDA"]
83
+
84
+ try:
85
+ last_device_log = os.path.join(BASE_PATH, "last_device.txt")
86
+ with open(last_device_log) as f:
87
+ last_device = f.readline().strip()
88
+ if last_device not in available_devices:
89
+ last_device = None
90
+ except:
91
+ last_device = "CPU"
92
+ first_run = True
93
+ with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
94
+ txt.write(last_device)
95
+
96
+ with open(req_file) as file:
97
+ install_count = 0
98
+ ort = "onnxruntime-gpu"
99
+ import torch
100
+ try:
101
+ if torch.cuda.is_available():
102
+ if first_run or last_device is None:
103
+ last_device = "CUDA"
104
+ elif torch.backends.mps.is_available() or hasattr(torch,'dml'):
105
+ ort = "onnxruntime"
106
+ # to prevent errors when ORT-GPU is installed but we want ORT instead:
107
+ if first_run:
108
+ pip_uninstall("onnxruntime", "onnxruntime-gpu")
109
+ # just in case:
110
+ if last_device == "CUDA" or last_device is None:
111
+ last_device = "CPU"
112
+ else:
113
+ if last_device == "CUDA" or last_device is None:
114
+ last_device = "CPU"
115
+ with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
116
+ txt.write(last_device)
117
+ if not is_installed(ort,"1.16.1",False):
118
+ install_count += 1
119
+ pip_install(ort, "-U")
120
+ except Exception as e:
121
+ print(e)
122
+ print(f"\nERROR: Failed to install {ort} - ReActor won't start")
123
+ raise e
124
+ print(f"Device: {last_device}")
125
+ strict = True
126
+ for package in file:
127
+ package_version = None
128
+ try:
129
+ package = package.strip()
130
+ if "==" in package:
131
+ package_version = package.split('==')[1]
132
+ elif ">=" in package:
133
+ package_version = package.split('>=')[1]
134
+ strict = False
135
+ if not is_installed(package,package_version,strict):
136
+ install_count += 1
137
+ pip_install(package)
138
+ except Exception as e:
139
+ print(e)
140
+ print(f"\nERROR: Failed to install {package} - ReActor won't start")
141
+ raise e
142
+ if install_count > 0:
143
+ print(f"""
144
+ +---------------------------------+
145
+ --- PLEASE, RESTART the Server! ---
146
+ +---------------------------------+
147
+ """)
sd-webui-reactor-main/sd-webui-reactor-main/reactor_modules/reactor_mask.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from PIL import Image, ImageDraw
4
+
5
+ from torchvision.transforms.functional import to_pil_image
6
+
7
+ from scripts.reactor_logger import logger
8
+ from scripts.reactor_inferencers.bisenet_mask_generator import BiSeNetMaskGenerator
9
+ from scripts.reactor_entities.face import FaceArea
10
+ from scripts.reactor_entities.rect import Rect
11
+
12
+
13
+ colors = [
14
+ (255, 0, 0),
15
+ (0, 255, 0),
16
+ (0, 0, 255),
17
+ (255, 255, 0),
18
+ (255, 0, 255),
19
+ (0, 255, 255),
20
+ (255, 255, 255),
21
+ (128, 0, 0),
22
+ (0, 128, 0),
23
+ (128, 128, 0),
24
+ (0, 0, 128),
25
+ (0, 128, 128),
26
+ ]
27
+
28
+ def color_generator(colors):
29
+ while True:
30
+ for color in colors:
31
+ yield color
32
+
33
+
34
+ def process_face_image(
35
+ face: FaceArea,
36
+ **kwargs,
37
+ ) -> Image:
38
+ image = np.array(face.image)
39
+ overlay = image.copy()
40
+ color_iter = color_generator(colors)
41
+ cv2.rectangle(overlay, (0, 0), (image.shape[1], image.shape[0]), next(color_iter), -1)
42
+ l, t, r, b = face.face_area_on_image
43
+ cv2.rectangle(overlay, (l, t), (r, b), (0, 0, 0), 10)
44
+ if face.landmarks_on_image is not None:
45
+ for landmark in face.landmarks_on_image:
46
+ cv2.circle(overlay, (int(landmark.x), int(landmark.y)), 6, (0, 0, 0), 10)
47
+ alpha = 0.3
48
+ output = cv2.addWeighted(image, 1 - alpha, overlay, alpha, 0)
49
+
50
+ return Image.fromarray(output)
51
+
52
+
53
+ def apply_face_mask(swapped_image:np.ndarray,target_image:np.ndarray,target_face,entire_mask_image:np.array)->np.ndarray:
54
+ logger.status("Correcting Face Mask")
55
+ mask_generator = BiSeNetMaskGenerator()
56
+ face = FaceArea(target_image,Rect.from_ndarray(np.array(target_face.bbox)),1.6,512,"")
57
+ face_image = np.array(face.image)
58
+ process_face_image(face)
59
+ face_area_on_image = face.face_area_on_image
60
+ mask = mask_generator.generate_mask(
61
+ face_image,
62
+ face_area_on_image=face_area_on_image,
63
+ affected_areas=["Face"],
64
+ mask_size=0,
65
+ use_minimal_area=True
66
+ )
67
+ mask = cv2.blur(mask, (12, 12))
68
+ # """entire_mask_image = np.zeros_like(target_image)"""
69
+ larger_mask = cv2.resize(mask, dsize=(face.width, face.height))
70
+ entire_mask_image[
71
+ face.top : face.bottom,
72
+ face.left : face.right,
73
+ ] = larger_mask
74
+
75
+ result = Image.composite(Image.fromarray(swapped_image),Image.fromarray(target_image), Image.fromarray(entire_mask_image).convert("L"))
76
+ return np.array(result)
77
+
78
+
79
+ def rotate_array(image: np.ndarray, angle: float) -> np.ndarray:
80
+ if angle == 0:
81
+ return image
82
+
83
+ h, w = image.shape[:2]
84
+ center = (w // 2, h // 2)
85
+
86
+ M = cv2.getRotationMatrix2D(center, angle, 1.0)
87
+ return cv2.warpAffine(image, M, (w, h))
88
+
89
+
90
+ def rotate_image(image: Image, angle: float) -> Image:
91
+ if angle == 0:
92
+ return image
93
+ return Image.fromarray(rotate_array(np.array(image), angle))
94
+
95
+
96
+ def correct_face_tilt(angle: float) -> bool:
97
+ angle = abs(angle)
98
+ if angle > 180:
99
+ angle = 360 - angle
100
+ return angle > 40
101
+
102
+
103
+ def _dilate(arr: np.ndarray, value: int) -> np.ndarray:
104
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value))
105
+ return cv2.dilate(arr, kernel, iterations=1)
106
+
107
+
108
+ def _erode(arr: np.ndarray, value: int) -> np.ndarray:
109
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value))
110
+ return cv2.erode(arr, kernel, iterations=1)
111
+
112
+
113
+ def dilate_erode(img: Image.Image, value: int) -> Image.Image:
114
+ """
115
+ The dilate_erode function takes an image and a value.
116
+ If the value is positive, it dilates the image by that amount.
117
+ If the value is negative, it erodes the image by that amount.
118
+
119
+ Parameters
120
+ ----------
121
+ img: PIL.Image.Image
122
+ the image to be processed
123
+ value: int
124
+ kernel size of dilation or erosion
125
+
126
+ Returns
127
+ -------
128
+ PIL.Image.Image
129
+ The image that has been dilated or eroded
130
+ """
131
+ if value == 0:
132
+ return img
133
+
134
+ arr = np.array(img)
135
+ arr = _dilate(arr, value) if value > 0 else _erode(arr, -value)
136
+
137
+ return Image.fromarray(arr)
138
+
139
+ def mask_to_pil(masks, shape: tuple[int, int]) -> list[Image.Image]:
140
+ """
141
+ Parameters
142
+ ----------
143
+ masks: torch.Tensor, dtype=torch.float32, shape=(N, H, W).
144
+ The device can be CUDA, but `to_pil_image` takes care of that.
145
+
146
+ shape: tuple[int, int]
147
+ (width, height) of the original image
148
+ """
149
+ n = masks.shape[0]
150
+ return [to_pil_image(masks[i], mode="L").resize(shape) for i in range(n)]
151
+
152
+ def create_mask_from_bbox(
153
+ bboxes: list[list[float]], shape: tuple[int, int]
154
+ ) -> list[Image.Image]:
155
+ """
156
+ Parameters
157
+ ----------
158
+ bboxes: list[list[float]]
159
+ list of [x1, y1, x2, y2]
160
+ bounding boxes
161
+ shape: tuple[int, int]
162
+ shape of the image (width, height)
163
+
164
+ Returns
165
+ -------
166
+ masks: list[Image.Image]
167
+ A list of masks
168
+
169
+ """
170
+ masks = []
171
+ for bbox in bboxes:
172
+ mask = Image.new("L", shape, 0)
173
+ mask_draw = ImageDraw.Draw(mask)
174
+ mask_draw.rectangle(bbox, fill=255)
175
+ masks.append(mask)
176
+ return masks
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import reactor_ui.reactor_upscale_ui as ui_upscale
2
+ import reactor_ui.reactor_tools_ui as ui_tools
3
+ import reactor_ui.reactor_settings_ui as ui_settings
4
+ import reactor_ui.reactor_main_ui as ui_main
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_main_ui.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from scripts.reactor_helpers import (
3
+ get_model_names,
4
+ get_facemodels
5
+ )
6
+ from scripts.reactor_swapper import (
7
+ clear_faces_list,
8
+ )
9
+ from modules import shared
10
+
11
+ SAVE_ORIGINAL: bool = False
12
+
13
+ def update_fm_list(selected: str):
14
+ return gr.Dropdown.update(
15
+ value=selected, choices=get_model_names(get_facemodels)
16
+ )
17
+
18
+ # TAB MAIN
19
+ def show(is_img2img: bool, show_br: bool = True, **msgs):
20
+
21
+ def on_select_source(selected: bool, evt: gr.SelectData):
22
+ global SAVE_ORIGINAL
23
+ if evt.index == 2:
24
+ if SAVE_ORIGINAL != selected:
25
+ SAVE_ORIGINAL = selected
26
+ return {
27
+ control_col_1: gr.Column.update(visible=False),
28
+ control_col_2: gr.Column.update(visible=False),
29
+ control_col_3: gr.Column.update(visible=True),
30
+ save_original: gr.Checkbox.update(value=False,visible=False),
31
+ imgs_hash_clear: gr.Button.update(visible=True)
32
+ }
33
+ if evt.index == 0:
34
+ return {
35
+ control_col_1: gr.Column.update(visible=True),
36
+ control_col_2: gr.Column.update(visible=False),
37
+ control_col_3: gr.Column.update(visible=False),
38
+ save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
39
+ imgs_hash_clear: gr.Button.update(visible=False)
40
+ }
41
+ if evt.index == 1:
42
+ return {
43
+ control_col_1: gr.Column.update(visible=False),
44
+ control_col_2: gr.Column.update(visible=True),
45
+ control_col_3: gr.Column.update(visible=False),
46
+ save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
47
+ imgs_hash_clear: gr.Button.update(visible=False)
48
+ }
49
+
50
+ progressbar_area = gr.Markdown("")
51
+ with gr.Tab("Main"):
52
+ with gr.Column():
53
+ with gr.Row():
54
+ select_source = gr.Radio(
55
+ ["Image(s)","Face Model","Folder"],
56
+ value="Image(s)",
57
+ label="Select Source",
58
+ type="index",
59
+ scale=1,
60
+ )
61
+ with gr.Column(visible=False) as control_col_2:
62
+ with gr.Row():
63
+ face_models = get_model_names(get_facemodels)
64
+ face_model = gr.Dropdown(
65
+ choices=face_models,
66
+ label="Choose Face Model",
67
+ value="None",
68
+ scale=1,
69
+ )
70
+ fm_update = gr.Button(
71
+ value="🔄",
72
+ variant="tool",
73
+ )
74
+ fm_update.click(
75
+ update_fm_list,
76
+ inputs=[face_model],
77
+ outputs=[face_model],
78
+ )
79
+ imgs_hash_clear = gr.Button(
80
+ value="Clear Source Images Hash",
81
+ scale=1,
82
+ visible=False,
83
+ )
84
+ imgs_hash_clear.click(clear_faces_list,None,[progressbar_area])
85
+ gr.Markdown("<br>", visible=show_br)
86
+ with gr.Column(visible=True) as control_col_1:
87
+ gr.Markdown("<center>🔽🔽🔽 Single Image has priority when both Areas in use 🔽🔽🔽</center>")
88
+ with gr.Row():
89
+ img = gr.Image(
90
+ type="pil",
91
+ label="Single Source Image",
92
+ )
93
+ imgs = gr.Files(
94
+ label=f"Multiple Source Images{msgs['extra_multiple_source']}",
95
+ file_types=["image"],
96
+ )
97
+ with gr.Column(visible=False) as control_col_3:
98
+ 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>")
99
+ source_folder = gr.Textbox(
100
+ value="",
101
+ placeholder="Paste here the path to the folder containing source faces images",
102
+ label=f"Source Folder{msgs['extra_multiple_source']}",
103
+ )
104
+ setattr(face_model, "do_not_save_to_config", True)
105
+ if is_img2img:
106
+ save_original = gr.Checkbox(
107
+ False,
108
+ label="Save Original (Swap in generated only)",
109
+ info="Save the original image(s) made before swapping (it always saves Original when you use Multiple Images or Folder)"
110
+ )
111
+ else:
112
+ save_original = gr.Checkbox(
113
+ False,
114
+ label="Save Original",
115
+ info="Save the original image(s) made before swapping (it always saves Original when you use Multiple Images or Folder)",
116
+ visible=show_br
117
+ )
118
+ # imgs.upload(on_files_upload_uncheck_so,[save_original],[save_original],show_progress=False)
119
+ # imgs.clear(on_files_clear,None,[save_original],show_progress=False)
120
+ imgs.clear(clear_faces_list,None,None,show_progress=False)
121
+ mask_face = gr.Checkbox(
122
+ False,
123
+ label="Face Mask Correction",
124
+ info="Apply this option if you see some pixelation around face contours"
125
+ )
126
+ gr.Markdown("<br>", visible=show_br)
127
+ gr.Markdown("Source Image (above):")
128
+ with gr.Row():
129
+ source_faces_index = gr.Textbox(
130
+ value="0",
131
+ placeholder="Which face(s) to use as Source (comma separated)",
132
+ label="Comma separated face number(s); Example: 0,2,1",
133
+ )
134
+ gender_source = gr.Radio(
135
+ ["No", "Female Only", "Male Only"],
136
+ value="No",
137
+ label="Gender Detection (Source)",
138
+ type="index",
139
+ )
140
+ gr.Markdown("<br>", visible=show_br)
141
+ gr.Markdown("Target Image (result):")
142
+ with gr.Row():
143
+ faces_index = gr.Textbox(
144
+ value="0",
145
+ placeholder="Which face(s) to Swap into Target (comma separated)",
146
+ label="Comma separated face number(s); Example: 1,0,2",
147
+ )
148
+ gender_target = gr.Radio(
149
+ ["No", "Female Only", "Male Only"],
150
+ value="No",
151
+ label="Gender Detection (Target)",
152
+ type="index",
153
+ )
154
+ gr.Markdown("<br>", visible=show_br)
155
+ with gr.Row():
156
+ face_restorer_name = gr.Radio(
157
+ label="Restore Face",
158
+ choices=["None"] + [x.name() for x in shared.face_restorers],
159
+ value=shared.face_restorers[0].name(),
160
+ type="value",
161
+ )
162
+ with gr.Column():
163
+ face_restorer_visibility = gr.Slider(
164
+ 0, 1, 1, step=0.1, label="Restore Face Visibility"
165
+ )
166
+ codeformer_weight = gr.Slider(
167
+ 0, 1, 0.5, step=0.1, label="CodeFormer Weight", info="0 = maximum effect, 1 = minimum effect"
168
+ )
169
+ gr.Markdown("<br>", visible=show_br)
170
+ swap_in_source = gr.Checkbox(
171
+ False,
172
+ label="Swap in source image",
173
+ visible=is_img2img,
174
+ )
175
+ swap_in_generated = gr.Checkbox(
176
+ True,
177
+ label="Swap in generated image",
178
+ visible=is_img2img,
179
+ )
180
+ 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)
181
+
182
+ 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_generated
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_settings_ui.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from scripts.reactor_logger import logger
3
+ from scripts.reactor_helpers import get_models, set_Device
4
+ from scripts.reactor_globals import DEVICE, DEVICE_LIST
5
+ try:
6
+ import torch.cuda as cuda
7
+ EP_is_visible = True if cuda.is_available() else False
8
+ except:
9
+ EP_is_visible = False
10
+
11
+ def update_models_list(selected: str):
12
+ return gr.Dropdown.update(
13
+ value=selected, choices=get_models()
14
+ )
15
+
16
+ def show(hash_check_block: bool = True):
17
+ # TAB SETTINGS
18
+ with gr.Tab("Settings"):
19
+ models = get_models()
20
+ with gr.Row(visible=EP_is_visible):
21
+ device = gr.Radio(
22
+ label="Execution Provider",
23
+ choices=DEVICE_LIST,
24
+ value=DEVICE,
25
+ type="value",
26
+ 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",
27
+ scale=2,
28
+ )
29
+ save_device_btn = gr.Button("Save", scale=0)
30
+ save = gr.Markdown("", visible=EP_is_visible)
31
+ setattr(device, "do_not_save_to_config", True)
32
+ save_device_btn.click(
33
+ set_Device,
34
+ inputs=[device],
35
+ outputs=[save],
36
+ )
37
+ with gr.Row():
38
+ if len(models) == 0:
39
+ logger.warning(
40
+ "You should at least have one model in models directory, please read the doc here: https://github.com/Gourieff/sd-webui-reactor/"
41
+ )
42
+ model = gr.Dropdown(
43
+ choices=models,
44
+ label="Model not found, please download one and refresh the list"
45
+ )
46
+ else:
47
+ model = gr.Dropdown(
48
+ choices=models, label="Model", value=models[0]
49
+ )
50
+ models_update = gr.Button(
51
+ value="🔄",
52
+ variant="tool",
53
+ )
54
+ models_update.click(
55
+ update_models_list,
56
+ inputs=[model],
57
+ outputs=[model],
58
+ )
59
+ console_logging_level = gr.Radio(
60
+ ["No log", "Minimum", "Default"],
61
+ value="Minimum",
62
+ label="Console Log Level",
63
+ type="index"
64
+ )
65
+ gr.Markdown("<br>", visible=hash_check_block)
66
+ with gr.Row(visible=hash_check_block):
67
+ source_hash_check = gr.Checkbox(
68
+ True,
69
+ label="Source Image Hash Check",
70
+ info="Recommended to keep it ON. Processing is faster when Source Image is the same."
71
+ )
72
+ target_hash_check = gr.Checkbox(
73
+ False,
74
+ label="Target Image Hash Check",
75
+ info="Affects if you use Extras tab or img2img with only 'Swap in source image' on."
76
+ )
77
+ return model, device, console_logging_level, source_hash_check, target_hash_check
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_tools_ui.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from scripts.reactor_swapper import build_face_model
3
+
4
+ # TAB TOOLS
5
+ def show():
6
+ with gr.Tab("Tools"):
7
+ with gr.Tab("Face Models"):
8
+ gr.Markdown("Load an image containing one person, name it and click 'Build and Save'")
9
+ img_fm = gr.Image(
10
+ type="pil",
11
+ label="Load Image to build Face Model",
12
+ )
13
+ with gr.Row(equal_height=True):
14
+ fm_name = gr.Textbox(
15
+ value="",
16
+ placeholder="Please type any name (e.g. Elena)",
17
+ label="Face Model Name",
18
+ )
19
+ save_fm_btn = gr.Button("Build and Save")
20
+ save_fm = gr.Markdown("You can find saved models in 'models/reactor/faces'")
21
+ save_fm_btn.click(
22
+ build_face_model,
23
+ inputs=[img_fm, fm_name],
24
+ outputs=[save_fm],
25
+ )
sd-webui-reactor-main/sd-webui-reactor-main/reactor_ui/reactor_upscale_ui.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from modules import shared
3
+
4
+ def update_upscalers_list(selected: str):
5
+ return gr.Dropdown.update(
6
+ value=selected, choices=[upscaler.name for upscaler in shared.sd_upscalers]
7
+ )
8
+
9
+ # TAB UPSCALE
10
+ def show(show_br: bool = True):
11
+ with gr.Tab("Upscale"):
12
+ restore_first = gr.Checkbox(
13
+ True,
14
+ label="1. Restore Face -> 2. Upscale (-Uncheck- if you want vice versa)",
15
+ info="Postprocessing Order"
16
+ )
17
+ with gr.Row():
18
+ upscaler_name = gr.Dropdown(
19
+ choices=[upscaler.name for upscaler in shared.sd_upscalers],
20
+ label="Upscaler",
21
+ value="None",
22
+ info="Won't scale if you choose -Swap in Source- via img2img, only 1x-postprocessing will affect (texturing, denoising, restyling etc.)"
23
+ )
24
+ upscalers_update = gr.Button(
25
+ value="🔄",
26
+ variant="tool",
27
+ )
28
+ upscalers_update.click(
29
+ update_upscalers_list,
30
+ inputs=[upscaler_name],
31
+ outputs=[upscaler_name],
32
+ )
33
+ gr.Markdown("<br>", visible=show_br)
34
+ with gr.Row():
35
+ upscaler_scale = gr.Slider(1, 8, 1, step=0.1, label="Scale by")
36
+ upscaler_visibility = gr.Slider(
37
+ 0, 1, 1, step=0.1, label="Upscaler Visibility (if scale = 1)"
38
+ )
39
+ return restore_first, upscaler_name, upscaler_scale, upscaler_visibility
sd-webui-reactor-main/sd-webui-reactor-main/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ insightface==0.7.3
2
+ onnx>=1.14.0
3
+ opencv-python>=4.7.0.72
sd-webui-reactor-main/sd-webui-reactor-main/scripts/console_log_patch.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path as osp
2
+ import glob
3
+ import logging
4
+ import insightface
5
+ from insightface.model_zoo.model_zoo import ModelRouter, PickableInferenceSession
6
+ from insightface.model_zoo.retinaface import RetinaFace
7
+ from insightface.model_zoo.landmark import Landmark
8
+ from insightface.model_zoo.attribute import Attribute
9
+ from insightface.model_zoo.inswapper import INSwapper
10
+ from insightface.model_zoo.arcface_onnx import ArcFaceONNX
11
+ from insightface.app import FaceAnalysis
12
+ from insightface.utils import DEFAULT_MP_NAME, ensure_available
13
+ from insightface.model_zoo import model_zoo
14
+ import onnxruntime
15
+ import onnx
16
+ from onnx import numpy_helper
17
+ from scripts.reactor_logger import logger
18
+
19
+
20
+ def patched_get_model(self, **kwargs):
21
+ session = PickableInferenceSession(self.onnx_file, **kwargs)
22
+ inputs = session.get_inputs()
23
+ input_cfg = inputs[0]
24
+ input_shape = input_cfg.shape
25
+ outputs = session.get_outputs()
26
+
27
+ if len(outputs) >= 5:
28
+ return RetinaFace(model_file=self.onnx_file, session=session)
29
+ elif input_shape[2] == 192 and input_shape[3] == 192:
30
+ return Landmark(model_file=self.onnx_file, session=session)
31
+ elif input_shape[2] == 96 and input_shape[3] == 96:
32
+ return Attribute(model_file=self.onnx_file, session=session)
33
+ elif len(inputs) == 2 and input_shape[2] == 128 and input_shape[3] == 128:
34
+ return INSwapper(model_file=self.onnx_file, session=session)
35
+ elif input_shape[2] == input_shape[3] and input_shape[2] >= 112 and input_shape[2] % 16 == 0:
36
+ return ArcFaceONNX(model_file=self.onnx_file, session=session)
37
+ else:
38
+ return None
39
+
40
+
41
+ def patched_faceanalysis_init(self, name=DEFAULT_MP_NAME, root='~/.insightface', allowed_modules=None, **kwargs):
42
+ onnxruntime.set_default_logger_severity(3)
43
+ self.models = {}
44
+ self.model_dir = ensure_available('models', name, root=root)
45
+ onnx_files = glob.glob(osp.join(self.model_dir, '*.onnx'))
46
+ onnx_files = sorted(onnx_files)
47
+ for onnx_file in onnx_files:
48
+ model = model_zoo.get_model(onnx_file, **kwargs)
49
+ if model is None:
50
+ print('model not recognized:', onnx_file)
51
+ elif allowed_modules is not None and model.taskname not in allowed_modules:
52
+ print('model ignore:', onnx_file, model.taskname)
53
+ del model
54
+ elif model.taskname not in self.models and (allowed_modules is None or model.taskname in allowed_modules):
55
+ self.models[model.taskname] = model
56
+ else:
57
+ print('duplicated model task type, ignore:', onnx_file, model.taskname)
58
+ del model
59
+ assert 'detection' in self.models
60
+ self.det_model = self.models['detection']
61
+
62
+
63
+ def patched_faceanalysis_prepare(self, ctx_id, det_thresh=0.5, det_size=(640, 640)):
64
+ self.det_thresh = det_thresh
65
+ assert det_size is not None
66
+ self.det_size = det_size
67
+ for taskname, model in self.models.items():
68
+ if taskname == 'detection':
69
+ model.prepare(ctx_id, input_size=det_size, det_thresh=det_thresh)
70
+ else:
71
+ model.prepare(ctx_id)
72
+
73
+
74
+ def patched_inswapper_init(self, model_file=None, session=None):
75
+ self.model_file = model_file
76
+ self.session = session
77
+ model = onnx.load(self.model_file)
78
+ graph = model.graph
79
+ self.emap = numpy_helper.to_array(graph.initializer[-1])
80
+ self.input_mean = 0.0
81
+ self.input_std = 255.0
82
+ if self.session is None:
83
+ self.session = onnxruntime.InferenceSession(self.model_file, None)
84
+ inputs = self.session.get_inputs()
85
+ self.input_names = []
86
+ for inp in inputs:
87
+ self.input_names.append(inp.name)
88
+ outputs = self.session.get_outputs()
89
+ output_names = []
90
+ for out in outputs:
91
+ output_names.append(out.name)
92
+ self.output_names = output_names
93
+ assert len(self.output_names) == 1
94
+ input_cfg = inputs[0]
95
+ input_shape = input_cfg.shape
96
+ self.input_shape = input_shape
97
+ self.input_size = tuple(input_shape[2:4][::-1])
98
+
99
+
100
+ def patch_insightface(get_model, faceanalysis_init, faceanalysis_prepare, inswapper_init):
101
+ insightface.model_zoo.model_zoo.ModelRouter.get_model = get_model
102
+ insightface.app.FaceAnalysis.__init__ = faceanalysis_init
103
+ insightface.app.FaceAnalysis.prepare = faceanalysis_prepare
104
+ insightface.model_zoo.inswapper.INSwapper.__init__ = inswapper_init
105
+
106
+
107
+ original_functions = [ModelRouter.get_model, FaceAnalysis.__init__, FaceAnalysis.prepare, INSwapper.__init__]
108
+ patched_functions = [patched_get_model, patched_faceanalysis_init, patched_faceanalysis_prepare, patched_inswapper_init]
109
+
110
+
111
+ def apply_logging_patch(console_logging_level):
112
+ if console_logging_level == 0:
113
+ patch_insightface(*patched_functions)
114
+ logger.setLevel(logging.WARNING)
115
+ elif console_logging_level == 1:
116
+ patch_insightface(*patched_functions)
117
+ logger.setLevel(logging.STATUS)
118
+ elif console_logging_level == 2:
119
+ patch_insightface(*original_functions)
120
+ logger.setLevel(logging.INFO)
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_api.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Thanks SpenserCai for the original version of the roop api script
3
+ -----------------------------------
4
+ --- ReActor External API v1.0.1 ---
5
+ -----------------------------------
6
+ '''
7
+ import os, glob
8
+ from datetime import datetime, date
9
+ from fastapi import FastAPI, Body
10
+
11
+ # from modules.api.models import *
12
+ from modules import scripts, shared
13
+ from modules.api import api
14
+
15
+ import gradio as gr
16
+
17
+ from scripts.reactor_swapper import EnhancementOptions, swap_face
18
+ from scripts.reactor_logger import logger
19
+
20
+
21
+ def default_file_path():
22
+ time = datetime.now()
23
+ today = date.today()
24
+ current_date = today.strftime('%Y-%m-%d')
25
+ current_time = time.strftime('%H-%M-%S')
26
+ output_file = 'output_'+current_date+'_'+current_time+'.png'
27
+ return os.path.join(os.path.abspath("outputs/api"), output_file)
28
+
29
+ def get_face_restorer(name):
30
+ for restorer in shared.face_restorers:
31
+ if restorer.name() == name:
32
+ return restorer
33
+ return None
34
+
35
+ def get_upscaler(name):
36
+ for upscaler in shared.sd_upscalers:
37
+ if upscaler.name == name:
38
+ return upscaler
39
+ return None
40
+
41
+ def get_models():
42
+ models_path = os.path.join(scripts.basedir(), "models/insightface/*")
43
+ models = glob.glob(models_path)
44
+ models = [x for x in models if x.endswith(".onnx") or x.endswith(".pth")]
45
+ return models
46
+
47
+ def get_full_model(model_name):
48
+ models = get_models()
49
+ for model in models:
50
+ model_path = os.path.split(model)
51
+ if model_path[1] == model_name:
52
+ return model
53
+ return None
54
+
55
+ def reactor_api(_: gr.Blocks, app: FastAPI):
56
+ @app.post("/reactor/image")
57
+ async def reactor_image(
58
+ source_image: str = Body("",title="Source Face Image"),
59
+ target_image: str = Body("",title="Target Image"),
60
+ source_faces_index: list[int] = Body([0],title="Comma separated face number(s) from swap-source image"),
61
+ face_index: list[int] = Body([0],title="Comma separated face number(s) for target image (result)"),
62
+ upscaler: str = Body("None",title="Upscaler"),
63
+ scale: int = Body(1,title="Scale by"),
64
+ upscale_visibility: float = Body(1,title="Upscaler visibility (if scale = 1)"),
65
+ face_restorer: str = Body("None",title="Restore Face: 0 - None; 1 - CodeFormer; 2 - GFPGA"),
66
+ restorer_visibility: float = Body(1,title="Restore visibility value"),
67
+ codeformer_weight: float = Body(0.5,title="CodeFormer Weight"),
68
+ restore_first: int = Body(1,title="Restore face -> Then upscale, 1 - True, 0 - False"),
69
+ model: str = Body("inswapper_128.onnx",title="Model"),
70
+ gender_source: int = Body(0,title="Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)"),
71
+ gender_target: int = Body(0,title="Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)"),
72
+ save_to_file: int = Body(0,title="Save Result to file, 0 - No, 1 - Yes"),
73
+ result_file_path: str = Body("",title="(if 'save_to_file = 1') Result file path"),
74
+ device: str = Body("CPU",title="CPU or CUDA (if you have it)"),
75
+ mask_face: int = Body(0,title="Face Mask Correction, 1 - True, 0 - False"),
76
+ select_source: int = Body(0,title="Select Source, 0 - Image, 1 - Face Model, 2 - Source Folder"),
77
+ face_model: str = Body("None",title="Filename of the face model (from 'models/reactor/faces'), e.g. elena.safetensors"),
78
+ source_folder: str = Body("",title="The path to the folder containing source faces images")
79
+ ):
80
+ s_image = api.decode_base64_to_image(source_image)
81
+ t_image = api.decode_base64_to_image(target_image)
82
+ sf_index = source_faces_index
83
+ f_index = face_index
84
+ gender_s = gender_source
85
+ gender_t = gender_target
86
+ restore_first_bool = True if restore_first == 1 else False
87
+ mask_face = True if mask_face == 1 else False
88
+ 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)
89
+ use_model = get_full_model(model)
90
+ if use_model is None:
91
+ Exception("Model not found")
92
+ 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)
93
+ if save_to_file == 1:
94
+ if result_file_path == "":
95
+ result_file_path = default_file_path()
96
+ try:
97
+ result[0].save(result_file_path, format='PNG')
98
+ logger.status("Result has been saved to: %s", result_file_path)
99
+ except Exception as e:
100
+ logger.error("Error while saving result: %s",e)
101
+ return {"image": api.encode_pil_to_base64(result[0])}
102
+
103
+ @app.get("/reactor/models")
104
+ async def reactor_models():
105
+ model_names = [os.path.split(model)[1] for model in get_models()]
106
+ return {"models": model_names}
107
+
108
+ @app.get("/reactor/upscalers")
109
+ async def reactor_upscalers():
110
+ names = [upscaler.name for upscaler in shared.sd_upscalers]
111
+ return {"upscalers": names}
112
+
113
+ try:
114
+ import modules.script_callbacks as script_callbacks
115
+
116
+ script_callbacks.on_app_started(reactor_api)
117
+ except:
118
+ pass
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_entities/face.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import traceback
2
+
3
+ import cv2
4
+ import numpy as np
5
+ from modules import images
6
+ from PIL import Image
7
+
8
+
9
+ from scripts.reactor_entities.rect import Point, Rect
10
+
11
+
12
+ class FaceArea:
13
+ def __init__(self, entire_image: np.ndarray, face_area: Rect, face_margin: float, face_size: int, upscaler: str):
14
+ self.face_area = face_area
15
+ self.center = face_area.center
16
+ left, top, right, bottom = face_area.to_square()
17
+
18
+ self.left, self.top, self.right, self.bottom = self.__ensure_margin(
19
+ left, top, right, bottom, entire_image, face_margin
20
+ )
21
+
22
+ self.width = self.right - self.left
23
+ self.height = self.bottom - self.top
24
+
25
+ self.image = self.__crop_face_image(entire_image, face_size, upscaler)
26
+ self.face_size = face_size
27
+ self.scale_factor = face_size / self.width
28
+ self.face_area_on_image = self.__get_face_area_on_image()
29
+ self.landmarks_on_image = self.__get_landmarks_on_image()
30
+
31
+ def __get_face_area_on_image(self):
32
+ left = int((self.face_area.left - self.left) * self.scale_factor)
33
+ top = int((self.face_area.top - self.top) * self.scale_factor)
34
+ right = int((self.face_area.right - self.left) * self.scale_factor)
35
+ bottom = int((self.face_area.bottom - self.top) * self.scale_factor)
36
+ return self.__clip_values(left, top, right, bottom)
37
+
38
+ def __get_landmarks_on_image(self):
39
+ landmarks = []
40
+ if self.face_area.landmarks is not None:
41
+ for landmark in self.face_area.landmarks:
42
+ landmarks.append(
43
+ Point(
44
+ int((landmark.x - self.left) * self.scale_factor),
45
+ int((landmark.y - self.top) * self.scale_factor),
46
+ )
47
+ )
48
+ return landmarks
49
+
50
+ def __crop_face_image(self, entire_image: np.ndarray, face_size: int, upscaler: str):
51
+ cropped = entire_image[self.top : self.bottom, self.left : self.right, :]
52
+ if upscaler:
53
+ return images.resize_image(0, Image.fromarray(cropped), face_size, face_size, upscaler)
54
+ else:
55
+ return Image.fromarray(cv2.resize(cropped, dsize=(face_size, face_size)))
56
+
57
+ def __ensure_margin(self, left: int, top: int, right: int, bottom: int, entire_image: np.ndarray, margin: float):
58
+ entire_height, entire_width = entire_image.shape[:2]
59
+
60
+ side_length = right - left
61
+ margin = min(min(entire_height, entire_width) / side_length, margin)
62
+ diff = int((side_length * margin - side_length) / 2)
63
+
64
+ top = top - diff
65
+ bottom = bottom + diff
66
+ left = left - diff
67
+ right = right + diff
68
+
69
+ if top < 0:
70
+ bottom = bottom - top
71
+ top = 0
72
+ if left < 0:
73
+ right = right - left
74
+ left = 0
75
+
76
+ if bottom > entire_height:
77
+ top = top - (bottom - entire_height)
78
+ bottom = entire_height
79
+ if right > entire_width:
80
+ left = left - (right - entire_width)
81
+ right = entire_width
82
+
83
+ return left, top, right, bottom
84
+
85
+ def get_angle(self) -> float:
86
+ landmarks = getattr(self.face_area, "landmarks", None)
87
+ if landmarks is None:
88
+ return 0
89
+
90
+ eye1 = getattr(landmarks, "eye1", None)
91
+ eye2 = getattr(landmarks, "eye2", None)
92
+ if eye2 is None or eye1 is None:
93
+ return 0
94
+
95
+ try:
96
+ dx = eye2.x - eye1.x
97
+ dy = eye2.y - eye1.y
98
+ if dx == 0:
99
+ dx = 1
100
+ angle = np.arctan(dy / dx) * 180 / np.pi
101
+
102
+ if dx < 0:
103
+ angle = (angle + 180) % 360
104
+ return angle
105
+ except Exception:
106
+ print(traceback.format_exc())
107
+ return 0
108
+
109
+ def rotate_face_area_on_image(self, angle: float):
110
+ center = [
111
+ (self.face_area_on_image[0] + self.face_area_on_image[2]) / 2,
112
+ (self.face_area_on_image[1] + self.face_area_on_image[3]) / 2,
113
+ ]
114
+
115
+ points = [
116
+ [self.face_area_on_image[0], self.face_area_on_image[1]],
117
+ [self.face_area_on_image[2], self.face_area_on_image[3]],
118
+ ]
119
+
120
+ angle = np.radians(angle)
121
+ rot_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
122
+
123
+ points = np.array(points) - center
124
+ points = np.dot(points, rot_matrix.T)
125
+ points += center
126
+ left, top, right, bottom = (int(points[0][0]), int(points[0][1]), int(points[1][0]), int(points[1][1]))
127
+
128
+ left, right = (right, left) if left > right else (left, right)
129
+ top, bottom = (bottom, top) if top > bottom else (top, bottom)
130
+
131
+ width, height = right - left, bottom - top
132
+ if width < height:
133
+ left, right = left - (height - width) // 2, right + (height - width) // 2
134
+ elif height < width:
135
+ top, bottom = top - (width - height) // 2, bottom + (width - height) // 2
136
+ return self.__clip_values(left, top, right, bottom)
137
+
138
+ def __clip_values(self, *args):
139
+ result = []
140
+ for val in args:
141
+ if val < 0:
142
+ result.append(0)
143
+ elif val > self.face_size:
144
+ result.append(self.face_size)
145
+ else:
146
+ result.append(val)
147
+ return tuple(result)
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_entities/rect.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, NamedTuple, Tuple
2
+
3
+ import numpy as np
4
+
5
+
6
+ class Point(NamedTuple):
7
+ x: int
8
+ y: int
9
+
10
+
11
+ class Landmarks(NamedTuple):
12
+ eye1: Point
13
+ eye2: Point
14
+ nose: Point
15
+ mouth1: Point
16
+ mouth2: Point
17
+
18
+
19
+ class Rect:
20
+ def __init__(
21
+ self,
22
+ left: int,
23
+ top: int,
24
+ right: int,
25
+ bottom: int,
26
+ tag: str = "face",
27
+ landmarks: Landmarks = None,
28
+ attributes: Dict[str, str] = {},
29
+ ) -> None:
30
+ self.tag = tag
31
+ self.left = left
32
+ self.top = top
33
+ self.right = right
34
+ self.bottom = bottom
35
+ self.center = int((right + left) / 2)
36
+ self.middle = int((top + bottom) / 2)
37
+ self.width = right - left
38
+ self.height = bottom - top
39
+ self.size = self.width * self.height
40
+ self.landmarks = landmarks
41
+ self.attributes = attributes
42
+
43
+ @classmethod
44
+ def from_ndarray(
45
+ cls,
46
+ face_box: np.ndarray,
47
+ tag: str = "face",
48
+ landmarks: Landmarks = None,
49
+ attributes: Dict[str, str] = {},
50
+ ) -> "Rect":
51
+ left, top, right, bottom, *_ = list(map(int, face_box))
52
+ return cls(left, top, right, bottom, tag, landmarks, attributes)
53
+
54
+ def to_tuple(self) -> Tuple[int, int, int, int]:
55
+ return self.left, self.top, self.right, self.bottom
56
+
57
+ def to_square(self):
58
+ left, top, right, bottom = self.to_tuple()
59
+
60
+ width = right - left
61
+ height = bottom - top
62
+
63
+ if width % 2 == 1:
64
+ right = right + 1
65
+ width = width + 1
66
+ if height % 2 == 1:
67
+ bottom = bottom + 1
68
+ height = height + 1
69
+
70
+ diff = int(abs(width - height) / 2)
71
+ if width > height:
72
+ top = top - diff
73
+ bottom = bottom + diff
74
+ else:
75
+ left = left - diff
76
+ right = right + diff
77
+
78
+ return left, top, right, bottom
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_faceswap.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, glob
2
+ import gradio as gr
3
+ from PIL import Image
4
+
5
+ from typing import List
6
+
7
+ import modules.scripts as scripts
8
+ from modules.upscaler import Upscaler, UpscalerData
9
+ from modules import scripts, shared, images, scripts_postprocessing
10
+ from modules.processing import (
11
+ Processed,
12
+ StableDiffusionProcessing,
13
+ StableDiffusionProcessingImg2Img,
14
+ )
15
+ from modules.face_restoration import FaceRestoration
16
+ from modules.images import save_image
17
+
18
+ from reactor_ui import ui_main, ui_upscale, ui_tools, ui_settings
19
+ from scripts.reactor_logger import logger
20
+ from scripts.reactor_swapper import (
21
+ EnhancementOptions,
22
+ swap_face,
23
+ check_process_halt,
24
+ reset_messaged,
25
+ )
26
+ from scripts.reactor_version import version_flag, app_title
27
+ from scripts.console_log_patch import apply_logging_patch
28
+ from scripts.reactor_helpers import (
29
+ make_grid,
30
+ set_Device,
31
+ )
32
+ from scripts.reactor_globals import SWAPPER_MODELS_PATH #, DEVICE, DEVICE_LIST
33
+
34
+
35
+ class FaceSwapScript(scripts.Script):
36
+ def title(self):
37
+ return f"{app_title}"
38
+
39
+ def show(self, is_img2img):
40
+ return scripts.AlwaysVisible
41
+
42
+ def ui(self, is_img2img):
43
+ with gr.Accordion(f"{app_title}", open=False):
44
+
45
+ # def on_files_upload_uncheck_so(selected: bool):
46
+ # global SAVE_ORIGINAL
47
+ # SAVE_ORIGINAL = selected
48
+ # return gr.Checkbox.update(value=False,visible=False)
49
+ # def on_files_clear():
50
+ # clear_faces_list()
51
+ # return gr.Checkbox.update(value=SAVE_ORIGINAL,visible=True)
52
+
53
+ enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}")
54
+ gr.Markdown("<br>")
55
+
56
+ # TAB MAIN
57
+ msgs: dict = {
58
+ "extra_multiple_source": "",
59
+ }
60
+ 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)
61
+
62
+ # TAB UPSCALE
63
+ restore_first, upscaler_name, upscaler_scale, upscaler_visibility = ui_upscale.show()
64
+
65
+ # TAB TOOLS
66
+ ui_tools.show()
67
+
68
+ # TAB SETTINGS
69
+ model, device, console_logging_level, source_hash_check, target_hash_check = ui_settings.show()
70
+
71
+ 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>")
72
+
73
+ return [
74
+ img,
75
+ enable,
76
+ source_faces_index,
77
+ faces_index,
78
+ model,
79
+ face_restorer_name,
80
+ face_restorer_visibility,
81
+ restore_first,
82
+ upscaler_name,
83
+ upscaler_scale,
84
+ upscaler_visibility,
85
+ swap_in_source,
86
+ swap_in_generated,
87
+ console_logging_level,
88
+ gender_source,
89
+ gender_target,
90
+ save_original,
91
+ codeformer_weight,
92
+ source_hash_check,
93
+ target_hash_check,
94
+ device,
95
+ mask_face,
96
+ select_source,
97
+ face_model,
98
+ source_folder,
99
+ imgs,
100
+ ]
101
+
102
+
103
+ @property
104
+ def upscaler(self) -> UpscalerData:
105
+ for upscaler in shared.sd_upscalers:
106
+ if upscaler.name == self.upscaler_name:
107
+ return upscaler
108
+ return None
109
+
110
+ @property
111
+ def face_restorer(self) -> FaceRestoration:
112
+ for face_restorer in shared.face_restorers:
113
+ if face_restorer.name() == self.face_restorer_name:
114
+ return face_restorer
115
+ return None
116
+
117
+ @property
118
+ def enhancement_options(self) -> EnhancementOptions:
119
+ return EnhancementOptions(
120
+ do_restore_first = self.restore_first,
121
+ scale=self.upscaler_scale,
122
+ upscaler=self.upscaler,
123
+ face_restorer=self.face_restorer,
124
+ upscale_visibility=self.upscaler_visibility,
125
+ restorer_visibility=self.face_restorer_visibility,
126
+ codeformer_weight=self.codeformer_weight,
127
+ )
128
+
129
+ def process(
130
+ self,
131
+ p: StableDiffusionProcessing,
132
+ img,
133
+ enable,
134
+ source_faces_index,
135
+ faces_index,
136
+ model,
137
+ face_restorer_name,
138
+ face_restorer_visibility,
139
+ restore_first,
140
+ upscaler_name,
141
+ upscaler_scale,
142
+ upscaler_visibility,
143
+ swap_in_source,
144
+ swap_in_generated,
145
+ console_logging_level,
146
+ gender_source,
147
+ gender_target,
148
+ save_original,
149
+ codeformer_weight,
150
+ source_hash_check,
151
+ target_hash_check,
152
+ device,
153
+ mask_face,
154
+ select_source,
155
+ face_model,
156
+ source_folder,
157
+ imgs,
158
+ ):
159
+ self.enable = enable
160
+ if self.enable:
161
+
162
+ logger.debug("*** Start process")
163
+
164
+ reset_messaged()
165
+ if check_process_halt():
166
+ return
167
+
168
+ global SWAPPER_MODELS_PATH
169
+ self.source = img
170
+ self.face_restorer_name = face_restorer_name
171
+ self.upscaler_scale = upscaler_scale
172
+ self.upscaler_visibility = upscaler_visibility
173
+ self.face_restorer_visibility = face_restorer_visibility
174
+ self.restore_first = restore_first
175
+ self.upscaler_name = upscaler_name
176
+ self.swap_in_source = swap_in_source
177
+ self.swap_in_generated = swap_in_generated
178
+ self.model = os.path.join(SWAPPER_MODELS_PATH,model)
179
+ self.console_logging_level = console_logging_level
180
+ self.gender_source = gender_source
181
+ self.gender_target = gender_target
182
+ self.save_original = save_original
183
+ self.codeformer_weight = codeformer_weight
184
+ self.source_hash_check = source_hash_check
185
+ self.target_hash_check = target_hash_check
186
+ self.device = device
187
+ self.mask_face = mask_face
188
+ self.select_source = select_source
189
+ self.face_model = face_model
190
+ self.source_folder = source_folder
191
+ self.source_imgs = imgs
192
+ if self.gender_source is None or self.gender_source == "No":
193
+ self.gender_source = 0
194
+ if self.gender_target is None or self.gender_target == "No":
195
+ self.gender_target = 0
196
+ self.source_faces_index = [
197
+ int(x) for x in source_faces_index.strip(",").split(",") if x.isnumeric()
198
+ ]
199
+ self.faces_index = [
200
+ int(x) for x in faces_index.strip(",").split(",") if x.isnumeric()
201
+ ]
202
+ if len(self.source_faces_index) == 0:
203
+ self.source_faces_index = [0]
204
+ if len(self.faces_index) == 0:
205
+ self.faces_index = [0]
206
+ if self.save_original is None:
207
+ self.save_original = False
208
+ if self.source_hash_check is None:
209
+ self.source_hash_check = True
210
+ if self.target_hash_check is None:
211
+ self.target_hash_check = False
212
+ if self.mask_face is None:
213
+ self.mask_face = False
214
+
215
+ logger.debug("*** Set Device")
216
+ set_Device(self.device)
217
+
218
+ 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):
219
+ logger.debug("*** Log patch")
220
+ apply_logging_patch(console_logging_level)
221
+ if isinstance(p, StableDiffusionProcessingImg2Img) and self.swap_in_source:
222
+ logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
223
+
224
+ for i in range(len(p.init_images)):
225
+ if len(p.init_images) > 1:
226
+ logger.status("Swap in %s", i)
227
+ result, output, swapped = swap_face(
228
+ self.source,
229
+ p.init_images[i],
230
+ source_faces_index=self.source_faces_index,
231
+ faces_index=self.faces_index,
232
+ model=self.model,
233
+ enhancement_options=self.enhancement_options,
234
+ gender_source=self.gender_source,
235
+ gender_target=self.gender_target,
236
+ source_hash_check=self.source_hash_check,
237
+ target_hash_check=self.target_hash_check,
238
+ device=self.device,
239
+ mask_face=self.mask_face,
240
+ select_source=self.select_source,
241
+ face_model = self.face_model,
242
+ source_folder = None,
243
+ source_imgs = None,
244
+ )
245
+ p.init_images[i] = result
246
+ # 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")
247
+ # if len(output) != 0:
248
+ # with open(result_path, 'w', encoding="utf8") as f:
249
+ # f.writelines(output)
250
+
251
+ if shared.state.interrupted or shared.state.skipped:
252
+ return
253
+
254
+ else:
255
+ logger.error("Please provide a source face")
256
+ return
257
+
258
+ def postprocess(self, p: StableDiffusionProcessing, processed: Processed, *args):
259
+ if self.enable:
260
+
261
+ logger.debug("*** Check postprocess")
262
+
263
+ reset_messaged()
264
+ if check_process_halt():
265
+ return
266
+
267
+ 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)):
268
+
269
+ postprocess_run: bool = True
270
+
271
+ orig_images : List[Image.Image] = processed.images[processed.index_of_first_image:]
272
+ orig_infotexts : List[str] = processed.infotexts[processed.index_of_first_image:]
273
+
274
+ result_images: List = processed.images
275
+ # result_info: List = processed.infotexts
276
+
277
+ if self.swap_in_generated:
278
+
279
+ logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
280
+
281
+ if self.source is not None:
282
+ # self.source_folder = None
283
+ self.source_imgs = None
284
+
285
+ for i,(img,info) in enumerate(zip(orig_images, orig_infotexts)):
286
+ if check_process_halt():
287
+ postprocess_run = False
288
+ break
289
+ if len(orig_images) > 1:
290
+ logger.status("Swap in %s", i)
291
+ result, output, swapped = swap_face(
292
+ self.source,
293
+ img,
294
+ source_faces_index=self.source_faces_index,
295
+ faces_index=self.faces_index,
296
+ model=self.model,
297
+ enhancement_options=self.enhancement_options,
298
+ gender_source=self.gender_source,
299
+ gender_target=self.gender_target,
300
+ source_hash_check=self.source_hash_check,
301
+ target_hash_check=self.target_hash_check,
302
+ device=self.device,
303
+ mask_face=self.mask_face,
304
+ select_source=self.select_source,
305
+ face_model = self.face_model,
306
+ source_folder = self.source_folder,
307
+ source_imgs = self.source_imgs,
308
+ )
309
+
310
+ if self.select_source == 2 or (self.select_source == 0 and self.source_imgs is not None and self.source is None):
311
+ if len(result) > 0 and swapped > 0:
312
+ result_images.extend(result)
313
+ suffix = "-swapped"
314
+ for i,x in enumerate(result):
315
+ try:
316
+ img_path = save_image(result[i], p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png",info=info, p=p, suffix=suffix)
317
+ except:
318
+ logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)")
319
+ elif len(result) == 0:
320
+ logger.error("Cannot create a result image")
321
+
322
+ else:
323
+ if result is not None and swapped > 0:
324
+ result_images.append(result)
325
+ suffix = "-swapped"
326
+ try:
327
+ img_path = save_image(result, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png",info=info, p=p, suffix=suffix)
328
+ except:
329
+ logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)")
330
+ elif result is None:
331
+ logger.error("Cannot create a result image")
332
+
333
+ # if len(output) != 0:
334
+ # split_fullfn = os.path.splitext(img_path[0])
335
+ # fullfn = split_fullfn[0] + ".txt"
336
+ # with open(fullfn, 'w', encoding="utf8") as f:
337
+ # f.writelines(output)
338
+
339
+ if shared.opts.return_grid and len(result_images) > 2 and postprocess_run:
340
+ grid = make_grid(result_images)
341
+ result_images.insert(0, grid)
342
+ try:
343
+ 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)
344
+ except:
345
+ logger.error("Cannot save a grid - please, check SD WebUI Settings (Saving and Paths)")
346
+
347
+ processed.images = result_images
348
+ # processed.infotexts = result_info
349
+
350
+ def postprocess_batch(self, p, *args, **kwargs):
351
+ if self.enable and not self.save_original:
352
+ logger.debug("*** Check postprocess_batch")
353
+ images = kwargs["images"]
354
+
355
+ def postprocess_image(self, p, script_pp: scripts.PostprocessImageArgs, *args):
356
+ 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):
357
+
358
+ logger.debug("*** Check postprocess_image")
359
+
360
+ current_job_number = shared.state.job_no + 1
361
+ job_count = shared.state.job_count
362
+ if current_job_number == job_count:
363
+ reset_messaged()
364
+ if check_process_halt():
365
+ return
366
+
367
+ # 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):
368
+ logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
369
+ image: Image.Image = script_pp.image
370
+ result, output, swapped = swap_face(
371
+ self.source,
372
+ image,
373
+ source_faces_index=self.source_faces_index,
374
+ faces_index=self.faces_index,
375
+ model=self.model,
376
+ enhancement_options=self.enhancement_options,
377
+ gender_source=self.gender_source,
378
+ gender_target=self.gender_target,
379
+ source_hash_check=self.source_hash_check,
380
+ target_hash_check=self.target_hash_check,
381
+ device=self.device,
382
+ mask_face=self.mask_face,
383
+ select_source=self.select_source,
384
+ face_model = self.face_model,
385
+ source_folder = None,
386
+ source_imgs = None,
387
+ )
388
+ try:
389
+ pp = scripts_postprocessing.PostprocessedImage(result)
390
+ pp.info = {}
391
+ p.extra_generation_params.update(pp.info)
392
+ script_pp.image = pp.image
393
+
394
+ # if len(output) != 0:
395
+ # result_path = get_image_path(script_pp.image, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "txt", p=p, suffix="-swapped")
396
+ # if len(output) != 0:
397
+ # with open(result_path, 'w', encoding="utf8") as f:
398
+ # f.writelines(output)
399
+ except:
400
+ logger.error("Cannot create a result image")
401
+
402
+
403
+ class FaceSwapScriptExtras(scripts_postprocessing.ScriptPostprocessing):
404
+ name = 'ReActor'
405
+ order = 20000
406
+
407
+ def ui(self):
408
+ with gr.Accordion(f"{app_title}", open=False):
409
+
410
+ enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}")
411
+
412
+ # TAB MAIN
413
+ msgs: dict = {
414
+ "extra_multiple_source": " | Сomparison grid as a result",
415
+ }
416
+ 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)
417
+
418
+ # TAB UPSCALE
419
+ restore_first, upscaler_name, upscaler_scale, upscaler_visibility = ui_upscale.show(show_br=False)
420
+
421
+ # TAB TOOLS
422
+ ui_tools.show()
423
+
424
+ # TAB SETTINGS
425
+ model, device, console_logging_level, source_hash_check, target_hash_check = ui_settings.show(hash_check_block=False)
426
+
427
+ 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>")
428
+
429
+ args = {
430
+ 'img': img,
431
+ 'enable': enable,
432
+ 'source_faces_index': source_faces_index,
433
+ 'faces_index': faces_index,
434
+ 'model': model,
435
+ 'face_restorer_name': face_restorer_name,
436
+ 'face_restorer_visibility': face_restorer_visibility,
437
+ 'restore_first': restore_first,
438
+ 'upscaler_name': upscaler_name,
439
+ 'upscaler_scale': upscaler_scale,
440
+ 'upscaler_visibility': upscaler_visibility,
441
+ 'console_logging_level': console_logging_level,
442
+ 'gender_source': gender_source,
443
+ 'gender_target': gender_target,
444
+ 'codeformer_weight': codeformer_weight,
445
+ 'device': device,
446
+ 'mask_face': mask_face,
447
+ 'select_source': select_source,
448
+ 'face_model': face_model,
449
+ 'source_folder': source_folder,
450
+ 'imgs': imgs,
451
+ }
452
+ return args
453
+
454
+ @property
455
+ def upscaler(self) -> UpscalerData:
456
+ for upscaler in shared.sd_upscalers:
457
+ if upscaler.name == self.upscaler_name:
458
+ return upscaler
459
+ return None
460
+
461
+ @property
462
+ def face_restorer(self) -> FaceRestoration:
463
+ for face_restorer in shared.face_restorers:
464
+ if face_restorer.name() == self.face_restorer_name:
465
+ return face_restorer
466
+ return None
467
+
468
+ @property
469
+ def enhancement_options(self) -> EnhancementOptions:
470
+ return EnhancementOptions(
471
+ do_restore_first=self.restore_first,
472
+ scale=self.upscaler_scale,
473
+ upscaler=self.upscaler,
474
+ face_restorer=self.face_restorer,
475
+ upscale_visibility=self.upscaler_visibility,
476
+ restorer_visibility=self.face_restorer_visibility,
477
+ codeformer_weight=self.codeformer_weight,
478
+ )
479
+
480
+ def process(self, pp: scripts_postprocessing.PostprocessedImage, **args):
481
+ if args['enable']:
482
+ reset_messaged()
483
+ if check_process_halt():
484
+ return
485
+
486
+ global SWAPPER_MODELS_PATH
487
+ self.source = args['img']
488
+ self.face_restorer_name = args['face_restorer_name']
489
+ self.upscaler_scale = args['upscaler_scale']
490
+ self.upscaler_visibility = args['upscaler_visibility']
491
+ self.face_restorer_visibility = args['face_restorer_visibility']
492
+ self.restore_first = args['restore_first']
493
+ self.upscaler_name = args['upscaler_name']
494
+ self.model = os.path.join(SWAPPER_MODELS_PATH, args['model'])
495
+ self.console_logging_level = args['console_logging_level']
496
+ self.gender_source = args['gender_source']
497
+ self.gender_target = args['gender_target']
498
+ self.codeformer_weight = args['codeformer_weight']
499
+ self.device = args['device']
500
+ self.mask_face = args['mask_face']
501
+ self.select_source = args['select_source']
502
+ self.face_model = args['face_model']
503
+ self.source_folder = args['source_folder']
504
+ self.source_imgs = args['imgs']
505
+ if self.gender_source is None or self.gender_source == "No":
506
+ self.gender_source = 0
507
+ if self.gender_target is None or self.gender_target == "No":
508
+ self.gender_target = 0
509
+ self.source_faces_index = [
510
+ int(x) for x in args['source_faces_index'].strip(",").split(",") if x.isnumeric()
511
+ ]
512
+ self.faces_index = [
513
+ int(x) for x in args['faces_index'].strip(",").split(",") if x.isnumeric()
514
+ ]
515
+ if len(self.source_faces_index) == 0:
516
+ self.source_faces_index = [0]
517
+ if len(self.faces_index) == 0:
518
+ self.faces_index = [0]
519
+ if self.mask_face is None:
520
+ self.mask_face = False
521
+
522
+ current_job_number = shared.state.job_no + 1
523
+ job_count = shared.state.job_count
524
+ if current_job_number == job_count:
525
+ reset_messaged()
526
+
527
+ set_Device(self.device)
528
+
529
+ logger.debug("We're here: process() 1")
530
+
531
+ 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):
532
+
533
+ logger.debug("We're here: process() 2")
534
+
535
+ apply_logging_patch(self.console_logging_level)
536
+ logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
537
+ # if self.select_source != 2:
538
+ image: Image.Image = pp.image
539
+ result, output, swapped = swap_face(
540
+ self.source,
541
+ image,
542
+ source_faces_index=self.source_faces_index,
543
+ faces_index=self.faces_index,
544
+ model=self.model,
545
+ enhancement_options=self.enhancement_options,
546
+ gender_source=self.gender_source,
547
+ gender_target=self.gender_target,
548
+ source_hash_check=True,
549
+ target_hash_check=True,
550
+ device=self.device,
551
+ mask_face=self.mask_face,
552
+ select_source=self.select_source,
553
+ face_model=self.face_model,
554
+ source_folder=self.source_folder,
555
+ source_imgs=self.source_imgs,
556
+ )
557
+ if self.select_source == 2 or (self.select_source == 0 and self.source_imgs is not None and self.source is None):
558
+ if len(result) > 0 and swapped > 0:
559
+ image = result[0]
560
+ if len(result) > 1:
561
+ grid = make_grid(result)
562
+ result.insert(0, grid)
563
+ image = grid
564
+ pp.info["ReActor"] = True
565
+ pp.image = image
566
+ logger.status("---Done!---")
567
+ else:
568
+ logger.error("Cannot create a result image")
569
+ else:
570
+ try:
571
+ pp.info["ReActor"] = True
572
+ pp.image = result
573
+ logger.status("---Done!---")
574
+ except Exception:
575
+ logger.error("Cannot create a result image")
576
+ else:
577
+ logger.error("Please provide a source face")
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_globals.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ try:
5
+ from modules.paths_internal import models_path
6
+ except:
7
+ try:
8
+ from modules.paths import models_path
9
+ except:
10
+ models_path = os.path.abspath("models")
11
+
12
+ IS_RUN: bool = False
13
+ BASE_PATH = os.path.join(Path(__file__).parents[1])
14
+ DEVICE_LIST: list = ["CPU", "CUDA"]
15
+
16
+ MODELS_PATH = models_path
17
+ SWAPPER_MODELS_PATH = os.path.join(MODELS_PATH, "insightface")
18
+ REACTOR_MODELS_PATH = os.path.join(MODELS_PATH, "reactor")
19
+ FACE_MODELS_PATH = os.path.join(REACTOR_MODELS_PATH, "faces")
20
+
21
+ if not os.path.exists(REACTOR_MODELS_PATH):
22
+ os.makedirs(REACTOR_MODELS_PATH)
23
+ if not os.path.exists(FACE_MODELS_PATH):
24
+ os.makedirs(FACE_MODELS_PATH)
25
+
26
+ def updateDevice():
27
+ try:
28
+ LAST_DEVICE_PATH = os.path.join(BASE_PATH, "last_device.txt")
29
+ with open(LAST_DEVICE_PATH) as f:
30
+ device = f.readline().strip()
31
+ if device not in DEVICE_LIST:
32
+ print(f"Error: Device {device} is not in DEVICE_LIST")
33
+ device = DEVICE_LIST[0]
34
+ print(f"Execution Provider has been set to {device}")
35
+ except Exception as e:
36
+ device = DEVICE_LIST[0]
37
+ print(f"Error: {e}\nExecution Provider has been set to {device}")
38
+ return device
39
+
40
+ DEVICE = updateDevice()
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_helpers.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, glob
2
+ from collections import Counter
3
+ from PIL import Image
4
+ from math import isqrt, ceil
5
+ from typing import List
6
+ import logging
7
+ import hashlib
8
+ import torch
9
+ from safetensors.torch import save_file, safe_open
10
+ from insightface.app.common import Face
11
+
12
+ from modules.images import FilenameGenerator, get_next_sequence_number
13
+ from modules import shared, script_callbacks
14
+ from scripts.reactor_globals import DEVICE, BASE_PATH, FACE_MODELS_PATH
15
+
16
+ try:
17
+ from modules.paths_internal import models_path
18
+ except:
19
+ try:
20
+ from modules.paths import models_path
21
+ except:
22
+ model_path = os.path.abspath("models")
23
+
24
+ MODELS_PATH = None
25
+
26
+ def set_Device(value):
27
+ global DEVICE
28
+ DEVICE = value
29
+ with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
30
+ txt.write(DEVICE)
31
+
32
+ def get_Device():
33
+ global DEVICE
34
+ return DEVICE
35
+
36
+ def make_grid(image_list: List):
37
+
38
+ # Count the occurrences of each image size in the image_list
39
+ size_counter = Counter(image.size for image in image_list)
40
+
41
+ # Get the most common image size (size with the highest count)
42
+ common_size = size_counter.most_common(1)[0][0]
43
+
44
+ # Filter the image_list to include only images with the common size
45
+ image_list = [image for image in image_list if image.size == common_size]
46
+
47
+ # Get the dimensions (width and height) of the common size
48
+ size = common_size
49
+
50
+ # If there are more than one image in the image_list
51
+ if len(image_list) > 1:
52
+ num_images = len(image_list)
53
+
54
+ # Calculate the number of rows and columns for the grid
55
+ rows = isqrt(num_images)
56
+ cols = ceil(num_images / rows)
57
+
58
+ # Calculate the size of the square image
59
+ square_size = (cols * size[0], rows * size[1])
60
+
61
+ # Create a new RGB image with the square size
62
+ square_image = Image.new("RGB", square_size)
63
+
64
+ # Paste each image onto the square image at the appropriate position
65
+ for i, image in enumerate(image_list):
66
+ row = i // cols
67
+ col = i % cols
68
+
69
+ square_image.paste(image, (col * size[0], row * size[1]))
70
+
71
+ # Return the resulting square image
72
+ return square_image
73
+
74
+ # Return None if there are no images or only one image in the image_list
75
+ return None
76
+
77
+ def get_image_path(image, path, basename, seed=None, prompt=None, extension='png', p=None, suffix=""):
78
+
79
+ namegen = FilenameGenerator(p, seed, prompt, image)
80
+
81
+ save_to_dirs = shared.opts.save_to_dirs
82
+
83
+ if save_to_dirs:
84
+ dirname = namegen.apply(shared.opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
85
+ path = os.path.join(path, dirname)
86
+
87
+ os.makedirs(path, exist_ok=True)
88
+
89
+ if seed is None:
90
+ file_decoration = ""
91
+ elif shared.opts.save_to_dirs:
92
+ file_decoration = shared.opts.samples_filename_pattern or "[seed]"
93
+ else:
94
+ file_decoration = shared.opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
95
+
96
+ file_decoration = namegen.apply(file_decoration) + suffix
97
+
98
+ add_number = shared.opts.save_images_add_number or file_decoration == ''
99
+
100
+ if file_decoration != "" and add_number:
101
+ file_decoration = f"-{file_decoration}"
102
+
103
+ if add_number:
104
+ basecount = get_next_sequence_number(path, basename)
105
+ fullfn = None
106
+ for i in range(500):
107
+ fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
108
+ fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
109
+ if not os.path.exists(fullfn):
110
+ break
111
+ else:
112
+ fullfn = os.path.join(path, f"{file_decoration}.{extension}")
113
+
114
+ pnginfo = {}
115
+
116
+ params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
117
+ # script_callbacks.before_image_saved_callback(params)
118
+
119
+ fullfn = params.filename
120
+
121
+ fullfn_without_extension, extension = os.path.splitext(params.filename)
122
+ if hasattr(os, 'statvfs'):
123
+ max_name_len = os.statvfs(path).f_namemax
124
+ fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
125
+ params.filename = fullfn_without_extension + extension
126
+ fullfn = params.filename
127
+
128
+ return fullfn
129
+
130
+ def addLoggingLevel(levelName, levelNum, methodName=None):
131
+ if not methodName:
132
+ methodName = levelName.lower()
133
+
134
+ def logForLevel(self, message, *args, **kwargs):
135
+ if self.isEnabledFor(levelNum):
136
+ self._log(levelNum, message, args, **kwargs)
137
+
138
+ def logToRoot(message, *args, **kwargs):
139
+ logging.log(levelNum, message, *args, **kwargs)
140
+
141
+ logging.addLevelName(levelNum, levelName)
142
+ setattr(logging, levelName, levelNum)
143
+ setattr(logging.getLoggerClass(), methodName, logForLevel)
144
+ setattr(logging, methodName, logToRoot)
145
+
146
+ def get_image_md5hash(image: Image.Image):
147
+ md5hash = hashlib.md5(image.tobytes())
148
+ return md5hash.hexdigest()
149
+
150
+ def save_face_model(face: Face, filename: str) -> None:
151
+ try:
152
+ tensors = {
153
+ "bbox": torch.tensor(face["bbox"]),
154
+ "kps": torch.tensor(face["kps"]),
155
+ "det_score": torch.tensor(face["det_score"]),
156
+ "landmark_3d_68": torch.tensor(face["landmark_3d_68"]),
157
+ "pose": torch.tensor(face["pose"]),
158
+ "landmark_2d_106": torch.tensor(face["landmark_2d_106"]),
159
+ "embedding": torch.tensor(face["embedding"]),
160
+ "gender": torch.tensor(face["gender"]),
161
+ "age": torch.tensor(face["age"]),
162
+ }
163
+ save_file(tensors, filename)
164
+ # print(f"Face model has been saved to '{filename}'")
165
+ except Exception as e:
166
+ print(f"Error: {e}")
167
+
168
+ def get_models():
169
+ global MODELS_PATH
170
+ models_path_init = os.path.join(models_path, "insightface/*")
171
+ models = glob.glob(models_path_init)
172
+ models = [x for x in models if x.endswith(".onnx") or x.endswith(".pth")]
173
+ models_names = []
174
+ for model in models:
175
+ model_path = os.path.split(model)
176
+ if MODELS_PATH is None:
177
+ MODELS_PATH = model_path[0]
178
+ model_name = model_path[1]
179
+ models_names.append(model_name)
180
+ return models_names
181
+
182
+ def load_face_model(filename: str):
183
+ face = {}
184
+ model_path = os.path.join(FACE_MODELS_PATH, filename)
185
+ with safe_open(model_path, framework="pt") as f:
186
+ for k in f.keys():
187
+ face[k] = f.get_tensor(k).numpy()
188
+ return Face(face)
189
+
190
+ def get_facemodels():
191
+ models_path = os.path.join(FACE_MODELS_PATH, "*")
192
+ models = glob.glob(models_path)
193
+ models = [x for x in models if x.endswith(".safetensors")]
194
+ return models
195
+
196
+ def get_model_names(get_models):
197
+ models = get_models()
198
+ names = ["None"]
199
+ for x in models:
200
+ names.append(os.path.basename(x))
201
+ return names
202
+
203
+ def get_images_from_folder(path: str):
204
+ images_path = os.path.join(path, "*")
205
+ images = glob.glob(images_path)
206
+ return [Image.open(x) for x in images if x.endswith(('jpg', 'png', 'jpeg', 'webp', 'bmp'))]
207
+
208
+ def get_images_from_list(imgs: List):
209
+ return [Image.open(os.path.abspath(x.name)) for x in imgs]
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_inferencers/bisenet_mask_generator.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple
2
+
3
+ import cv2
4
+ import modules.shared as shared
5
+ import numpy as np
6
+ import torch
7
+ from facexlib.parsing import init_parsing_model
8
+ from facexlib.utils.misc import img2tensor
9
+ from torchvision.transforms.functional import normalize
10
+ from scripts.reactor_inferencers.mask_generator import MaskGenerator
11
+
12
+ class BiSeNetMaskGenerator(MaskGenerator):
13
+ def __init__(self) -> None:
14
+ self.mask_model = init_parsing_model(device=shared.device)
15
+
16
+ def name(self):
17
+ return "BiSeNet"
18
+
19
+ def generate_mask(
20
+ self,
21
+ face_image: np.ndarray,
22
+ face_area_on_image: Tuple[int, int, int, int],
23
+ affected_areas: List[str],
24
+ mask_size: int,
25
+ use_minimal_area: bool,
26
+ fallback_ratio: float = 0.25,
27
+ **kwargs,
28
+ ) -> np.ndarray:
29
+ # original_face_image = face_image
30
+ face_image = face_image.copy()
31
+ face_image = face_image[:, :, ::-1]
32
+
33
+ if use_minimal_area:
34
+ face_image = MaskGenerator.mask_non_face_areas(face_image, face_area_on_image)
35
+
36
+ h, w, _ = face_image.shape
37
+
38
+ if w != 512 or h != 512:
39
+ rw = (int(w * (512 / w)) // 8) * 8
40
+ rh = (int(h * (512 / h)) // 8) * 8
41
+ face_image = cv2.resize(face_image, dsize=(rw, rh))
42
+
43
+ face_tensor = img2tensor(face_image.astype("float32") / 255.0, float32=True)
44
+ normalize(face_tensor, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
45
+ face_tensor = torch.unsqueeze(face_tensor, 0).to(shared.device)
46
+
47
+ with torch.no_grad():
48
+ face = self.mask_model(face_tensor)[0]
49
+ face = face.squeeze(0).cpu().numpy().argmax(0)
50
+ face = face.copy().astype(np.uint8)
51
+
52
+ mask = self.__to_mask(face, affected_areas)
53
+
54
+ if mask_size > 0:
55
+ mask = cv2.dilate(mask, np.ones((5, 5), np.uint8), iterations=mask_size)
56
+
57
+ if w != 512 or h != 512:
58
+ mask = cv2.resize(mask, dsize=(w, h))
59
+
60
+ # """if MaskGenerator.calculate_mask_coverage(mask) < fallback_ratio:
61
+ # logger.info("Use fallback mask generator")
62
+ # mask = self.fallback_mask_generator.generate_mask(
63
+ # original_face_image, face_area_on_image, use_minimal_area=True
64
+ # )"""
65
+
66
+ return mask
67
+
68
+ def __to_mask(self, face: np.ndarray, affected_areas: List[str]) -> np.ndarray:
69
+ keep_face = "Face" in affected_areas
70
+ keep_neck = "Neck" in affected_areas
71
+ keep_hair = "Hair" in affected_areas
72
+ keep_hat = "Hat" in affected_areas
73
+
74
+ mask = np.zeros((face.shape[0], face.shape[1], 3), dtype=np.uint8)
75
+ num_of_class = np.max(face)
76
+ for i in range(1, num_of_class + 1):
77
+ index = np.where(face == i)
78
+ if i < 14 and keep_face:
79
+ mask[index[0], index[1], :] = [255, 255, 255]
80
+ elif i == 14 and keep_neck:
81
+ mask[index[0], index[1], :] = [255, 255, 255]
82
+ elif i == 17 and keep_hair:
83
+ mask[index[0], index[1], :] = [255, 255, 255]
84
+ elif i == 18 and keep_hat:
85
+ mask[index[0], index[1], :] = [255, 255, 255]
86
+ return mask
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_inferencers/mask_generator.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Tuple
3
+
4
+ import cv2
5
+ import numpy as np
6
+
7
+ class MaskGenerator(ABC):
8
+ @abstractmethod
9
+ def name(self) -> str:
10
+ pass
11
+
12
+ @abstractmethod
13
+ def generate_mask(
14
+ self,
15
+ face_image: np.ndarray,
16
+ face_area_on_image: Tuple[int, int, int, int],
17
+ **kwargs,
18
+ ) -> np.ndarray:
19
+ pass
20
+
21
+ @staticmethod
22
+ def mask_non_face_areas(image: np.ndarray, face_area_on_image: Tuple[int, int, int, int]) -> np.ndarray:
23
+ left, top, right, bottom = face_area_on_image
24
+ image = image.copy()
25
+ image[:top, :] = 0
26
+ image[bottom:, :] = 0
27
+ image[:, :left] = 0
28
+ image[:, right:] = 0
29
+ return image
30
+
31
+ @staticmethod
32
+ def calculate_mask_coverage(mask: np.ndarray):
33
+ gray_mask = cv2.cvtColor(mask, cv2.COLOR_RGB2GRAY)
34
+ non_black_pixels = np.count_nonzero(gray_mask)
35
+ total_pixels = gray_mask.size
36
+ return non_black_pixels / total_pixels
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_logger.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import copy
3
+ import sys
4
+
5
+ from modules import shared
6
+ from scripts.reactor_globals import IS_RUN
7
+ from scripts.reactor_helpers import addLoggingLevel
8
+
9
+
10
+ class ColoredFormatter(logging.Formatter):
11
+ COLORS = {
12
+ "DEBUG": "\033[0;36m", # CYAN
13
+ "STATUS": "\033[38;5;173m", # Calm ORANGE
14
+ "INFO": "\033[0;32m", # GREEN
15
+ "WARNING": "\033[0;33m", # YELLOW
16
+ "ERROR": "\033[0;31m", # RED
17
+ "CRITICAL": "\033[0;37;41m", # WHITE ON RED
18
+ "RESET": "\033[0m", # RESET COLOR
19
+ }
20
+
21
+ def format(self, record):
22
+ colored_record = copy.copy(record)
23
+ levelname = colored_record.levelname
24
+ seq = self.COLORS.get(levelname, self.COLORS["RESET"])
25
+ colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
26
+ return super().format(colored_record)
27
+
28
+
29
+ # Create a new logger
30
+ logger = logging.getLogger("ReActor")
31
+ logger.propagate = False
32
+
33
+ # Add Custom Level
34
+ addLoggingLevel("STATUS", logging.INFO + 5)
35
+
36
+ # Add handler if we don't have one.
37
+ if not logger.handlers:
38
+ handler = logging.StreamHandler(sys.stdout)
39
+ handler.setFormatter(
40
+ ColoredFormatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s","%H:%M:%S")
41
+ )
42
+ logger.addHandler(handler)
43
+
44
+ # Configure logger
45
+ loglevel_string = getattr(shared.cmd_opts, "reactor_loglevel", "INFO")
46
+ loglevel = getattr(logging, loglevel_string.upper(), "info")
47
+ logger.setLevel(loglevel)
48
+
49
+ def set_Run(value):
50
+ global IS_RUN
51
+ IS_RUN = value
52
+
53
+ def get_Run():
54
+ global IS_RUN
55
+ return IS_RUN
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_swapper.py ADDED
@@ -0,0 +1,715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ from dataclasses import dataclass
4
+ from typing import List, Union
5
+
6
+ import cv2
7
+ import numpy as np
8
+ from PIL import Image
9
+
10
+ import insightface
11
+ from insightface.app.common import Face
12
+
13
+ from scripts.reactor_globals import FACE_MODELS_PATH
14
+ from scripts.reactor_helpers import (
15
+ get_image_md5hash,
16
+ get_Device,
17
+ save_face_model,
18
+ load_face_model,
19
+ get_images_from_folder,
20
+ get_images_from_list
21
+ )
22
+ from scripts.console_log_patch import apply_logging_patch
23
+
24
+ from modules.face_restoration import FaceRestoration
25
+ try: # A1111
26
+ from modules import codeformer_model
27
+ except: # SD.Next
28
+ from modules.postprocess import codeformer_model
29
+ from modules.upscaler import UpscalerData
30
+ from modules.shared import state
31
+ from scripts.reactor_logger import logger
32
+ from reactor_modules.reactor_mask import apply_face_mask
33
+
34
+ try:
35
+ from modules.paths_internal import models_path
36
+ except:
37
+ try:
38
+ from modules.paths import models_path
39
+ except:
40
+ models_path = os.path.abspath("models")
41
+
42
+ import warnings
43
+
44
+ np.warnings = warnings
45
+ np.warnings.filterwarnings('ignore')
46
+
47
+
48
+ DEVICE = get_Device()
49
+ if DEVICE == "CUDA":
50
+ PROVIDERS = ["CUDAExecutionProvider"]
51
+ else:
52
+ PROVIDERS = ["CPUExecutionProvider"]
53
+
54
+
55
+ @dataclass
56
+ class EnhancementOptions:
57
+ do_restore_first: bool = True
58
+ scale: int = 1
59
+ upscaler: UpscalerData = None
60
+ upscale_visibility: float = 0.5
61
+ face_restorer: FaceRestoration = None
62
+ restorer_visibility: float = 0.5
63
+ codeformer_weight: float = 0.5
64
+
65
+
66
+ MESSAGED_STOPPED = False
67
+ MESSAGED_SKIPPED = False
68
+
69
+ def reset_messaged():
70
+ global MESSAGED_STOPPED, MESSAGED_SKIPPED
71
+ if not state.interrupted:
72
+ MESSAGED_STOPPED = False
73
+ if not state.skipped:
74
+ MESSAGED_SKIPPED = False
75
+
76
+ def check_process_halt(msgforced: bool = False):
77
+ global MESSAGED_STOPPED, MESSAGED_SKIPPED
78
+ if state.interrupted:
79
+ if not MESSAGED_STOPPED or msgforced:
80
+ logger.status("Stopped by User")
81
+ MESSAGED_STOPPED = True
82
+ return True
83
+ if state.skipped:
84
+ if not MESSAGED_SKIPPED or msgforced:
85
+ logger.status("Skipped by User")
86
+ MESSAGED_SKIPPED = True
87
+ return True
88
+ return False
89
+
90
+
91
+ FS_MODEL = None
92
+ ANALYSIS_MODEL = None
93
+ MASK_MODEL = None
94
+
95
+ CURRENT_FS_MODEL_PATH = None
96
+ CURRENT_MASK_MODEL_PATH = None
97
+
98
+ SOURCE_FACES = None
99
+ SOURCE_IMAGE_HASH = None
100
+ TARGET_FACES = None
101
+ TARGET_IMAGE_HASH = None
102
+ SOURCE_FACES_LIST = []
103
+ SOURCE_IMAGE_LIST_HASH = []
104
+
105
+ def clear_faces_list():
106
+ global SOURCE_FACES_LIST, SOURCE_IMAGE_LIST_HASH
107
+ SOURCE_FACES_LIST = []
108
+ SOURCE_IMAGE_LIST_HASH = []
109
+ logger.status("Source Images Hash has been reset (for Multiple or Folder Source)")
110
+
111
+
112
+ def getAnalysisModel():
113
+ global ANALYSIS_MODEL
114
+ if ANALYSIS_MODEL is None:
115
+ ANALYSIS_MODEL = insightface.app.FaceAnalysis(
116
+ name="buffalo_l", providers=PROVIDERS, root=os.path.join(models_path, "insightface") # note: allowed_modules=['detection', 'genderage']
117
+ )
118
+ return ANALYSIS_MODEL
119
+
120
+
121
+ def getFaceSwapModel(model_path: str):
122
+ global FS_MODEL
123
+ global CURRENT_FS_MODEL_PATH
124
+ if CURRENT_FS_MODEL_PATH is None or CURRENT_FS_MODEL_PATH != model_path:
125
+ CURRENT_FS_MODEL_PATH = model_path
126
+ FS_MODEL = insightface.model_zoo.get_model(model_path, providers=PROVIDERS)
127
+
128
+ return FS_MODEL
129
+
130
+
131
+ def restore_face(image: Image, enhancement_options: EnhancementOptions):
132
+ result_image = image
133
+
134
+ if check_process_halt(msgforced=True):
135
+ return result_image
136
+
137
+ if enhancement_options.face_restorer is not None:
138
+ original_image = result_image.copy()
139
+ logger.status("Restoring the face with %s", enhancement_options.face_restorer.name())
140
+ numpy_image = np.array(result_image)
141
+ if enhancement_options.face_restorer.name() == "CodeFormer":
142
+ numpy_image = codeformer_model.codeformer.restore(
143
+ numpy_image, w=enhancement_options.codeformer_weight
144
+ )
145
+ else:
146
+ numpy_image = enhancement_options.face_restorer.restore(numpy_image)
147
+ restored_image = Image.fromarray(numpy_image)
148
+ result_image = Image.blend(
149
+ original_image, restored_image, enhancement_options.restorer_visibility
150
+ )
151
+
152
+ return result_image
153
+
154
+ def upscale_image(image: Image, enhancement_options: EnhancementOptions):
155
+ result_image = image
156
+
157
+ if check_process_halt(msgforced=True):
158
+ return result_image
159
+
160
+ if enhancement_options.upscaler is not None and enhancement_options.upscaler.name != "None":
161
+ original_image = result_image.copy()
162
+ logger.status(
163
+ "Upscaling with %s scale = %s",
164
+ enhancement_options.upscaler.name,
165
+ enhancement_options.scale,
166
+ )
167
+ result_image = enhancement_options.upscaler.scaler.upscale(
168
+ original_image, enhancement_options.scale, enhancement_options.upscaler.data_path
169
+ )
170
+ if enhancement_options.scale == 1:
171
+ result_image = Image.blend(
172
+ original_image, result_image, enhancement_options.upscale_visibility
173
+ )
174
+
175
+ return result_image
176
+
177
+ def enhance_image(image: Image, enhancement_options: EnhancementOptions):
178
+ result_image = image
179
+
180
+ if check_process_halt(msgforced=True):
181
+ return result_image
182
+
183
+ if enhancement_options.do_restore_first:
184
+
185
+ result_image = restore_face(result_image, enhancement_options)
186
+ result_image = upscale_image(result_image, enhancement_options)
187
+
188
+ else:
189
+
190
+ result_image = upscale_image(result_image, enhancement_options)
191
+ result_image = restore_face(result_image, enhancement_options)
192
+
193
+ return result_image
194
+
195
+ def enhance_image_and_mask(image: Image.Image, enhancement_options: EnhancementOptions,target_img_orig:Image.Image,entire_mask_image:Image.Image)->Image.Image:
196
+ result_image = image
197
+
198
+ if check_process_halt(msgforced=True):
199
+ return result_image
200
+
201
+ if enhancement_options.do_restore_first:
202
+
203
+ result_image = restore_face(result_image, enhancement_options)
204
+ result_image = Image.composite(result_image,target_img_orig,entire_mask_image)
205
+ result_image = upscale_image(result_image, enhancement_options)
206
+
207
+ else:
208
+
209
+ result_image = upscale_image(result_image, enhancement_options)
210
+ entire_mask_image = Image.fromarray(cv2.resize(np.array(entire_mask_image),result_image.size, interpolation=cv2.INTER_AREA)).convert("L")
211
+ result_image = Image.composite(result_image,target_img_orig,entire_mask_image)
212
+ result_image = restore_face(result_image, enhancement_options)
213
+
214
+ return result_image
215
+
216
+
217
+ def get_gender(face, face_index):
218
+ gender = [
219
+ x.sex
220
+ for x in face
221
+ ]
222
+ gender.reverse()
223
+ try:
224
+ face_gender = gender[face_index]
225
+ except:
226
+ logger.error("Gender Detection: No face with index = %s was found", face_index)
227
+ return "None"
228
+ return face_gender
229
+
230
+ def get_face_gender(
231
+ face,
232
+ face_index,
233
+ gender_condition,
234
+ operated: str,
235
+ gender_detected,
236
+ ):
237
+ face_gender = gender_detected
238
+ if face_gender == "None":
239
+ return None, 0
240
+ logger.status("%s Face %s: Detected Gender -%s-", operated, face_index, face_gender)
241
+ if (gender_condition == 1 and face_gender == "F") or (gender_condition == 2 and face_gender == "M"):
242
+ logger.status("OK - Detected Gender matches Condition")
243
+ try:
244
+ return sorted(face, key=lambda x: x.bbox[0])[face_index], 0
245
+ except IndexError:
246
+ return None, 0
247
+ else:
248
+ logger.status("WRONG - Detected Gender doesn't match Condition")
249
+ return sorted(face, key=lambda x: x.bbox[0])[face_index], 1
250
+
251
+ def get_face_age(face, face_index):
252
+ age = [
253
+ x.age
254
+ for x in face
255
+ ]
256
+ age.reverse()
257
+ try:
258
+ face_age = age[face_index]
259
+ except:
260
+ logger.error("Age Detection: No face with index = %s was found", face_index)
261
+ return "None"
262
+ return face_age
263
+
264
+ def half_det_size(det_size):
265
+ logger.status("Trying to halve 'det_size' parameter")
266
+ return (det_size[0] // 2, det_size[1] // 2)
267
+
268
+ def analyze_faces(img_data: np.ndarray, det_size=(640, 640)):
269
+ logger.info("Applied Execution Provider: %s", PROVIDERS[0])
270
+ face_analyser = copy.deepcopy(getAnalysisModel())
271
+ face_analyser.prepare(ctx_id=0, det_size=det_size)
272
+ return face_analyser.get(img_data)
273
+
274
+ def get_face_single(img_data: np.ndarray, face, face_index=0, det_size=(640, 640), gender_source=0, gender_target=0):
275
+
276
+ buffalo_path = os.path.join(models_path, "insightface/models/buffalo_l.zip")
277
+ if os.path.exists(buffalo_path):
278
+ os.remove(buffalo_path)
279
+
280
+ face_age = "None"
281
+ try:
282
+ face_age = get_face_age(face, face_index)
283
+ except:
284
+ logger.error("Cannot detect any Age for Face index = %s", face_index)
285
+
286
+ face_gender = "None"
287
+ try:
288
+ face_gender = get_gender(face, face_index)
289
+ gender_detected = face_gender
290
+ face_gender = "Female" if face_gender == "F" else ("Male" if face_gender == "M" else "None")
291
+ except:
292
+ logger.error("Cannot detect any Gender for Face index = %s", face_index)
293
+
294
+ if gender_source != 0:
295
+ if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
296
+ det_size_half = half_det_size(det_size)
297
+ return get_face_single(img_data, analyze_faces(img_data, det_size_half), face_index, det_size_half, gender_source, gender_target)
298
+ faces, wrong_gender = get_face_gender(face,face_index,gender_source,"Source",gender_detected)
299
+ return faces, wrong_gender, face_age, face_gender
300
+
301
+ if gender_target != 0:
302
+ if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
303
+ det_size_half = half_det_size(det_size)
304
+ return get_face_single(img_data, analyze_faces(img_data, det_size_half), face_index, det_size_half, gender_source, gender_target)
305
+ faces, wrong_gender = get_face_gender(face,face_index,gender_target,"Target",gender_detected)
306
+ return faces, wrong_gender, face_age, face_gender
307
+
308
+ if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
309
+ det_size_half = half_det_size(det_size)
310
+ return get_face_single(img_data, analyze_faces(img_data, det_size_half), face_index, det_size_half, gender_source, gender_target)
311
+
312
+ try:
313
+ return sorted(face, key=lambda x: x.bbox[0])[face_index], 0, face_age, face_gender
314
+ except IndexError:
315
+ return None, 0, face_age, face_gender
316
+
317
+
318
+ def swap_face(
319
+ source_img: Image.Image,
320
+ target_img: Image.Image,
321
+ model: Union[str, None] = None,
322
+ source_faces_index: List[int] = [0],
323
+ faces_index: List[int] = [0],
324
+ enhancement_options: Union[EnhancementOptions, None] = None,
325
+ gender_source: int = 0,
326
+ gender_target: int = 0,
327
+ source_hash_check: bool = True,
328
+ target_hash_check: bool = False,
329
+ device: str = "CPU",
330
+ mask_face: bool = False,
331
+ select_source: int = 0,
332
+ face_model: str = "None",
333
+ source_folder: str = "",
334
+ source_imgs: Union[List, None] = None,
335
+ ):
336
+ global SOURCE_FACES, SOURCE_IMAGE_HASH, TARGET_FACES, TARGET_IMAGE_HASH, PROVIDERS, SOURCE_FACES_LIST, SOURCE_IMAGE_LIST_HASH
337
+
338
+ result_image = target_img
339
+
340
+ PROVIDERS = ["CUDAExecutionProvider"] if device == "CUDA" else ["CPUExecutionProvider"]
341
+
342
+ if check_process_halt():
343
+ return result_image, [], 0
344
+
345
+ if model is not None:
346
+
347
+ if isinstance(source_img, str): # source_img is a base64 string
348
+ import base64, io
349
+ if 'base64,' in source_img: # check if the base64 string has a data URL scheme
350
+ # split the base64 string to get the actual base64 encoded image data
351
+ base64_data = source_img.split('base64,')[-1]
352
+ # decode base64 string to bytes
353
+ img_bytes = base64.b64decode(base64_data)
354
+ else:
355
+ # if no data URL scheme, just decode
356
+ img_bytes = base64.b64decode(source_img)
357
+
358
+ source_img = Image.open(io.BytesIO(img_bytes))
359
+
360
+ target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
361
+
362
+ target_img_orig = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
363
+ entire_mask_image = np.zeros_like(np.array(target_img))
364
+
365
+ output: List = []
366
+ output_info: str = ""
367
+ swapped = 0
368
+
369
+ # *****************
370
+ # SWAP from FOLDER or MULTIPLE images:
371
+
372
+ if (select_source == 0 and source_imgs is not None) or (select_source == 2 and (source_folder is not None and source_folder != "")):
373
+
374
+ result = []
375
+
376
+ source_images = get_images_from_folder(source_folder) if select_source == 2 else get_images_from_list(source_imgs)
377
+
378
+ if len(source_images) > 0:
379
+ source_img_ff = []
380
+ source_faces_ff = []
381
+ for i, source_image in enumerate(source_images):
382
+
383
+ source_image = cv2.cvtColor(np.array(source_image), cv2.COLOR_RGB2BGR)
384
+ source_img_ff.append(source_image)
385
+
386
+ if source_hash_check:
387
+
388
+ source_image_md5hash = get_image_md5hash(source_image)
389
+
390
+ if len(SOURCE_IMAGE_LIST_HASH) == 0:
391
+ SOURCE_IMAGE_LIST_HASH = [source_image_md5hash]
392
+ source_image_same = False
393
+ elif len(SOURCE_IMAGE_LIST_HASH) == i:
394
+ SOURCE_IMAGE_LIST_HASH.append(source_image_md5hash)
395
+ source_image_same = False
396
+ else:
397
+ source_image_same = True if SOURCE_IMAGE_LIST_HASH[i] == source_image_md5hash else False
398
+ if not source_image_same:
399
+ SOURCE_IMAGE_LIST_HASH[i] = source_image_md5hash
400
+
401
+ logger.info("(Image %s) Source Image MD5 Hash = %s", i, SOURCE_IMAGE_LIST_HASH[i])
402
+ logger.info("(Image %s) Source Image the Same? %s", i, source_image_same)
403
+
404
+ if len(SOURCE_FACES_LIST) == 0:
405
+ logger.status(f"Analyzing Source Image {i}...")
406
+ source_faces = analyze_faces(source_image)
407
+ SOURCE_FACES_LIST = [source_faces]
408
+ elif len(SOURCE_FACES_LIST) == i and not source_image_same:
409
+ logger.status(f"Analyzing Source Image {i}...")
410
+ source_faces = analyze_faces(source_image)
411
+ SOURCE_FACES_LIST.append(source_faces)
412
+ elif len(SOURCE_FACES_LIST) != i and not source_image_same:
413
+ logger.status(f"Analyzing Source Image {i}...")
414
+ source_faces = analyze_faces(source_image)
415
+ SOURCE_FACES_LIST[i] = source_faces
416
+ elif source_image_same:
417
+ logger.status("(Image %s) Using Hashed Source Face(s) Model...", i)
418
+ source_faces = SOURCE_FACES_LIST[i]
419
+
420
+ else:
421
+ logger.status(f"Analyzing Source Image {i}...")
422
+ source_faces = analyze_faces(source_image)
423
+
424
+ if source_faces is not None:
425
+ source_faces_ff.append(source_faces)
426
+
427
+ if len(source_faces_ff) > 0:
428
+
429
+ if target_hash_check:
430
+
431
+ target_image_md5hash = get_image_md5hash(target_img)
432
+
433
+ if TARGET_IMAGE_HASH is None:
434
+ TARGET_IMAGE_HASH = target_image_md5hash
435
+ target_image_same = False
436
+ else:
437
+ target_image_same = True if TARGET_IMAGE_HASH == target_image_md5hash else False
438
+ if not target_image_same:
439
+ TARGET_IMAGE_HASH = target_image_md5hash
440
+
441
+ logger.info("Target Image MD5 Hash = %s", TARGET_IMAGE_HASH)
442
+ logger.info("Target Image the Same? %s", target_image_same)
443
+
444
+ if TARGET_FACES is None or not target_image_same:
445
+ logger.status("Analyzing Target Image...")
446
+ target_faces = analyze_faces(target_img)
447
+ TARGET_FACES = target_faces
448
+ elif target_image_same:
449
+ logger.status("Using Hashed Target Face(s) Model...")
450
+ target_faces = TARGET_FACES
451
+
452
+ else:
453
+ logger.status("Analyzing Target Image...")
454
+ target_faces = analyze_faces(target_img)
455
+
456
+ for i,source_faces in enumerate(source_faces_ff):
457
+
458
+ logger.status("(Image %s) Detecting Source Face, Index = %s", i, source_faces_index[0])
459
+ 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)
460
+
461
+ if source_age != "None" or source_gender != "None":
462
+ logger.status("(Image %s) Detected: -%s- y.o. %s", i, source_age, source_gender)
463
+
464
+ if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index):
465
+ logger.status("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.")
466
+
467
+ elif source_face is not None:
468
+
469
+ 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)
470
+
471
+ result.append(result_image)
472
+
473
+ result = [result_image] if len(result) == 0 else result
474
+
475
+ return result, output, swapped
476
+
477
+ # END
478
+ # *****************
479
+
480
+ # ***********************
481
+ # SWAP from IMG or MODEL:
482
+
483
+ else:
484
+
485
+ if select_source == 0 and source_img is not None:
486
+
487
+ source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
488
+
489
+ if source_hash_check:
490
+
491
+ source_image_md5hash = get_image_md5hash(source_img)
492
+
493
+ if SOURCE_IMAGE_HASH is None:
494
+ SOURCE_IMAGE_HASH = source_image_md5hash
495
+ source_image_same = False
496
+ else:
497
+ source_image_same = True if SOURCE_IMAGE_HASH == source_image_md5hash else False
498
+ if not source_image_same:
499
+ SOURCE_IMAGE_HASH = source_image_md5hash
500
+
501
+ logger.info("Source Image MD5 Hash = %s", SOURCE_IMAGE_HASH)
502
+ logger.info("Source Image the Same? %s", source_image_same)
503
+
504
+ if SOURCE_FACES is None or not source_image_same:
505
+ logger.status("Analyzing Source Image...")
506
+ source_faces = analyze_faces(source_img)
507
+ SOURCE_FACES = source_faces
508
+ elif source_image_same:
509
+ logger.status("Using Hashed Source Face(s) Model...")
510
+ source_faces = SOURCE_FACES
511
+
512
+ else:
513
+ logger.status("Analyzing Source Image...")
514
+ source_faces = analyze_faces(source_img)
515
+
516
+ elif select_source == 1 and (face_model is not None and face_model != "None"):
517
+ source_face_model = [load_face_model(face_model)]
518
+ if source_face_model is not None:
519
+ source_faces_index = [0]
520
+ source_faces = source_face_model
521
+ logger.status("Using Loaded Source Face Model...")
522
+ else:
523
+ logger.error(f"Cannot load Face Model File: {face_model}.safetensors")
524
+
525
+ else:
526
+ logger.error("Cannot detect any Source")
527
+ return result_image, [], 0
528
+
529
+ if source_faces is not None:
530
+
531
+ if target_hash_check:
532
+
533
+ target_image_md5hash = get_image_md5hash(target_img)
534
+
535
+ if TARGET_IMAGE_HASH is None:
536
+ TARGET_IMAGE_HASH = target_image_md5hash
537
+ target_image_same = False
538
+ else:
539
+ target_image_same = True if TARGET_IMAGE_HASH == target_image_md5hash else False
540
+ if not target_image_same:
541
+ TARGET_IMAGE_HASH = target_image_md5hash
542
+
543
+ logger.info("Target Image MD5 Hash = %s", TARGET_IMAGE_HASH)
544
+ logger.info("Target Image the Same? %s", target_image_same)
545
+
546
+ if TARGET_FACES is None or not target_image_same:
547
+ logger.status("Analyzing Target Image...")
548
+ target_faces = analyze_faces(target_img)
549
+ TARGET_FACES = target_faces
550
+ elif target_image_same:
551
+ logger.status("Using Hashed Target Face(s) Model...")
552
+ target_faces = TARGET_FACES
553
+
554
+ else:
555
+ logger.status("Analyzing Target Image...")
556
+ target_faces = analyze_faces(target_img)
557
+
558
+ logger.status("Detecting Source Face, Index = %s", source_faces_index[0])
559
+ if select_source == 0 and source_img is not None:
560
+ 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)
561
+ else:
562
+ source_face = sorted(source_faces, key=lambda x: x.bbox[0])[source_faces_index[0]]
563
+ wrong_gender = 0
564
+ source_age = source_face["age"]
565
+ source_gender = "Female" if source_face["gender"] == 0 else "Male"
566
+
567
+ if source_age != "None" or source_gender != "None":
568
+ logger.status("Detected: -%s- y.o. %s", source_age, source_gender)
569
+
570
+ output_info = f"SourceFaceIndex={source_faces_index[0]};Age={source_age};Gender={source_gender}\n"
571
+ output.append(output_info)
572
+
573
+ if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index):
574
+ logger.status("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.")
575
+
576
+ elif source_face is not None:
577
+
578
+ 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)
579
+
580
+ else:
581
+ logger.status("No source face(s) in the provided Index")
582
+ else:
583
+ logger.status("No source face(s) found")
584
+
585
+ return result_image, output, swapped
586
+
587
+ # END
588
+ # **********************
589
+
590
+ return result_image, [], 0
591
+
592
+ def build_face_model(image: Image.Image, name: str):
593
+ if image is None:
594
+ error_msg = "Please load an Image"
595
+ logger.error(error_msg)
596
+ return error_msg
597
+ if name is None:
598
+ error_msg = "Please filled out the 'Face Model Name' field"
599
+ logger.error(error_msg)
600
+ return error_msg
601
+ apply_logging_patch(1)
602
+ image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
603
+ logger.status("Building Face Model...")
604
+ face_model = analyze_faces(image)
605
+ if face_model is not None and len(face_model) > 0:
606
+ face_model_path = os.path.join(FACE_MODELS_PATH, name + ".safetensors")
607
+ save_face_model(face_model[0],face_model_path)
608
+ logger.status("--Done!--")
609
+ done_msg = f"Face model has been saved to '{face_model_path}'"
610
+ logger.status(done_msg)
611
+ return done_msg
612
+ else:
613
+ no_face_msg = "No face found, please try another image"
614
+ logger.error(no_face_msg)
615
+ return no_face_msg
616
+
617
+
618
+ def operate(
619
+ source_img,
620
+ target_img,
621
+ target_img_orig,
622
+ model,
623
+ source_faces_index,
624
+ faces_index,
625
+ source_faces,
626
+ target_faces,
627
+ gender_source,
628
+ gender_target,
629
+ source_face,
630
+ wrong_gender,
631
+ source_age,
632
+ source_gender,
633
+ output,
634
+ swapped,
635
+ mask_face,
636
+ entire_mask_image,
637
+ enhancement_options,
638
+ ):
639
+ result = target_img
640
+ face_swapper = getFaceSwapModel(model)
641
+
642
+ source_face_idx = 0
643
+
644
+ for face_num in faces_index:
645
+ if check_process_halt():
646
+ return result_image, [], 0
647
+ if len(source_faces_index) > 1 and source_face_idx > 0:
648
+ logger.status("Detecting Source Face, Index = %s", source_faces_index[source_face_idx])
649
+ 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)
650
+ if source_age != "None" or source_gender != "None":
651
+ logger.status("Detected: -%s- y.o. %s", source_age, source_gender)
652
+
653
+ output_info = f"SourceFaceIndex={source_faces_index[source_face_idx]};Age={source_age};Gender={source_gender}\n"
654
+ output.append(output_info)
655
+
656
+ source_face_idx += 1
657
+
658
+ if source_face is not None and wrong_gender == 0:
659
+ logger.status("Detecting Target Face, Index = %s", face_num)
660
+ target_face, wrong_gender, target_age, target_gender = get_face_single(target_img, target_faces, face_index=face_num, gender_target=gender_target)
661
+ if target_age != "None" or target_gender != "None":
662
+ logger.status("Detected: -%s- y.o. %s", target_age, target_gender)
663
+
664
+ output_info = f"TargetFaceIndex={face_num};Age={target_age};Gender={target_gender}\n"
665
+ output.append(output_info)
666
+
667
+ if target_face is not None and wrong_gender == 0:
668
+ logger.status("Swapping Source into Target")
669
+ swapped_image = face_swapper.get(result, target_face, source_face)
670
+
671
+ if mask_face:
672
+ result = apply_face_mask(swapped_image=swapped_image,target_image=result,target_face=target_face,entire_mask_image=entire_mask_image)
673
+ else:
674
+ result = swapped_image
675
+ swapped += 1
676
+
677
+ elif wrong_gender == 1:
678
+ wrong_gender = 0
679
+
680
+ if source_face_idx == len(source_faces_index):
681
+ result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
682
+
683
+ if enhancement_options is not None and len(source_faces_index) > 1:
684
+ result_image = enhance_image(result_image, enhancement_options)
685
+
686
+ return result_image, output, swapped
687
+
688
+ else:
689
+ logger.status(f"No target face found for {face_num}")
690
+
691
+ elif wrong_gender == 1:
692
+ wrong_gender = 0
693
+
694
+ if source_face_idx == len(source_faces_index):
695
+ result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
696
+
697
+ if enhancement_options is not None and len(source_faces_index) > 1:
698
+ result_image = enhance_image(result_image, enhancement_options)
699
+
700
+ return result_image, output, swapped
701
+
702
+ else:
703
+ logger.status(f"No source face found for face number {source_face_idx}.")
704
+
705
+ result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
706
+
707
+ if enhancement_options is not None and swapped > 0:
708
+ if mask_face and entire_mask_image is not None:
709
+ result_image = enhance_image_and_mask(result_image, enhancement_options,Image.fromarray(target_img_orig),Image.fromarray(entire_mask_image).convert("L"))
710
+ else:
711
+ result_image = enhance_image(result_image, enhancement_options)
712
+ elif mask_face and entire_mask_image is not None and swapped > 0:
713
+ result_image = Image.composite(result_image,Image.fromarray(target_img_orig),Image.fromarray(entire_mask_image).convert("L"))
714
+
715
+ return result_image, output, swapped
sd-webui-reactor-main/sd-webui-reactor-main/scripts/reactor_version.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ app_title = "ReActor"
2
+ version_flag = "v0.6.0-a1"
3
+
4
+ from scripts.reactor_logger import logger, get_Run, set_Run
5
+
6
+ is_run = get_Run()
7
+
8
+ if not is_run:
9
+ logger.status(f"Running {version_flag}")
10
+ set_Run(True)