Kizi-Art commited on
Commit
3b340e8
1 Parent(s): 4dc9a61

Upload folder using huggingface_hub

Browse files
Files changed (29) hide show
  1. extensions-builtin/sd-webui-reactor/.github/ISSUE_TEMPLATE/bug_report.yml +58 -0
  2. extensions-builtin/sd-webui-reactor/.github/ISSUE_TEMPLATE/config.yml +5 -0
  3. extensions-builtin/sd-webui-reactor/.github/ISSUE_TEMPLATE/feature_request.yml +16 -0
  4. extensions-builtin/sd-webui-reactor/.gitignore +9 -0
  5. extensions-builtin/sd-webui-reactor/API.md +71 -0
  6. extensions-builtin/sd-webui-reactor/LICENSE +661 -0
  7. extensions-builtin/sd-webui-reactor/README.md +269 -0
  8. extensions-builtin/sd-webui-reactor/README_RU.md +277 -0
  9. extensions-builtin/sd-webui-reactor/example/IamSFW.jpg +3 -0
  10. extensions-builtin/sd-webui-reactor/example/ReActor_logo_red.png +3 -0
  11. extensions-builtin/sd-webui-reactor/example/api_example.py +95 -0
  12. extensions-builtin/sd-webui-reactor/example/api_external.curl +0 -0
  13. extensions-builtin/sd-webui-reactor/example/api_external.json +0 -0
  14. extensions-builtin/sd-webui-reactor/example/demo_crop.jpg +3 -0
  15. extensions-builtin/sd-webui-reactor/example/example.jpg +3 -0
  16. extensions-builtin/sd-webui-reactor/example/insightface-0.7.3-cp310-cp310-win_amd64.whl +0 -0
  17. extensions-builtin/sd-webui-reactor/example/multiple-faces.png +3 -0
  18. extensions-builtin/sd-webui-reactor/example/pp-order.png +3 -0
  19. extensions-builtin/sd-webui-reactor/example/roop-off.png +3 -0
  20. extensions-builtin/sd-webui-reactor/install.py +76 -0
  21. extensions-builtin/sd-webui-reactor/requirements.txt +4 -0
  22. extensions-builtin/sd-webui-reactor/scripts/console_log_patch.py +120 -0
  23. extensions-builtin/sd-webui-reactor/scripts/reactor_api.py +111 -0
  24. extensions-builtin/sd-webui-reactor/scripts/reactor_faceswap.py +384 -0
  25. extensions-builtin/sd-webui-reactor/scripts/reactor_globals.py +1 -0
  26. extensions-builtin/sd-webui-reactor/scripts/reactor_helpers.py +102 -0
  27. extensions-builtin/sd-webui-reactor/scripts/reactor_logger.py +54 -0
  28. extensions-builtin/sd-webui-reactor/scripts/reactor_swapper.py +358 -0
  29. extensions-builtin/sd-webui-reactor/scripts/reactor_version.py +10 -0
extensions-builtin/sd-webui-reactor/.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.
extensions-builtin/sd-webui-reactor/.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.
extensions-builtin/sd-webui-reactor/.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)
extensions-builtin/sd-webui-reactor/.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.pyc
5
+
6
+ .vscode/
7
+
8
+ example
9
+ toDo.txt
extensions-builtin/sd-webui-reactor/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
extensions-builtin/sd-webui-reactor/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/>.
extensions-builtin/sd-webui-reactor/README.md ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img src="example/ReActor_logo_red.png" alt="logo" width="180px"/>
4
+
5
+ ![Version](https://img.shields.io/badge/version-0.4.2_beta2-green?style=for-the-badge&labelColor=darkgreen)<hr>
6
+ [![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)
7
+ ![Last commit](https://img.shields.io/github/last-commit/Gourieff/sd-webui-reactor/main?cacheSeconds=0)
8
+ [![Opened issues](https://img.shields.io/github/issues/Gourieff/sd-webui-reactor?color=red)](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
9
+ [![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)
10
+ ![License](https://img.shields.io/github/license/Gourieff/sd-webui-reactor)
11
+
12
+ English | [Русский](/README_RU.md)
13
+
14
+ # ReActor for Stable Diffusion
15
+
16
+ </div>
17
+
18
+ ### The Fast and Simple FaceSwap Extension with a lot of improvements and without NSFW filter (uncensored, use it on your own [responsibility](#disclaimer))
19
+
20
+ > Ex "Roop-GE" (GE - Gourieff Edition, aka "NSFW-Roop"), the extension was renamed with the version 0.3.0<br>
21
+ > Repository old link: `https://github.com/Gourieff/sd-webui-roop-nsfw`
22
+
23
+ ---
24
+ <div align="center">
25
+ <b>
26
+ <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>
27
+ </b>
28
+ </div>
29
+
30
+ ---
31
+
32
+ <table>
33
+ <tr>
34
+ <td width="144px">
35
+ <a href="https://boosty.to/artgourieff" target="_blank">
36
+ <img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/>
37
+ <br>
38
+ <sup>
39
+ Support This Project
40
+ </sup>
41
+ </a>
42
+ </td>
43
+ <td>
44
+ ReActor is an extension for Stable Diffusion WebUI that allows a very easy and accurate face-replacement (face swap) in images. Based on <a href="https://github.com/Gourieff/ReActor-UI" target="_blank">ReActor-UI</a>.
45
+ </td>
46
+ </tr>
47
+ </table>
48
+
49
+ <img src="example/demo_crop.jpg" alt="example"/>
50
+
51
+ ## Installation
52
+
53
+ [Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
54
+
55
+ <a name="a1111">If you use [AUTOMATIC1111 web-ui](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
56
+
57
+ 1. (For Windows Users):
58
+ - Install **Visual Studio 2022** (Community version, for example - you need this step to build some of dependencies):
59
+ https://visualstudio.microsoft.com/downloads/
60
+ - 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":
61
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/
62
+ - OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. VIII)](#insightfacebuild)
63
+ 2. In web-ui, 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"
64
+ 3. Please, wait for several minutes until the installation process will be finished
65
+ 4. Check the last message in your SD-WebUI Console:
66
+ * 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 (*if you have any other Roop-based extension enabled - disable it, otherwise this extension won't work*), click "Apply and restart UI"
67
+ * If you see the message "Done!", just go to the "Installed" tab (*if you have any other Roop-based extension enabled - disable it, otherwise this extension won't work*), click "Apply and restart UI" - or you can just simply reload the UI
68
+ 5. Enjoy!
69
+
70
+ <a name="sdnext">If you use [SD.Next](https://github.com/vladmandic/automatic):
71
+
72
+ 1. Close (stop) your SD WebUI Server if it's running
73
+ 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)
74
+ 3. Go to (Windows)`automatic\venv\Scripts` or (MacOS/Linux)`automatic/venv/bin`, run Terminal or Console (cmd) for that folder and type `activate`
75
+ 4. Run `pip install insightface==0.7.3`
76
+ 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"
77
+ 6. Please, wait for several minutes until the installation process will be finished
78
+ 7. Check the last message in your SD.Next Console:
79
+ * 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 (*if you have any other Roop-based extension enabled - disable it, otherwise this extension won't work*), click "Restart the UI"
80
+ 8. Stop SD.Next, 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
81
+ 9. Run your SD.Next WebUI and enjoy!
82
+
83
+ <a name="colab">If you use [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
84
+
85
+ 1. In active WebUI, 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"
86
+ 2. Please, wait for several minutes until the installation process will be finished
87
+ 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" (*if you have any other Roop-based extension enabled - disable it before restart, otherwise this extension won't work*)
88
+ 4. Enjoy!
89
+
90
+ ## Features
91
+
92
+ - Very fast and accurate **face replacement (face swap)** in images
93
+ - **Multiple faces support**
94
+ - **Gender detection**
95
+ - Ability to **save original images** (made before swapping)
96
+ - **Face restoration** of a swapped face
97
+ - **Upscaling** of a resulting image
98
+ - Ability to set the **Postprocessing order**
99
+ - **100% compatibility** with different **SD WebUIs**: Automatic1111, SD.Next, Cagliostro Colab UI
100
+ - **Fast performance** even with CPU, ReActor for SD WebUI is absolutely not picky about how powerful your GPU is
101
+ - **[API](/API.md) support**: both SD WebUI built-in and external (via POST/GET requests)
102
+ - **ComfyUI [support](https://github.com/Gourieff/comfyui-reactor-node)**
103
+ - **Mac M1/M2 [support](https://github.com/Gourieff/sd-webui-reactor/issues/42)**
104
+ - Console **log level control**
105
+ - **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)
106
+
107
+ ## Usage
108
+
109
+ > Using this software you are agree with [disclaimer](#disclaimer)
110
+
111
+ 1. Under "ReActor" drop-down menu, import an image containing a face;
112
+ 2. Turn on the "Enable" checkbox;
113
+ 3. That's it, now the generated result will have the face you selected.
114
+
115
+ <img src="example/example.jpg" alt="example" width="808"/>
116
+
117
+
118
+ ### The result face is blurry
119
+ Use the "Restore Face" option. You can also try the "Upscaler" option or for more finer control, use an upscaler from the "Extras" tab.
120
+ You can also set the postproduction order (from 0.1.0 version):
121
+ <img src="example/pp-order.png" alt="example"/>
122
+
123
+ *The old logic was the opposite (Upscale -> then Restore), resulting in worse face quality (and big texture differences) after upscaling.*
124
+
125
+ ### There are multiple faces in result
126
+ 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.
127
+ <img src="example/multiple-faces.png" alt="example"/>
128
+
129
+ ### ~~The result is totally black~~
130
+ ~~This means NSFW filter detected that your image is NSFW.~~
131
+
132
+ <img src="example/IamSFW.jpg" alt="IamSFW" width="50%"/>
133
+
134
+ ### Img2Img
135
+
136
+ 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.
137
+
138
+ 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".
139
+
140
+ ## API
141
+
142
+ You can use ReActor with the built-in Webui API or via an external API.
143
+
144
+ Please follow **[this](/API.md)** page for the detailed instruction.
145
+
146
+ ## Troubleshooting
147
+
148
+ ### **I. "You should at least have one model in models directory"**
149
+
150
+ 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.
151
+
152
+ ### **II. Any problems with installing Insightface or other dependencies**
153
+
154
+ (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
155
+
156
+ (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:
157
+ 1. Close (stop) your SD WebUI Server and start it again
158
+
159
+ (for Any OS Users) If the problem still there, then do the following:
160
+ 1. Close (stop) your SD WebUI Server if it's running
161
+ 2. Go to (Windows)`venv\Lib\site-packages` folder or (MacOS/Linux)`venv/lib/python3.10/site-packages`
162
+ 3. If you see any folders with names start from `~` (e.g. "~rotobuf") - delete them
163
+ 4. Go to (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin`
164
+ 5. Run Terminal or Console (cmd) for that folder and type `activate`
165
+ 6. Update your pip at first: `pip install -U pip`
166
+ 7. Then one-by-one:
167
+ - `pip install insightface==0.7.3`
168
+ - `pip install onnx==1.14.0`
169
+ - `pip install onnxruntime==1.15.0`
170
+ - `pip install opencv-python==4.7.0.72`
171
+ - `pip install tqdm`
172
+ 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.
173
+
174
+ ### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
175
+
176
+ First of all - you need to disable any other Roop-based extensions:
177
+ - Go to 'Extensions -> Installed' tab and uncheck any Roop-based extensions except this one
178
+ <img src="example/roop-off.png" alt="uncompatible-with-other-roop"/>
179
+ - Click 'Apply and restart UI'
180
+
181
+ Alternative solutions:
182
+ - https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243
183
+ - https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (can be actual, if you use Vladmandic SD.Next)
184
+
185
+ ### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
186
+
187
+ You need to disable the "SD-CN-Animation" extension (or perhaps some another that causes the conflict)
188
+
189
+ ### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed" OR "AttributeError: 'NoneType' object has no attribute 'get'"**
190
+
191
+ This error may occur if there's smth wrong with the model file `inswapper_128.onnx`
192
+
193
+ Try to download it manually from [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)
194
+ and put it to the `stable-diffusion-webui\models\insightface` replacing existing one
195
+
196
+ ### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled"**
197
+
198
+ 1. Close (stop) your SD WebUI Server if it's running
199
+ 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
200
+ 3. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
201
+ 4. Then:
202
+ - `python -m pip install -U pip`
203
+ - `pip uninstall -y onnx onnxruntime onnxruntime-gpu onnxruntime-silicon`
204
+ - `pip install onnx==1.14.0 onnxruntime==1.15.0`
205
+
206
+ If it didn't help - it seems that you have another extension reinstalling `onnxruntime` when SD WebUI checks requirements. Please see your extensions list. If you find there "WD14 tagger" - try to disable it and then follow the steps above once again. This extension causes reinstalling of `onnxruntime` to `onnxruntime-gpu` every time SD WebUI runs.
207
+
208
+ ### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
209
+
210
+ 1. Close (stop) your SD WebUI Server if it's running
211
+ 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
212
+ 3. Go to the "google" folder (inside the "site-packages") and delete any folders there with names start from "~"
213
+ 4. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
214
+ 5. Then:
215
+ - `python -m pip install -U pip`
216
+ - `pip uninstall protobuf`
217
+ - `pip install protobuf==3.20.3`
218
+
219
+ If this method doesn't help - there is some other extension that has a higher version of protobuf dependence and SD WebUI installs it on a startup requirements check
220
+
221
+ <a name="insightfacebuild">
222
+
223
+ ### **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:**
224
+
225
+ 1. Close (stop) your SD WebUI Server if it's running
226
+ 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)
227
+ 3. From stable-diffusion-webui (or SD.Next) root folder run CMD and `.\venv\Scripts\activate`
228
+ 4. Then update your PIP: `python -m pip install -U pip`
229
+ 5. Then install Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`
230
+ 6. Enjoy!
231
+
232
+ ### **IX. 07-August-23 Update problem**
233
+
234
+ 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`
235
+
236
+ Please do the next:
237
+
238
+ Inside the folder `extensions\sd-webui-reactor` run Terminal or Console (cmd) and then:
239
+ - `git reset f48bdf1 --hard`
240
+ - `git pull`
241
+
242
+ OR
243
+
244
+ 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`
245
+
246
+
247
+ ## Updating
248
+
249
+ A good and quick way to check for Extensions updates: https://github.com/Gourieff/sd-webui-extensions-updater
250
+
251
+ ## ComfyUI
252
+
253
+ You can use ReActor with ComfyUI.<br>
254
+ For the installation instruction follow the [ReActor Node repo](https://github.com/Gourieff/comfyui-reactor-node)
255
+
256
+ ## Disclaimer
257
+
258
+ 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.
259
+
260
+ 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.
261
+
262
+ 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.**
263
+
264
+ By using this extension you are agree not to create any content that:
265
+ - violates any laws;
266
+ - causes any harm to a person or persons;
267
+ - propogates (spreads) any information (both public or personal) or images (both public or personal) which could be meant for harm;
268
+ - spreads misinformation;
269
+ - targets vulnerable groups of people.
extensions-builtin/sd-webui-reactor/README_RU.md ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img src="example/ReActor_logo_red.png" alt="logo" width="180px"/>
4
+
5
+ ![Version](https://img.shields.io/badge/версия-0.4.2_beta2-green?style=for-the-badge&labelColor=darkgreen)<hr>
6
+ [![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)
7
+ ![Last commit](https://img.shields.io/github/last-commit/Gourieff/sd-webui-reactor/main?cacheSeconds=0)
8
+ [![Opened issues](https://img.shields.io/github/issues/Gourieff/sd-webui-reactor?color=red)](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
9
+ [![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)
10
+ ![License](https://img.shields.io/github/license/Gourieff/sd-webui-reactor)
11
+
12
+ [English](/README.md) | Русский
13
+
14
+ # ReActor для Stable Diffusion
15
+ ### Расширение для быстрой и простой замены лиц на любых изображениях. Без фильтра цензуры, 18+, используйте под вашу собственную [ответственность](#disclaimer)
16
+
17
+ </div>
18
+
19
+ ---
20
+ <div align="center">
21
+ <b>
22
+ <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>
23
+ </b>
24
+ </div>
25
+
26
+ ---
27
+
28
+ <table>
29
+ <tr>
30
+ <td width="144px">
31
+ <a href="https://boosty.to/artgourieff" target="_blank">
32
+ <img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/>
33
+ <br>
34
+ <sup>
35
+ Поддержать проект
36
+ </sup>
37
+ </a>
38
+ </td>
39
+ <td>
40
+ ReActor это расширение для Stable Diffusion WebUI, которое позволяет делать простую и точную замену лиц на изображениях. Сделано на основе <a href="https://github.com/Gourieff/ReActor-UI" target="_blank">ReActor-UI</a>.
41
+ </td>
42
+ </tr>
43
+ </table>
44
+
45
+ <img src="example/demo_crop.jpg" alt="example"/>
46
+
47
+ <a name="installation">
48
+
49
+ ## Установка
50
+
51
+ [Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
52
+
53
+ <a name="a1111">Если вы используете [AUTOMATIC1111 Web-UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
54
+
55
+ 1. (Для пользователей Windows):
56
+ - Установите **Visual Studio 2022** (Например, версию Community - этот шаг нужен для правильной компиляции библиотеки Insightface):
57
+ https://visualstudio.microsoft.com/downloads/
58
+ - ИЛИ только **VS C++ Build Tools** (если вам не нужен весь пакет Visual Studio), выберите "Desktop Development with C++" в разделе "Workloads -> Desktop & Mobile":
59
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/
60
+ - ИЛИ если же вы не хотите устанавливать что-либо из вышеуказанного - выполните [следующие шаги (пункт VIII)](#insightfacebuild)
61
+ 2. Внутри SD Web-UI перейдите во вкладку "Extensions" и вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
62
+ 3. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится
63
+ 4. Проверьте последнее сообщение в консоли SD-WebUI:
64
+ * Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) и запустите его заново - ИЛИ же перейдите во вкладку "Installed" (*если у вас имееются какие-либо другие расширение, основанные на Roop или клонах ReActor - отключите их, иначе данное расширение может не работать*), нажмите "Apply and restart UI"
65
+ * Если вы видите "Done!", перейдите во вкладку "Installed" (*если у вас имееются какие-либо другие расширение, основанные на Roop или клонах ReActor - отключите их, иначе данное расширение может не работать*), нажмите "Apply and restart UI" - или же просто перезагрузите UI, нажав на "Reload UI"
66
+ 5. Готово!
67
+
68
+ <a name="sdnext">Если вы используете [SD.Next](https://github.com/vladmandic/automatic):
69
+
70
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
71
+ 2. (Для пользователей Windows) Смотрите [Шаг 1](#a1111) для Automatic1111 (если же вы следовали [данным шагам (пункт VIII)](#insightfacebuild) вместо этого - переходите к Шагу 5)
72
+ 3. Перейдите в (Windows)`automatic\venv\Scripts` или (MacOS/Linux)`automatic/venv/bin`, запустите Терминал или Консоль (cmd) для данной папки и выполните `activate`
73
+ 4. Выполните `pip install insightface==0.7.3`
74
+ 5. Запустите SD.Next, перейдите во вкладку "Extensions", вставьте эту ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
75
+ 6. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится
76
+ 7. Проверьте последнее сообщение в консоли SD.Next:
77
+ * Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) и запустите его заново - ИЛИ же перейдите во вкладку "Installed" (*если у вас имееются какие-либо другие расширение, основанные на Roop или клонах ReActor - отключите их, иначе данное расширение может не работать*), нажмите "Restart the UI"
78
+ 8. Остановите Сервер SD.Next, перейдите в директорию `automatic\extensions\sd-webui-reactor` - если вы видите там папку `models\insightface` с файлом `inswapper_128.onnx` внутри, переместите его в папку `automatic\models\insightface`
79
+ 9. Готово, можете запустить SD.Next WebUI!
80
+
81
+ <a name="colab">Если вы используете [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
82
+
83
+ 1. В активном WebUI, перейдите во вкладку "Extensions", вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
84
+ 2. Пожалуйста, подождите некоторое время, пока процесс установки полностью не завершится
85
+ 3. Когда вы увидите сообщение "--- PLEASE, RESTART the Server! ---" (в секции "Start UI" вашего ноутбука "Start Cagliostro Colab UI") - перейдите во вкладку "Installed" и нажмите "Apply and restart UI" (*если у вас имееются какие-либо другие расширение, основанные на Roop или клонах ReActor - отключите их, иначе данное расширение может не работать*)
86
+ 4. Готово!
87
+
88
+ <a name="features">
89
+
90
+ ## Возможности
91
+
92
+ - Быстрая и точна **замена лиц (faceswap)** на изображении
93
+ - **Поддержка нескольких лиц**
94
+ - **Определение пола**
95
+ - Функция **сохранения оригинального изображения** (сгенерированного до замены лица)
96
+ - **Восстановление лица** после замены
97
+ - **Увеличение размера** полученного изображения
98
+ - Возможность задать **порядок постобработки**
99
+ - **100% совместимость** с разными **SD WebUI**: Automatic1111, SD.Next, Cagliostro Colab UI
100
+ - **Отличная производительность** даже с использованием ЦПУ, ReActor для SD WebUI абсолютно не требователен к мощности вашей видеокарты
101
+ - **Поддержка [API](/API.md)**: как встроенного в SD WebUI, так и внешнего (через POST/GET запросы)
102
+ - **[Поддержка](https://github.com/Gourieff/comfyui-reactor-node) ComfyUI**
103
+ - **[Поддержка](https://github.com/Gourieff/sd-webui-reactor/issues/42) компьютеров Mac M1/M2**
104
+ - **Регулировка уровня логов** консоли
105
+ - **Без NSFW фильтров** (данное расширение адресовано высокоразвитым интеллектуальным людям, а не извращенцам; наше общество должно быть ориентировано на своём пути на высшие стандарты, а не на низшие - в этом состоит суть развития и эволюции человеческого общества; поэтому, моя позиция такова - что зрелые у��ом люди достаточно разумны, чтобы понимать, что есть хорошо, а что плохо и нести полную ответственность за собственные действия; для прочих - никакие "фильтры" не помогут, пока эти люди сами не поймут, как работает Вселенная)
106
+
107
+ <a name="usage">
108
+
109
+ ## Использование
110
+
111
+ > Используя данное программное обеспечение, вы соглашаетесь с [ответственностью](#disclaimer)
112
+
113
+ 1. В раскрывающимся меню "ReActor" импортируйте изображение, содержащее лицо;
114
+ 2. Установите флажок "Enable";
115
+ 3. Готово, теперь результат будет иметь то лицо, которое вы выбрали.
116
+
117
+ <img src="example/example.jpg" alt="example" width="808"/>
118
+
119
+
120
+ ### Если лицо получилось нечётким
121
+ Используйте опцию "Restore Face". Также можете попробовать опцию "Upscaler". Для более точного контроля параметров используйте Upscaler во вкладке "Extras".
122
+ Также вы можете установить порядок постобработки (начиная с версии 0.1.0):
123
+ <img src="example/pp-order.png" alt="example"/>
124
+
125
+ *Прежняя логика была противоположенной (Upscale -> затем Restore), что приводило к более худшему качеству изображения лица (а также к значительной разнице текстур) после увеличения.*
126
+
127
+ ### Результат имеет несколько лиц
128
+ Выберите номера лиц, которые нужно поменять, используя поля "Comma separated face number(s)" для исходного изображения лица и для результата. Можно устанавливать любой, необходимый вам, порядок лиц.
129
+ <img src="example/multiple-faces.png" alt="example"/>
130
+
131
+ ### ~~Результат получился чёрным~~
132
+ ~~Это значит, что сработал NSFW фильтр.~~
133
+
134
+ <img src="example/IamSFW.jpg" alt="IamSFW" width="50%"/>
135
+
136
+ ### Img2Img
137
+
138
+ Используйте эту вкладку, чтобы заменить лицо на уже готовом изображении (флажок "Swap in source image") или на сгенерированном на основе готового (флажок "Swap in generated image").
139
+
140
+ Inpainting также работает, но замена лица происходит только в области маски.<br>Пожалуйста, используйте с опцией "Only masked" для "Inpaint area", если вы применяете "Upscaler". Иначе, используйте функцию увеличения (апскейла) через вкладку "Extras" или через опциональный загрузчик "Script" (внизу экрана), применив "SD upscale" или "Ultimate SD upscale".
141
+
142
+ ## API
143
+
144
+ Вы можете использовать ReActor как со встроенным SD Webui API так и через внешнее API.
145
+
146
+ Подробная инструкция **[здесь](/API.md)**.
147
+
148
+ <a name="troubleshooting">
149
+
150
+ ## Устранение проблем
151
+
152
+ ### **I. "You should at least have one model in models directory"**
153
+
154
+ Проверьте путь, где хранится модель "inswapper_128.onnx". Файл должен находиться в папке `stable-diffusion-webui\models\insightface`. Переместите модель туда, если она находится в какой-то иной директории.
155
+
156
+ ### **II. Какие-либо проблемы с установкой Insightface или прочих пакетов**
157
+
158
+ (Для пользователей Mac M1/M2) Если вы получаете ошибки в ходе установки Insightface - читайте https://github.com/Gourieff/sd-webui-reactor/issues/42
159
+
160
+ (Для пользователей Windows) Если VS C++ Build Tools или MS VS 2022 установлены но вы видите ошибки, связанные с отсутствием Insightface, попробуйте следующее:
161
+ 1. Закройте (остановите) SD WebUI Сервер и запустите его снова (возможно, не прошла инициализация пакета после его установки)
162
+
163
+ (Для пользователей любых ОС) Попробуйте следующее:
164
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
165
+ 2. Перейдите в папку (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages`
166
+ 3. Если вы видите к-л папки с именами, начинающимися с `~` (например, "~rotobuf") - удалите их
167
+ 4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`
168
+ 5. Откройте Терминал или Консоль (cmd) для этой папки и выполните `activate`
169
+ 6. Для начала обновите pip: `pip install -U pip`
170
+ 7. Далее:
171
+ - `pip install insightface==0.7.3`
172
+ - `pip install onnx==1.14.0`
173
+ - `pip install onnxruntime==1.15.0`
174
+ - `pip install opencv-python==4.7.0.72`
175
+ - `pip install tqdm`
176
+ 8. Выполните `deactivate`, закройте Терминал или Консоль и запустите SD WebUI, ReActor должен запуститься без к-л проблем - если же нет, добро пожаловать в раздел "Issues".
177
+
178
+ ### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
179
+
180
+ Для начала отключите любые другие Roop-подобные расширения:
181
+ - Перейдите в 'Extensions -> Installed' и снимите флажок с ненужных:
182
+ <img src="example/roop-off.png" alt="uncompatible-with-other-roop"/>
183
+ - Нажмите 'Apply and restart UI'
184
+
185
+ Альтернативные решения:
186
+ - https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243
187
+ - https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (актуально для Vladmandic SD.Next)
188
+
189
+ ### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
190
+
191
+ Отключите расширение "SD-CN-Animation" (или какое-либо другое, вызывающее конфликт)
192
+
193
+ ### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed" ИЛИ "AttributeError: 'NoneType' object has no attribute 'get'"**
194
+
195
+ Эта ошибка появляется, если что-то не так с файлом модели `inswapper_128.onnx`.
196
+
197
+ Скачайте вручную по ссылке [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)
198
+ и сохраните в директорию `stable-diffusion-webui\models\insightface`, заменив имеющийся файл.
199
+
200
+ ### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled"**
201
+
202
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
203
+ 2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
204
+ 3. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
205
+ 4. Затем:
206
+ - `python -m pip install -U pip`
207
+ - `pip uninstall -y onnx onnxruntime onnxruntime-gpu onnxruntime-silicon`
208
+ - `pip install onnx==1.14.0 onnxruntime==1.15.0`
209
+
210
+ Если это не помогло - значит какое-то другое расширение переустанавливает `onnxruntime` всякий раз, когда SD WebUI проверяет требования пакетов. Внимательно посмотрите список активных расширений. Если видите там "WD14 tagger" - попробуйте отключить его и ещё раз выполнить шаги выше. Это расширение вызывает переустановку `onnxruntime` на `onnxruntime-gpu` при каждом запуске SD WebUI.
211
+
212
+ ### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
213
+
214
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
215
+ 2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
216
+ 3. Перейдите в папку "google" (внутри "site-packages") и удалите любые папки с именам, начинающимися на "~"
217
+ 4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
218
+ 5. Затем:
219
+ - `python -m pip install -U pip`
220
+ - `pip uninstall protobuf`
221
+ - `pip install protobuf==3.20.3`
222
+
223
+ Если это не помгло - значит, есть к-л другое расширение, которое использует более новую версию пакета protobuf, и SD WebUI устанавли��ает эту версию при каждом запуске.
224
+
225
+ <a name="insightfacebuild">
226
+
227
+ ### **VIII. (Для пользователей Windows) Если вы до сих пор не можете установить пакет Insightface по каким-то причинам или же просто не желаете устанавливать Visual Studio или VS C++ Build Tools - сделайте следующее:**
228
+
229
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
230
+ 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"
231
+ 3. Из корневой директории откройте Консоль (CMD) и выполните `.\venv\Scripts\activate`
232
+ 4. Обновите PIP: `python -m pip install -U pip`
233
+ 5. Затем установите Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`
234
+ 6. Готово!
235
+
236
+ ### **IX. Ошибка обновления 07-Август-23**
237
+
238
+ Если после очередного `git pull` вы получили сообщение: `Merge made by the 'recursive' strategy` и затем, когда проверяете статус репозитория через `git status`, вы видите `Your branch is ahead of 'origin/main' by`
239
+
240
+ Выполните следующее:
241
+
242
+ Внутри папки `extensions\sd-webui-reactor` запустите Терминал или Консоль (cmd) и затем:
243
+ - `git reset f48bdf1 --hard`
244
+ - `git pull`
245
+
246
+ ИЛИ:
247
+
248
+ Полностью удалите папку `sd-webui-reactor` внутри директории `extensions`, запустите Терминал или Консоль (cmd) и выполните `git clone https://github.com/Gourieff/sd-webui-reactor`
249
+
250
+
251
+ <a name="updating">
252
+
253
+ ## Обновление
254
+
255
+ Самый простой и удобный способ обновления SD WebUI и расширений: https://github.com/Gourieff/sd-webui-extensions-updater
256
+
257
+ ## ComfyUI
258
+
259
+ Вы можете использовать ReActor с ComfyUI<br>
260
+ Инструкция здесь: [ReActor Node](https://github.com/Gourieff/comfyui-reactor-node)
261
+
262
+ <a name="disclaimer">
263
+
264
+ ## Ответственность
265
+
266
+ Это программное обеспечение призвано стать продуктивным вкладом в быстрорастущую медиаиндустрию на основе генеративных сетей и искусственного интеллекта. Данное ПО поможет художникам в решении таких задач, как анимация собственного персонажа или использование персонажа в качестве модели для одежды и т.д.
267
+
268
+ Разработчики этого программного обеспечения осведомлены о возможных неэтичных применениях и обязуются принять против этого превентивные меры. Мы продолжим развивать этот проект в позитивном направлении, придерживаясь закона и этики.
269
+
270
+ Подразумевается, что пользователи этого программного обеспечения будут использовать его ответственно, соблюдая локальное законодательство. Если используется лицо реального человека, пользователь обязан получить согласие заинтересованного лица и четко указать, что это дипфейк при размещении контента в Интернете. **Разработчики и Со-авторы данного программного обеспечения не несут ответственности за действия конечных пользователей.**
271
+
272
+ Используя данное расширение, вы соглашаетесь не создавать материалы, которые:
273
+ - нарушают какие-либо действующие законы тех или иных государств или международных организаций;
274
+ - причиняют какой-либо вред человеку или лицам;
275
+ - пропагандируют любую информацию (как общедоступную, так и личную) или изображения (как общедоступные, так и личные), которые могут быть направлены на причинение вреда;
276
+ - используются для распростр��нения дезинформации;
277
+ - нацелены на уязвимые группы людей.
extensions-builtin/sd-webui-reactor/example/IamSFW.jpg ADDED

Git LFS Details

  • SHA256: 791b6573f6a26a96272d1ae401c7f5e4108688e164a794f8ff719b847a50af4e
  • Pointer size: 131 Bytes
  • Size of remote file: 496 kB
extensions-builtin/sd-webui-reactor/example/ReActor_logo_red.png ADDED

Git LFS Details

  • SHA256: 2ae554cc50c0321601aa4004cacf303c496c966e3032c8efc5382cb878a72ef1
  • Pointer size: 129 Bytes
  • Size of remote file: 7.76 kB
extensions-builtin/sd-webui-reactor/example/api_example.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ]
43
+
44
+ # The args for ReActor can be found by
45
+ # requests.get(url=f'{address}/sdapi/v1/script-info')
46
+
47
+ 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"
48
+
49
+ 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))"
50
+
51
+ payload = {
52
+ "prompt": prompt,
53
+ "negative_prompt": neg,
54
+ "seed": -1,
55
+ "sampler_name": "DPM++ 2M Karras",
56
+ "steps": 15,
57
+ "cfg_scale": 7,
58
+ "width": 512,
59
+ "height": 768,
60
+ "restore_faces": False,
61
+ "alwayson_scripts": {"reactor":{"args":args}}
62
+ }
63
+
64
+ try:
65
+ print('Working... Please wait...')
66
+ result = requests.post(url=f'{address}/sdapi/v1/txt2img', json=payload)
67
+ except Exception as e:
68
+ print(e)
69
+ finally:
70
+ print('Done! Saving file...')
71
+
72
+ if result is not None:
73
+ r = result.json()
74
+ n = 0
75
+
76
+ for i in r['images']:
77
+ image = Image.open(io.BytesIO(base64.b64decode(i.split(",",1)[0])))
78
+
79
+ png_payload = {
80
+ "image": "data:image/png;base64," + i
81
+ }
82
+ response2 = requests.post(url=f'{address}/sdapi/v1/png-info', json=png_payload)
83
+
84
+ pnginfo = PngImagePlugin.PngInfo()
85
+ pnginfo.add_text("parameters", response2.json().get("info"))
86
+ output_file = output+'_'+str(n)+'_.png'
87
+ try:
88
+ image.save(output_file, pnginfo=pnginfo)
89
+ except Exception as e:
90
+ print(e)
91
+ finally:
92
+ print(f'{output_file} is saved\nAll is done!')
93
+ n += 1
94
+ else:
95
+ print('Something went wrong...')
extensions-builtin/sd-webui-reactor/example/api_external.curl ADDED
The diff for this file is too large to render. See raw diff
 
extensions-builtin/sd-webui-reactor/example/api_external.json ADDED
The diff for this file is too large to render. See raw diff
 
extensions-builtin/sd-webui-reactor/example/demo_crop.jpg ADDED

Git LFS Details

  • SHA256: 1bfa8081c25d69d837200ef3211782518ab18df7214a3465a172d6b592a0698c
  • Pointer size: 131 Bytes
  • Size of remote file: 305 kB
extensions-builtin/sd-webui-reactor/example/example.jpg ADDED

Git LFS Details

  • SHA256: 7587d72251b92fd69b102e4ccfa4398056eac81b24a734909895e061bd87582d
  • Pointer size: 130 Bytes
  • Size of remote file: 90.7 kB
extensions-builtin/sd-webui-reactor/example/insightface-0.7.3-cp310-cp310-win_amd64.whl ADDED
Binary file (842 kB). View file
 
extensions-builtin/sd-webui-reactor/example/multiple-faces.png ADDED

Git LFS Details

  • SHA256: b0b8c147bb82d28819309e9837f98aadda5e9699a61f2d4ad230d217c85a9af4
  • Pointer size: 130 Bytes
  • Size of remote file: 15.5 kB
extensions-builtin/sd-webui-reactor/example/pp-order.png ADDED

Git LFS Details

  • SHA256: 98cbd528f5f7869938f2fb9aad90effa399dc078a4f82e5d00f159025625adad
  • Pointer size: 130 Bytes
  • Size of remote file: 31.8 kB
extensions-builtin/sd-webui-reactor/example/roop-off.png ADDED

Git LFS Details

  • SHA256: 65a04f98c180eafad7a8aaeb08f82459f362a2f43246185ce889fa3ecacd2013
  • Pointer size: 130 Bytes
  • Size of remote file: 13.3 kB
extensions-builtin/sd-webui-reactor/install.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import os, sys
3
+ import pkg_resources
4
+ from tqdm import tqdm
5
+ import urllib.request
6
+ from packaging import version as pv
7
+
8
+ from modules.paths_internal import models_path
9
+
10
+ req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt")
11
+
12
+ models_dir_old = os.path.join(models_path, "roop")
13
+ models_dir = os.path.join(models_path, "insightface")
14
+ if os.path.exists(models_dir_old):
15
+ os.rename(models_dir_old, models_dir)
16
+ model_url = "https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx"
17
+ model_name = os.path.basename(model_url)
18
+ model_path = os.path.join(models_dir, model_name)
19
+
20
+ def run_pip(*args):
21
+ subprocess.run([sys.executable, "-m", "pip", "install", *args])
22
+
23
+ def is_installed (
24
+ package: str, version: str | None = None, strict: bool = True
25
+ ):
26
+ has_package = None
27
+ try:
28
+ has_package = pkg_resources.get_distribution(package)
29
+ if has_package is not None:
30
+ installed_version = has_package.version
31
+ if (installed_version != version and strict == True) or (pv.parse(installed_version) < pv.parse(version) and strict == False):
32
+ return False
33
+ else:
34
+ return True
35
+ else:
36
+ return False
37
+ except Exception as e:
38
+ print(f"Error: {e}")
39
+ return False
40
+
41
+ def download(url, path):
42
+ request = urllib.request.urlopen(url)
43
+ total = int(request.headers.get('Content-Length', 0))
44
+ with tqdm(total=total, desc='Downloading...', unit='B', unit_scale=True, unit_divisor=1024) as progress:
45
+ urllib.request.urlretrieve(url, path, reporthook=lambda count, block_size, total_size: progress.update(block_size))
46
+
47
+ if not os.path.exists(models_dir):
48
+ os.makedirs(models_dir)
49
+
50
+ if not os.path.exists(model_path):
51
+ download(model_url, model_path)
52
+
53
+ print("Checking ReActor requirements...", end=' ')
54
+ with open(req_file) as file:
55
+ install_count = 0
56
+ strict = True
57
+ for package in file:
58
+ package_version = None
59
+ try:
60
+ package = package.strip()
61
+ if "==" in package:
62
+ package_version = package.split('==')[1]
63
+ elif ">=" in package:
64
+ package_version = package.split('>=')[1]
65
+ strict = False
66
+ if not is_installed(package,package_version,strict):
67
+ install_count += 1
68
+ run_pip(package)
69
+ except Exception as e:
70
+ print(e)
71
+ print(f"\nERROR: Failed to install {package} - ReActor won't start")
72
+ raise e
73
+ if install_count > 0:
74
+ print(f'\n--- PLEASE, RESTART the Server! ---\n')
75
+ else:
76
+ print('Ok')
extensions-builtin/sd-webui-reactor/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ insightface==0.7.3
2
+ onnx>=1.14.0
3
+ onnxruntime>=1.15.0
4
+ opencv-python>=4.7.0.72
extensions-builtin/sd-webui-reactor/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.INFO)
118
+ elif console_logging_level == 2:
119
+ patch_insightface(*original_functions)
120
+ logger.setLevel(logging.INFO)
extensions-builtin/sd-webui-reactor/scripts/reactor_api.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Thanks SpenserCai for the original version of the roop api script
3
+ -----------------------------------
4
+ --- ReActor External API v1.0.0 ---
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
+ restore_first: int = Body(1,title="Restore face -> Then upscale, 1 - True, 0 - False"),
68
+ model: str = Body("inswapper_128.onnx",title="Model"),
69
+ gender_source: int = Body(0,title="Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)"),
70
+ gender_target: int = Body(0,title="Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)"),
71
+ save_to_file: int = Body(0,title="Save Result to file, 0 - No, 1 - Yes"),
72
+ result_file_path: str = Body("",title="(if 'save_to_file = 1') Result file path")
73
+ ):
74
+ s_image = api.decode_base64_to_image(source_image)
75
+ t_image = api.decode_base64_to_image(target_image)
76
+ sf_index = source_faces_index
77
+ f_index = face_index
78
+ gender_s = gender_source
79
+ gender_t = gender_target
80
+ restore_first_bool = True if restore_first == 1 else False
81
+ 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)
82
+ use_model = get_full_model(model)
83
+ if use_model is None:
84
+ Exception("Model not found")
85
+ result = swap_face(s_image, t_image, use_model, sf_index, f_index, up_options, gender_s, gender_t)
86
+ if save_to_file == 1:
87
+ if result_file_path == "":
88
+ result_file_path = default_file_path()
89
+ try:
90
+ result[0].save(result_file_path, format='PNG')
91
+ logger.info("Result has been saved to: %s", result_file_path)
92
+ except Exception as e:
93
+ logger.error("Error while saving result: %s",e)
94
+ return {"image": api.encode_pil_to_base64(result[0])}
95
+
96
+ @app.get("/reactor/models")
97
+ async def reactor_models():
98
+ model_names = [os.path.split(model)[1] for model in get_models()]
99
+ return {"models": model_names}
100
+
101
+ @app.get("/reactor/upscalers")
102
+ async def reactor_upscalers():
103
+ names = [upscaler.name for upscaler in shared.sd_upscalers]
104
+ return {"upscalers": names}
105
+
106
+ try:
107
+ import modules.script_callbacks as script_callbacks
108
+
109
+ script_callbacks.on_app_started(reactor_api)
110
+ except:
111
+ pass
extensions-builtin/sd-webui-reactor/scripts/reactor_faceswap.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.paths_internal import models_path
17
+ from modules.images import save_image
18
+
19
+ from scripts.reactor_logger import logger
20
+ from scripts.reactor_swapper import EnhancementOptions, swap_face, check_process_halt, reset_messaged
21
+ from scripts.reactor_version import version_flag, app_title
22
+ from scripts.console_log_patch import apply_logging_patch
23
+ from scripts.reactor_helpers import make_grid, get_image_path
24
+
25
+
26
+ MODELS_PATH = None
27
+
28
+ def get_models():
29
+ global MODELS_PATH
30
+ models_path_init = os.path.join(models_path, "insightface/*")
31
+ models = glob.glob(models_path_init)
32
+ models = [x for x in models if x.endswith(".onnx") or x.endswith(".pth")]
33
+ models_names = []
34
+ for model in models:
35
+ model_path = os.path.split(model)
36
+ if MODELS_PATH is None:
37
+ MODELS_PATH = model_path[0]
38
+ model_name = model_path[1]
39
+ models_names.append(model_name)
40
+ return models_names
41
+
42
+
43
+ class FaceSwapScript(scripts.Script):
44
+ def title(self):
45
+ return f"{app_title}"
46
+
47
+ def show(self, is_img2img):
48
+ return scripts.AlwaysVisible
49
+
50
+ def ui(self, is_img2img):
51
+ with gr.Accordion(f"{app_title}", open=False):
52
+ with gr.Tab("Main"):
53
+ with gr.Column():
54
+ img = gr.Image(type="pil")
55
+ enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}")
56
+ save_original = gr.Checkbox(False, label="Save Original", info="Save the original image(s) made before swapping; If you use \"img2img\" - this option will affect with \"Swap in generated\" only")
57
+ gr.Markdown("<br>")
58
+ gr.Markdown("Source Image (above):")
59
+ with gr.Row():
60
+ source_faces_index = gr.Textbox(
61
+ value="0",
62
+ placeholder="Which face(s) to use as Source (comma separated)",
63
+ label="Comma separated face number(s); Example: 0,2,1",
64
+ )
65
+ gender_source = gr.Radio(
66
+ ["No", "Female Only", "Male Only"],
67
+ value="No",
68
+ label="Gender Detection (Source)",
69
+ type="index",
70
+ )
71
+ gr.Markdown("<br>")
72
+ gr.Markdown("Target Image (result):")
73
+ with gr.Row():
74
+ faces_index = gr.Textbox(
75
+ value="0",
76
+ placeholder="Which face(s) to Swap into Target (comma separated)",
77
+ label="Comma separated face number(s); Example: 1,0,2",
78
+ )
79
+ gender_target = gr.Radio(
80
+ ["No", "Female Only", "Male Only"],
81
+ value="No",
82
+ label="Gender Detection (Target)",
83
+ type="index",
84
+ )
85
+ gr.Markdown("<br>")
86
+ with gr.Row():
87
+ face_restorer_name = gr.Radio(
88
+ label="Restore Face",
89
+ choices=["None"] + [x.name() for x in shared.face_restorers],
90
+ value=shared.face_restorers[0].name(),
91
+ type="value",
92
+ )
93
+ face_restorer_visibility = gr.Slider(
94
+ 0, 1, 1, step=0.1, label="Restore Face Visibility"
95
+ )
96
+ gr.Markdown("<br>")
97
+ swap_in_source = gr.Checkbox(
98
+ False,
99
+ label="Swap in source image",
100
+ visible=is_img2img,
101
+ )
102
+ swap_in_generated = gr.Checkbox(
103
+ True,
104
+ label="Swap in generated image",
105
+ visible=is_img2img,
106
+ )
107
+ with gr.Tab("Upscale"):
108
+ restore_first = gr.Checkbox(
109
+ True,
110
+ label="1. Restore Face -> 2. Upscale (-Uncheck- if you want vice versa)",
111
+ info="Postprocessing Order"
112
+ )
113
+ upscaler_name = gr.Dropdown(
114
+ choices=[upscaler.name for upscaler in shared.sd_upscalers],
115
+ label="Upscaler",
116
+ value="None",
117
+ info="Won't scale if you choose -Swap in Source- via img2img, only 1x-postprocessing will affect (texturing, denoising, restyling etc.)"
118
+ )
119
+ gr.Markdown("<br>")
120
+ with gr.Row():
121
+ upscaler_scale = gr.Slider(1, 8, 1, step=0.1, label="Scale by")
122
+ upscaler_visibility = gr.Slider(
123
+ 0, 1, 1, step=0.1, label="Upscaler Visibility (if scale = 1)"
124
+ )
125
+ with gr.Tab("Settings"):
126
+ models = get_models()
127
+ with gr.Row():
128
+ if len(models) == 0:
129
+ logger.warning(
130
+ "You should at least have one model in models directory, please read the doc here : https://github.com/Gourieff/sd-webui-reactor/"
131
+ )
132
+ model = gr.Dropdown(
133
+ choices=models,
134
+ label="Model not found, please download one and reload WebUI",
135
+ )
136
+ else:
137
+ model = gr.Dropdown(
138
+ choices=models, label="Model", value=models[0]
139
+ )
140
+ console_logging_level = gr.Radio(
141
+ ["No log", "Minimum", "Default"],
142
+ value="Minimum",
143
+ label="Console Log Level",
144
+ type="index",
145
+ )
146
+
147
+ return [
148
+ img,
149
+ enable,
150
+ source_faces_index,
151
+ faces_index,
152
+ model,
153
+ face_restorer_name,
154
+ face_restorer_visibility,
155
+ restore_first,
156
+ upscaler_name,
157
+ upscaler_scale,
158
+ upscaler_visibility,
159
+ swap_in_source,
160
+ swap_in_generated,
161
+ console_logging_level,
162
+ gender_source,
163
+ gender_target,
164
+ save_original,
165
+ ]
166
+
167
+
168
+ @property
169
+ def upscaler(self) -> UpscalerData:
170
+ for upscaler in shared.sd_upscalers:
171
+ if upscaler.name == self.upscaler_name:
172
+ return upscaler
173
+ return None
174
+
175
+ @property
176
+ def face_restorer(self) -> FaceRestoration:
177
+ for face_restorer in shared.face_restorers:
178
+ if face_restorer.name() == self.face_restorer_name:
179
+ return face_restorer
180
+ return None
181
+
182
+ @property
183
+ def enhancement_options(self) -> EnhancementOptions:
184
+ return EnhancementOptions(
185
+ do_restore_first = self.restore_first,
186
+ scale=self.upscaler_scale,
187
+ upscaler=self.upscaler,
188
+ face_restorer=self.face_restorer,
189
+ upscale_visibility=self.upscaler_visibility,
190
+ restorer_visibility=self.face_restorer_visibility,
191
+ )
192
+
193
+ def process(
194
+ self,
195
+ p: StableDiffusionProcessing,
196
+ img,
197
+ enable,
198
+ source_faces_index,
199
+ faces_index,
200
+ model,
201
+ face_restorer_name,
202
+ face_restorer_visibility,
203
+ restore_first,
204
+ upscaler_name,
205
+ upscaler_scale,
206
+ upscaler_visibility,
207
+ swap_in_source,
208
+ swap_in_generated,
209
+ console_logging_level,
210
+ gender_source,
211
+ gender_target,
212
+ save_original,
213
+ ):
214
+ self.enable = enable
215
+ if self.enable:
216
+
217
+ reset_messaged()
218
+ if check_process_halt():
219
+ return
220
+
221
+ global MODELS_PATH
222
+ self.source = img
223
+ self.face_restorer_name = face_restorer_name
224
+ self.upscaler_scale = upscaler_scale
225
+ self.upscaler_visibility = upscaler_visibility
226
+ self.face_restorer_visibility = face_restorer_visibility
227
+ self.restore_first = restore_first
228
+ self.upscaler_name = upscaler_name
229
+ self.swap_in_generated = swap_in_generated
230
+ self.model = os.path.join(MODELS_PATH,model)
231
+ self.console_logging_level = console_logging_level
232
+ self.gender_source = gender_source
233
+ self.gender_target = gender_target
234
+ self.save_original = save_original
235
+ if self.gender_source is None or self.gender_source == "No":
236
+ self.gender_source = 0
237
+ if self.gender_target is None or self.gender_target == "No":
238
+ self.gender_target = 0
239
+ self.source_faces_index = [
240
+ int(x) for x in source_faces_index.strip(",").split(",") if x.isnumeric()
241
+ ]
242
+ self.faces_index = [
243
+ int(x) for x in faces_index.strip(",").split(",") if x.isnumeric()
244
+ ]
245
+ if len(self.source_faces_index) == 0:
246
+ self.source_faces_index = [0]
247
+ if len(self.faces_index) == 0:
248
+ self.faces_index = [0]
249
+ if self.save_original is None:
250
+ self.save_original = False
251
+
252
+ if self.source is not None:
253
+ apply_logging_patch(console_logging_level)
254
+ if isinstance(p, StableDiffusionProcessingImg2Img) and swap_in_source:
255
+ logger.info("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
256
+
257
+ for i in range(len(p.init_images)):
258
+ if len(p.init_images) > 1:
259
+ logger.info("Swap in %s", i)
260
+ result, output, swapped = swap_face(
261
+ self.source,
262
+ p.init_images[i],
263
+ source_faces_index=self.source_faces_index,
264
+ faces_index=self.faces_index,
265
+ model=self.model,
266
+ enhancement_options=self.enhancement_options,
267
+ gender_source=self.gender_source,
268
+ gender_target=self.gender_target,
269
+ )
270
+ p.init_images[i] = result
271
+ # 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")
272
+ # if len(output) != 0:
273
+ # with open(result_path, 'w', encoding="utf8") as f:
274
+ # f.writelines(output)
275
+
276
+ if shared.state.interrupted or shared.state.skipped:
277
+ return
278
+
279
+ else:
280
+ logger.error("Please provide a source face")
281
+
282
+ def postprocess(self, p: StableDiffusionProcessing, processed: Processed, *args):
283
+ if self.enable:
284
+
285
+ reset_messaged()
286
+ if check_process_halt():
287
+ return
288
+
289
+ if self.save_original:
290
+
291
+ postprocess_run: bool = True
292
+
293
+ orig_images : List[Image.Image] = processed.images[processed.index_of_first_image:]
294
+ orig_infotexts : List[str] = processed.infotexts[processed.index_of_first_image:]
295
+
296
+ result_images: List = processed.images
297
+ # result_info: List = processed.infotexts
298
+
299
+ if self.swap_in_generated:
300
+ logger.info("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
301
+ if self.source is not None:
302
+ for i,(img,info) in enumerate(zip(orig_images, orig_infotexts)):
303
+ if check_process_halt():
304
+ postprocess_run = False
305
+ break
306
+ if len(orig_images) > 1:
307
+ logger.info("Swap in %s", i)
308
+ result, output, swapped = swap_face(
309
+ self.source,
310
+ img,
311
+ source_faces_index=self.source_faces_index,
312
+ faces_index=self.faces_index,
313
+ model=self.model,
314
+ enhancement_options=self.enhancement_options,
315
+ gender_source=self.gender_source,
316
+ gender_target=self.gender_target,
317
+ )
318
+ if result is not None and swapped > 0:
319
+ result_images.append(result)
320
+ suffix = "-swapped"
321
+ try:
322
+ img_path = save_image(result, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png",info=info, p=p, suffix=suffix)
323
+ except:
324
+ logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)")
325
+ elif result is None:
326
+ logger.error("Cannot create a result image")
327
+
328
+ # if len(output) != 0:
329
+ # split_fullfn = os.path.splitext(img_path[0])
330
+ # fullfn = split_fullfn[0] + ".txt"
331
+ # with open(fullfn, 'w', encoding="utf8") as f:
332
+ # f.writelines(output)
333
+
334
+ if shared.opts.return_grid and len(result_images) > 2 and postprocess_run:
335
+ grid = make_grid(result_images)
336
+ result_images.insert(0, grid)
337
+ try:
338
+ 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)
339
+ except:
340
+ logger.error("Cannot save a grid - please, check SD WebUI Settings (Saving and Paths)")
341
+
342
+ processed.images = result_images
343
+ # processed.infotexts = result_info
344
+
345
+ def postprocess_batch(self, p, *args, **kwargs):
346
+ if self.enable and not self.save_original:
347
+ images = kwargs["images"]
348
+
349
+ def postprocess_image(self, p, script_pp: scripts.PostprocessImageArgs, *args):
350
+ if self.enable and self.swap_in_generated and not self.save_original:
351
+
352
+ current_job_number = shared.state.job_no + 1
353
+ job_count = shared.state.job_count
354
+ if current_job_number == job_count:
355
+ reset_messaged()
356
+ if check_process_halt():
357
+ return
358
+
359
+ if self.source is not None:
360
+ logger.info("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
361
+ image: Image.Image = script_pp.image
362
+ result, output, swapped = swap_face(
363
+ self.source,
364
+ image,
365
+ source_faces_index=self.source_faces_index,
366
+ faces_index=self.faces_index,
367
+ model=self.model,
368
+ enhancement_options=self.enhancement_options,
369
+ gender_source=self.gender_source,
370
+ gender_target=self.gender_target,
371
+ )
372
+ try:
373
+ pp = scripts_postprocessing.PostprocessedImage(result)
374
+ pp.info = {}
375
+ p.extra_generation_params.update(pp.info)
376
+ script_pp.image = pp.image
377
+
378
+ # if len(output) != 0:
379
+ # result_path = get_image_path(script_pp.image, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "txt", p=p, suffix="-swapped")
380
+ # if len(output) != 0:
381
+ # with open(result_path, 'w', encoding="utf8") as f:
382
+ # f.writelines(output)
383
+ except:
384
+ logger.error("Cannot create a result image")
extensions-builtin/sd-webui-reactor/scripts/reactor_globals.py ADDED
@@ -0,0 +1 @@
 
 
1
+ IS_RUN: bool = False
extensions-builtin/sd-webui-reactor/scripts/reactor_helpers.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from collections import Counter
3
+ from PIL import Image
4
+ from math import isqrt, ceil
5
+ from typing import List
6
+
7
+ from modules.images import FilenameGenerator, get_next_sequence_number
8
+ from modules import shared, script_callbacks
9
+
10
+ def make_grid(image_list: List):
11
+
12
+ # Count the occurrences of each image size in the image_list
13
+ size_counter = Counter(image.size for image in image_list)
14
+
15
+ # Get the most common image size (size with the highest count)
16
+ common_size = size_counter.most_common(1)[0][0]
17
+
18
+ # Filter the image_list to include only images with the common size
19
+ image_list = [image for image in image_list if image.size == common_size]
20
+
21
+ # Get the dimensions (width and height) of the common size
22
+ size = common_size
23
+
24
+ # If there are more than one image in the image_list
25
+ if len(image_list) > 1:
26
+ num_images = len(image_list)
27
+
28
+ # Calculate the number of rows and columns for the grid
29
+ rows = isqrt(num_images)
30
+ cols = ceil(num_images / rows)
31
+
32
+ # Calculate the size of the square image
33
+ square_size = (cols * size[0], rows * size[1])
34
+
35
+ # Create a new RGB image with the square size
36
+ square_image = Image.new("RGB", square_size)
37
+
38
+ # Paste each image onto the square image at the appropriate position
39
+ for i, image in enumerate(image_list):
40
+ row = i // cols
41
+ col = i % cols
42
+
43
+ square_image.paste(image, (col * size[0], row * size[1]))
44
+
45
+ # Return the resulting square image
46
+ return square_image
47
+
48
+ # Return None if there are no images or only one image in the image_list
49
+ return None
50
+
51
+ def get_image_path(image, path, basename, seed=None, prompt=None, extension='png', p=None, suffix=""):
52
+
53
+ namegen = FilenameGenerator(p, seed, prompt, image)
54
+
55
+ save_to_dirs = shared.opts.save_to_dirs
56
+
57
+ if save_to_dirs:
58
+ dirname = namegen.apply(shared.opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
59
+ path = os.path.join(path, dirname)
60
+
61
+ os.makedirs(path, exist_ok=True)
62
+
63
+ if seed is None:
64
+ file_decoration = ""
65
+ elif shared.opts.save_to_dirs:
66
+ file_decoration = shared.opts.samples_filename_pattern or "[seed]"
67
+ else:
68
+ file_decoration = shared.opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
69
+
70
+ file_decoration = namegen.apply(file_decoration) + suffix
71
+
72
+ add_number = shared.opts.save_images_add_number or file_decoration == ''
73
+
74
+ if file_decoration != "" and add_number:
75
+ file_decoration = f"-{file_decoration}"
76
+
77
+ if add_number:
78
+ basecount = get_next_sequence_number(path, basename)
79
+ fullfn = None
80
+ for i in range(500):
81
+ fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
82
+ fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
83
+ if not os.path.exists(fullfn):
84
+ break
85
+ else:
86
+ fullfn = os.path.join(path, f"{file_decoration}.{extension}")
87
+
88
+ pnginfo = {}
89
+
90
+ params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
91
+ # script_callbacks.before_image_saved_callback(params)
92
+
93
+ fullfn = params.filename
94
+
95
+ fullfn_without_extension, extension = os.path.splitext(params.filename)
96
+ if hasattr(os, 'statvfs'):
97
+ max_name_len = os.statvfs(path).f_namemax
98
+ fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
99
+ params.filename = fullfn_without_extension + extension
100
+ fullfn = params.filename
101
+
102
+ return fullfn
extensions-builtin/sd-webui-reactor/scripts/reactor_logger.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import copy
3
+ import sys
4
+
5
+ from modules import shared
6
+ from scripts.reactor_globals import IS_RUN
7
+
8
+
9
+ class ColoredFormatter(logging.Formatter):
10
+ COLORS = {
11
+ "DEBUG": "\033[0;36m", # CYAN
12
+ "STATUS": "\033[38;5;173m", # Calm ORANGE
13
+ "INFO": "\033[0;32m", # GREEN
14
+ "WARNING": "\033[0;33m", # YELLOW
15
+ "ERROR": "\033[0;31m", # RED
16
+ "CRITICAL": "\033[0;37;41m", # WHITE ON RED
17
+ "RESET": "\033[0m", # RESET COLOR
18
+ }
19
+
20
+ def format(self, record):
21
+ colored_record = copy.copy(record)
22
+ levelname = colored_record.levelname
23
+ seq = self.COLORS.get(levelname, self.COLORS["RESET"])
24
+ colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
25
+ return super().format(colored_record)
26
+
27
+
28
+ # Create a new logger
29
+ logger = logging.getLogger("ReActor")
30
+ logger.propagate = False
31
+
32
+ # Custom Level name
33
+ logging.addLevelName(logging.INFO, "STATUS")
34
+
35
+ # Add handler if we don't have one.
36
+ if not logger.handlers:
37
+ handler = logging.StreamHandler(sys.stdout)
38
+ handler.setFormatter(
39
+ ColoredFormatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s","%H:%M:%S")
40
+ )
41
+ logger.addHandler(handler)
42
+
43
+ # Configure logger
44
+ loglevel_string = getattr(shared.cmd_opts, "reactor_loglevel", "INFO")
45
+ loglevel = getattr(logging, loglevel_string.upper(), "info")
46
+ logger.setLevel(loglevel)
47
+
48
+ def set_Run(value):
49
+ global IS_RUN
50
+ IS_RUN = value
51
+
52
+ def get_Run():
53
+ global IS_RUN
54
+ return IS_RUN
extensions-builtin/sd-webui-reactor/scripts/reactor_swapper.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
12
+ from modules.face_restoration import FaceRestoration
13
+ from modules.upscaler import UpscalerData
14
+ from modules.shared import state
15
+ from modules.paths_internal import models_path
16
+ from scripts.reactor_logger import logger
17
+
18
+ import warnings
19
+
20
+ np.warnings = warnings
21
+ np.warnings.filterwarnings('ignore')
22
+
23
+ providers = ["CPUExecutionProvider"]
24
+
25
+
26
+ @dataclass
27
+ class EnhancementOptions:
28
+ do_restore_first: bool = True
29
+ scale: int = 1
30
+ upscaler: UpscalerData = None
31
+ upscale_visibility: float = 0.5
32
+ face_restorer: FaceRestoration = None
33
+ restorer_visibility: float = 0.5
34
+
35
+
36
+ MESSAGED_STOPPED = False
37
+ MESSAGED_SKIPPED = False
38
+
39
+ def reset_messaged():
40
+ global MESSAGED_STOPPED, MESSAGED_SKIPPED
41
+ if not state.interrupted:
42
+ MESSAGED_STOPPED = False
43
+ if not state.skipped:
44
+ MESSAGED_SKIPPED = False
45
+
46
+ def check_process_halt(msgforced: bool = False):
47
+ global MESSAGED_STOPPED, MESSAGED_SKIPPED
48
+ if state.interrupted:
49
+ if not MESSAGED_STOPPED or msgforced:
50
+ logger.info("Stopped by User")
51
+ MESSAGED_STOPPED = True
52
+ return True
53
+ if state.skipped:
54
+ if not MESSAGED_SKIPPED or msgforced:
55
+ logger.info("Skipped by User")
56
+ MESSAGED_SKIPPED = True
57
+ return True
58
+ return False
59
+
60
+
61
+ FS_MODEL = None
62
+ CURRENT_FS_MODEL_PATH = None
63
+
64
+ ANALYSIS_MODEL = None
65
+
66
+
67
+ def getAnalysisModel():
68
+ global ANALYSIS_MODEL
69
+ if ANALYSIS_MODEL is None:
70
+ ANALYSIS_MODEL = insightface.app.FaceAnalysis(
71
+ name="buffalo_l", providers=providers, root=os.path.join(models_path, "insightface") # note: allowed_modules=['detection', 'genderage']
72
+ )
73
+ return ANALYSIS_MODEL
74
+
75
+
76
+ def getFaceSwapModel(model_path: str):
77
+ global FS_MODEL
78
+ global CURRENT_FS_MODEL_PATH
79
+ if CURRENT_FS_MODEL_PATH is None or CURRENT_FS_MODEL_PATH != model_path:
80
+ CURRENT_FS_MODEL_PATH = model_path
81
+ FS_MODEL = insightface.model_zoo.get_model(model_path, providers=providers)
82
+
83
+ return FS_MODEL
84
+
85
+
86
+ def restore_face(image: Image, enhancement_options: EnhancementOptions):
87
+ result_image = image
88
+
89
+ if check_process_halt(msgforced=True):
90
+ return result_image
91
+
92
+ if enhancement_options.face_restorer is not None:
93
+ original_image = result_image.copy()
94
+ logger.info("Restoring the face with %s", enhancement_options.face_restorer.name())
95
+ numpy_image = np.array(result_image)
96
+ numpy_image = enhancement_options.face_restorer.restore(numpy_image)
97
+ restored_image = Image.fromarray(numpy_image)
98
+ result_image = Image.blend(
99
+ original_image, restored_image, enhancement_options.restorer_visibility
100
+ )
101
+
102
+ return result_image
103
+
104
+ def upscale_image(image: Image, enhancement_options: EnhancementOptions):
105
+ result_image = image
106
+
107
+ if check_process_halt(msgforced=True):
108
+ return result_image
109
+
110
+ if enhancement_options.upscaler is not None and enhancement_options.upscaler.name != "None":
111
+ original_image = result_image.copy()
112
+ logger.info(
113
+ "Upscaling with %s scale = %s",
114
+ enhancement_options.upscaler.name,
115
+ enhancement_options.scale,
116
+ )
117
+ result_image = enhancement_options.upscaler.scaler.upscale(
118
+ original_image, enhancement_options.scale, enhancement_options.upscaler.data_path
119
+ )
120
+ if enhancement_options.scale == 1:
121
+ result_image = Image.blend(
122
+ original_image, result_image, enhancement_options.upscale_visibility
123
+ )
124
+
125
+ return result_image
126
+
127
+ def enhance_image(image: Image, enhancement_options: EnhancementOptions):
128
+ result_image = image
129
+
130
+ if check_process_halt(msgforced=True):
131
+ return result_image
132
+
133
+ if enhancement_options.do_restore_first:
134
+
135
+ result_image = restore_face(result_image, enhancement_options)
136
+ result_image = upscale_image(result_image, enhancement_options)
137
+
138
+ else:
139
+
140
+ result_image = upscale_image(result_image, enhancement_options)
141
+ result_image = restore_face(result_image, enhancement_options)
142
+
143
+ return result_image
144
+
145
+ def get_gender(face, face_index):
146
+ gender = [
147
+ x.sex
148
+ for x in face
149
+ ]
150
+ gender.reverse()
151
+ try:
152
+ face_gender = gender[face_index]
153
+ except:
154
+ logger.error("Gender Detection: No face with index = %s was found", face_index)
155
+ return "None"
156
+ return face_gender
157
+
158
+ def get_face_gender(
159
+ face,
160
+ face_index,
161
+ gender_condition,
162
+ operated: str,
163
+ gender_detected,
164
+ ):
165
+ face_gender = gender_detected
166
+ if face_gender == "None":
167
+ return None, 0
168
+ logger.info("%s Face %s: Detected Gender -%s-", operated, face_index, face_gender)
169
+ if (gender_condition == 1 and face_gender == "F") or (gender_condition == 2 and face_gender == "M"):
170
+ logger.info("OK - Detected Gender matches Condition")
171
+ try:
172
+ return sorted(face, key=lambda x: x.bbox[0])[face_index], 0
173
+ except IndexError:
174
+ return None, 0
175
+ else:
176
+ logger.info("WRONG - Detected Gender doesn't match Condition")
177
+ return sorted(face, key=lambda x: x.bbox[0])[face_index], 1
178
+
179
+ def get_face_age(face, face_index):
180
+ age = [
181
+ x.age
182
+ for x in face
183
+ ]
184
+ age.reverse()
185
+ try:
186
+ face_age = age[face_index]
187
+ except:
188
+ logger.error("Age Detection: No face with index = %s was found", face_index)
189
+ return "None"
190
+ return face_age
191
+
192
+ def reget_face_single(img_data, det_size, face_index, gender_source, gender_target):
193
+ det_size_half = (det_size[0] // 2, det_size[1] // 2)
194
+ return get_face_single(img_data, face_index=face_index, det_size=det_size_half, gender_source=gender_source, gender_target=gender_target)
195
+
196
+
197
+ def get_face_single(img_data: np.ndarray, face_index=0, det_size=(640, 640), gender_source=0, gender_target=0):
198
+ face_analyser = copy.deepcopy(getAnalysisModel())
199
+ face_analyser.prepare(ctx_id=0, det_size=det_size)
200
+ face = face_analyser.get(img_data)
201
+
202
+ buffalo_path = os.path.join(models_path, "insightface/models/buffalo_l.zip")
203
+ if os.path.exists(buffalo_path):
204
+ os.remove(buffalo_path)
205
+
206
+ face_age = "None"
207
+ try:
208
+ face_age = get_face_age(face, face_index)
209
+ except:
210
+ logger.error("Cannot detect any Age for Face index = %s", face_index)
211
+
212
+ face_gender = "None"
213
+ try:
214
+ face_gender = get_gender(face, face_index)
215
+ gender_detected = face_gender
216
+ face_gender = "Female" if face_gender == "F" else ("Male" if face_gender == "M" else "None")
217
+ except:
218
+ logger.error("Cannot detect any Gender for Face index = %s", face_index)
219
+
220
+ if gender_source != 0:
221
+ if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
222
+ return reget_face_single(img_data, det_size, face_index, gender_source, gender_target)
223
+ faces, wrong_gender = get_face_gender(face,face_index,gender_source,"Source",gender_detected)
224
+ return faces, wrong_gender, face_age, face_gender
225
+
226
+ if gender_target != 0:
227
+ if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
228
+ return reget_face_single(img_data, det_size, face_index, gender_source, gender_target)
229
+ faces, wrong_gender = get_face_gender(face,face_index,gender_target,"Target",gender_detected)
230
+ return faces, wrong_gender, face_age, face_gender
231
+
232
+ if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
233
+ return reget_face_single(img_data, det_size, face_index, gender_source, gender_target)
234
+
235
+ try:
236
+ return sorted(face, key=lambda x: x.bbox[0])[face_index], 0, face_age, face_gender
237
+ except IndexError:
238
+ return None, 0, face_age, face_gender
239
+
240
+
241
+ def swap_face(
242
+ source_img: Image.Image,
243
+ target_img: Image.Image,
244
+ model: Union[str, None] = None,
245
+ source_faces_index: List[int] = [0],
246
+ faces_index: List[int] = [0],
247
+ enhancement_options: Union[EnhancementOptions, None] = None,
248
+ gender_source: int = 0,
249
+ gender_target: int = 0,
250
+ ):
251
+ result_image = target_img
252
+
253
+ if check_process_halt():
254
+ return result_image
255
+
256
+ if model is not None:
257
+
258
+ if isinstance(source_img, str): # source_img is a base64 string
259
+ import base64, io
260
+ if 'base64,' in source_img: # check if the base64 string has a data URL scheme
261
+ # split the base64 string to get the actual base64 encoded image data
262
+ base64_data = source_img.split('base64,')[-1]
263
+ # decode base64 string to bytes
264
+ img_bytes = base64.b64decode(base64_data)
265
+ else:
266
+ # if no data URL scheme, just decode
267
+ img_bytes = base64.b64decode(source_img)
268
+
269
+ source_img = Image.open(io.BytesIO(img_bytes))
270
+
271
+ source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
272
+ target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
273
+
274
+ output: List = []
275
+ output_info: str = ""
276
+ swapped = 0
277
+
278
+ logger.info("Detecting Source Face, Index = %s", source_faces_index[0])
279
+ source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, face_index=source_faces_index[0], gender_source=gender_source)
280
+ if source_age != "None" or source_gender != "None":
281
+ logger.info("Detected: -%s- y.o. %s", source_age, source_gender)
282
+
283
+ output_info = f"SourceFaceIndex={source_faces_index[0]};Age={source_age};Gender={source_gender}\n"
284
+ output.append(output_info)
285
+
286
+ if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index):
287
+ logger.info("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.")
288
+ elif source_face is not None:
289
+
290
+ result = target_img
291
+ face_swapper = getFaceSwapModel(model)
292
+
293
+ source_face_idx = 0
294
+
295
+ for face_num in faces_index:
296
+ if len(source_faces_index) > 1 and source_face_idx > 0:
297
+
298
+ logger.info("Detecting Source Face, Index = %s", source_faces_index[source_face_idx])
299
+ source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, face_index=source_faces_index[source_face_idx], gender_source=gender_source)
300
+ if source_age != "None" or source_gender != "None":
301
+ logger.info("Detected: -%s- y.o. %s", source_age, source_gender)
302
+
303
+ output_info = f"SourceFaceIndex={source_faces_index[source_face_idx]};Age={source_age};Gender={source_gender}\n"
304
+ output.append(output_info)
305
+
306
+ source_face_idx += 1
307
+
308
+ if source_face is not None and wrong_gender == 0:
309
+ logger.info("Detecting Target Face, Index = %s", face_num)
310
+ target_face, wrong_gender, target_age, target_gender = get_face_single(target_img, face_index=face_num, gender_target=gender_target)
311
+ if target_age != "None" or target_gender != "None":
312
+ logger.info("Detected: -%s- y.o. %s", target_age, target_gender)
313
+
314
+ output_info = f"TargetFaceIndex={face_num};Age={target_age};Gender={target_gender}\n"
315
+ output.append(output_info)
316
+
317
+ if target_face is not None and wrong_gender == 0:
318
+ logger.info("Swapping Source into Target")
319
+ result = face_swapper.get(result, target_face, source_face)
320
+ swapped += 1
321
+
322
+ elif wrong_gender == 1:
323
+ wrong_gender = 0
324
+
325
+ if source_face_idx == len(source_faces_index):
326
+ result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
327
+
328
+ if enhancement_options is not None and len(source_faces_index) > 1:
329
+ result_image = enhance_image(result_image, enhancement_options)
330
+
331
+ return result_image, output, swapped
332
+
333
+ else:
334
+ logger.info(f"No target face found for {face_num}")
335
+
336
+ elif wrong_gender == 1:
337
+ wrong_gender = 0
338
+
339
+ if source_face_idx == len(source_faces_index):
340
+ result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
341
+
342
+ if enhancement_options is not None and len(source_faces_index) > 1:
343
+ result_image = enhance_image(result_image, enhancement_options)
344
+
345
+ return result_image, output, swapped
346
+
347
+ else:
348
+ logger.info(f"No source face found for face number {source_face_idx}.")
349
+
350
+ result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
351
+
352
+ if enhancement_options is not None and swapped > 0:
353
+ result_image = enhance_image(result_image, enhancement_options)
354
+
355
+ else:
356
+ logger.info("No source face(s) found")
357
+
358
+ return result_image, output, swapped
extensions-builtin/sd-webui-reactor/scripts/reactor_version.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ app_title = "ReActor"
2
+ version_flag = "v0.4.2-b2"
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.info(f"Running {version_flag}")
10
+ set_Run(True)