Upload 52 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- extensions/sd-webui-reactor/.github/ISSUE_TEMPLATE/bug_report.yml +58 -0
- extensions/sd-webui-reactor/.github/ISSUE_TEMPLATE/config.yml +5 -0
- extensions/sd-webui-reactor/.github/ISSUE_TEMPLATE/feature_request.yml +16 -0
- extensions/sd-webui-reactor/.gitignore +10 -0
- extensions/sd-webui-reactor/API.md +71 -0
- extensions/sd-webui-reactor/LICENSE +661 -0
- extensions/sd-webui-reactor/README.md +361 -0
- extensions/sd-webui-reactor/README_RU.md +372 -0
- extensions/sd-webui-reactor/example/IamSFW.jpg +3 -0
- extensions/sd-webui-reactor/example/api_example.py +103 -0
- extensions/sd-webui-reactor/example/api_external.curl +0 -0
- extensions/sd-webui-reactor/example/api_external.json +0 -0
- extensions/sd-webui-reactor/example/insightface-0.7.3-cp310-cp310-win_amd64.whl +0 -0
- extensions/sd-webui-reactor/install.py +147 -0
- extensions/sd-webui-reactor/last_device.txt +1 -0
- extensions/sd-webui-reactor/reactor_modules/__pycache__/reactor_mask.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/reactor_modules/reactor_mask.py +176 -0
- extensions/sd-webui-reactor/reactor_ui/__init__.py +4 -0
- extensions/sd-webui-reactor/reactor_ui/__pycache__/__init__.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/reactor_ui/__pycache__/reactor_main_ui.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/reactor_ui/__pycache__/reactor_settings_ui.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/reactor_ui/__pycache__/reactor_tools_ui.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/reactor_ui/__pycache__/reactor_upscale_ui.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/reactor_ui/reactor_main_ui.py +182 -0
- extensions/sd-webui-reactor/reactor_ui/reactor_settings_ui.py +77 -0
- extensions/sd-webui-reactor/reactor_ui/reactor_tools_ui.py +25 -0
- extensions/sd-webui-reactor/reactor_ui/reactor_upscale_ui.py +39 -0
- extensions/sd-webui-reactor/requirements.txt +3 -0
- extensions/sd-webui-reactor/scripts/__pycache__/console_log_patch.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/__pycache__/reactor_api.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/__pycache__/reactor_faceswap.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/__pycache__/reactor_globals.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/__pycache__/reactor_helpers.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/__pycache__/reactor_logger.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/__pycache__/reactor_swapper.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/__pycache__/reactor_version.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/console_log_patch.py +120 -0
- extensions/sd-webui-reactor/scripts/reactor_api.py +118 -0
- extensions/sd-webui-reactor/scripts/reactor_entities/__pycache__/face.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/reactor_entities/__pycache__/rect.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/reactor_entities/face.py +147 -0
- extensions/sd-webui-reactor/scripts/reactor_entities/rect.py +78 -0
- extensions/sd-webui-reactor/scripts/reactor_faceswap.py +589 -0
- extensions/sd-webui-reactor/scripts/reactor_globals.py +42 -0
- extensions/sd-webui-reactor/scripts/reactor_helpers.py +217 -0
- extensions/sd-webui-reactor/scripts/reactor_inferencers/__pycache__/bisenet_mask_generator.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/reactor_inferencers/__pycache__/mask_generator.cpython-310.pyc +0 -0
- extensions/sd-webui-reactor/scripts/reactor_inferencers/bisenet_mask_generator.py +86 -0
- extensions/sd-webui-reactor/scripts/reactor_inferencers/mask_generator.py +36 -0
- extensions/sd-webui-reactor/scripts/reactor_logger.py +55 -0
extensions/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/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/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/sd-webui-reactor/.gitignore
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__pycache__/
|
2 |
+
*.py[cod]
|
3 |
+
*$py.class
|
4 |
+
*.pyc
|
5 |
+
|
6 |
+
.vscode/
|
7 |
+
|
8 |
+
example
|
9 |
+
*.txt
|
10 |
+
!requirements.txt
|
extensions/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/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/sd-webui-reactor/README.md
ADDED
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<div align="center">
|
2 |
+
|
3 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_EN.png?raw=true" alt="logo" width="180px"/>
|
4 |
+
|
5 |
+
![Version](https://img.shields.io/badge/version-0.6.0-brightgreen?style=for-the-badge&labelColor=darkgreen)
|
6 |
+
|
7 |
+
<a href="https://boosty.to/artgourieff" target="_blank">
|
8 |
+
<img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/>
|
9 |
+
<br>
|
10 |
+
<sup>
|
11 |
+
Support This Project
|
12 |
+
</sup>
|
13 |
+
</a>
|
14 |
+
|
15 |
+
<hr>
|
16 |
+
|
17 |
+
[![Commit activity](https://img.shields.io/github/commit-activity/t/Gourieff/sd-webui-reactor/main?cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/commits/main)
|
18 |
+
![Last commit](https://img.shields.io/github/last-commit/Gourieff/sd-webui-reactor/main?cacheSeconds=0)
|
19 |
+
[![Opened issues](https://img.shields.io/github/issues/Gourieff/sd-webui-reactor?color=red)](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
|
20 |
+
[![Closed issues](https://img.shields.io/github/issues-closed/Gourieff/sd-webui-reactor?color=green&cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/issues?q=is%3Aissue+is%3Aclosed)
|
21 |
+
![License](https://img.shields.io/github/license/Gourieff/sd-webui-reactor)
|
22 |
+
|
23 |
+
English | [Русский](/README_RU.md)
|
24 |
+
|
25 |
+
# ReActor for Stable Diffusion
|
26 |
+
|
27 |
+
### The Fast and Simple FaceSwap Extension with a lot of improvements and without NSFW filter (uncensored, use it on your own [responsibility](#disclaimer))
|
28 |
+
|
29 |
+
---
|
30 |
+
<b>
|
31 |
+
<a href="#latestupdate">What's new</a> | <a href="#installation">Installation</a> | <a href="#features">Features</a> | <a href="#usage">Usage</a> | <a href="#api">API</a> | <a href="#troubleshooting">Troubleshooting</a> | <a href="#updating">Updating</a> | <a href="#comfyui">ComfyUI</a> | <a href="#disclaimer">Disclaimer</a>
|
32 |
+
</b>
|
33 |
+
</div>
|
34 |
+
|
35 |
+
---
|
36 |
+
|
37 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
|
38 |
+
|
39 |
+
<a name="latestupdate">
|
40 |
+
|
41 |
+
## What's new in the latest updates
|
42 |
+
|
43 |
+
### 0.6.0 <sub><sup>ALPHA1
|
44 |
+
|
45 |
+
- UI reworked
|
46 |
+
- You can now load several source images (with reference faces) or set the path to the folder containing faces images
|
47 |
+
|
48 |
+
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_01.png?raw=true" alt="0.6.0-whatsnew-01" width="100%"/>
|
49 |
+
|
50 |
+
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_02.png?raw=true" alt="0.6.0-whatsnew-02" width="100%"/>
|
51 |
+
|
52 |
+
### 0.5.1
|
53 |
+
|
54 |
+
- You can save face models as "safetensors" files (stored in `<sd-web-ui-folder>\models\reactor\faces`) and load them into ReActor, keeping super lightweight face models of the faces you use;
|
55 |
+
- "Face Mask Correction" option - if you encounter some pixelation around face contours, this option will be useful;
|
56 |
+
|
57 |
+
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/face_model_demo_01.jpg?raw=true" alt="0.5.0-whatsnew-01" width="100%"/>
|
58 |
+
|
59 |
+
## Installation
|
60 |
+
|
61 |
+
[Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
|
62 |
+
|
63 |
+
<a name="a1111">If you use [AUTOMATIC1111 web-ui](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
|
64 |
+
|
65 |
+
1. (For Windows Users):
|
66 |
+
- Install **Visual Studio 2022** (Community version, for example - you need this step to build some of dependencies):
|
67 |
+
https://visualstudio.microsoft.com/downloads/
|
68 |
+
- OR only **VS C++ Build Tools** (if you don't need the whole Visual Studio) and select "Desktop Development with C++" under "Workloads -> Desktop & Mobile":
|
69 |
+
https://visualstudio.microsoft.com/visual-cpp-build-tools/
|
70 |
+
- OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. VIII)](#insightfacebuild)
|
71 |
+
2. In web-ui, go to the "Extensions" tab, load "Available" extensions and type "ReActor" in the search field or use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab - and click "Install"
|
72 |
+
3. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
|
73 |
+
4. Check the last message in your SD-WebUI Console:
|
74 |
+
* If you see the message "--- PLEASE, RESTART the Server! ---" - so, do it, stop the Server (CTRL+C or CMD+C) and start it again - or just go to the "Installed" tab, click "Apply and restart UI"
|
75 |
+
* If you see the message "Done!", just reload the UI
|
76 |
+
5. Enjoy!
|
77 |
+
|
78 |
+
<a name="sdnext">If you use [SD.Next](https://github.com/vladmandic/automatic):
|
79 |
+
|
80 |
+
1. Close (stop) your SD WebUI Server if it's running
|
81 |
+
2. (For Windows Users) See the [1st step](#a1111) for Automatic1111 (if you followed [this steps (sec. VIII)](#insightfacebuild) instead - go to the Step 5)
|
82 |
+
3. Go to (Windows)`automatic\venv\Scripts` or (MacOS/Linux)`automatic/venv/bin`, run Terminal or Console (cmd) for that folder and type `activate`
|
83 |
+
4. Run `pip install insightface==0.7.3`
|
84 |
+
5. Run SD.Next, go to the "Extensions" tab and use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab and click "Install"
|
85 |
+
6. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
|
86 |
+
7. Check the last message in your SD.Next Console:
|
87 |
+
* If you see the message "--- PLEASE, RESTART the Server! ---" - stop the Server (CTRL+C or CMD+C) or just close your console
|
88 |
+
8. Go to the `automatic\extensions\sd-webui-reactor` directory - if you see there `models\insightface` folder with the file `inswapper_128.onnx`, just move the file to the `automatic\models\insightface` folder
|
89 |
+
9. Run your SD.Next WebUI and enjoy!
|
90 |
+
|
91 |
+
<a name="colab">If you use [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
|
92 |
+
|
93 |
+
1. In active WebUI, go to the "Extensions" tab, load "Available" extensions and type "ReActor" in the search field or use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab - and click "Install"
|
94 |
+
2. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
|
95 |
+
3. When you see the message "--- PLEASE, RESTART the Server! ---" (in your Colab Notebook Start UI section "Start Cagliostro Colab UI") - just go to the "Installed" tab and click "Apply and restart UI"
|
96 |
+
4. Enjoy!
|
97 |
+
|
98 |
+
## Features
|
99 |
+
|
100 |
+
- Very fast and accurate **face replacement (face swap)** in images
|
101 |
+
- **Multiple faces support**
|
102 |
+
- **Gender detection**
|
103 |
+
- Ability to **save original images** (made before swapping)
|
104 |
+
- **Face restoration** of a swapped face
|
105 |
+
- **Upscaling** of a resulting image
|
106 |
+
- Saving ans loading **Safetensors Face Models**
|
107 |
+
- **Facial Mask Correction** to avoid any pixelation around face contours
|
108 |
+
- Ability to set the **Postprocessing order**
|
109 |
+
- **100% compatibility** with different **SD WebUIs**: Automatic1111, SD.Next, Cagliostro Colab UI
|
110 |
+
- **Fast performance** even with CPU, ReActor for SD WebUI is absolutely not picky about how powerful your GPU is
|
111 |
+
- **CUDA** acceleration support since version 0.5.0
|
112 |
+
- **[API](/API.md) support**: both SD WebUI built-in and external (via POST/GET requests)
|
113 |
+
- **ComfyUI [support](https://github.com/Gourieff/comfyui-reactor-node)**
|
114 |
+
- **Mac M1/M2 [support](https://github.com/Gourieff/sd-webui-reactor/issues/42)**
|
115 |
+
- Console **log level control**
|
116 |
+
- **NSFW filter free** (this extension is aimed at highly developed intellectual people, not at perverts; our society must be oriented on its way towards the highest standards, not the lowest - this is the essence of development and evolution; so, my position is - that mature-minded people are clever enough to understand for themselves what is good and what is bad and take full responsibility for personal actions; for others - no "filters" will help until they do understand how Universe works)
|
117 |
+
|
118 |
+
## Usage
|
119 |
+
|
120 |
+
> Using this software you are agree with [disclaimer](#disclaimer)
|
121 |
+
|
122 |
+
1. Under "ReActor" drop-down menu, import an image containing a face;
|
123 |
+
2. Turn on the "Enable" checkbox;
|
124 |
+
3. That's it, now the generated result will have the face you selected.
|
125 |
+
|
126 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
|
127 |
+
|
128 |
+
### Face Indexes
|
129 |
+
|
130 |
+
ReActor detects faces in images in the following order:<br>
|
131 |
+
left->right, top->bottom
|
132 |
+
|
133 |
+
And if you need to specify faces, you can set indexes for source and input images.
|
134 |
+
|
135 |
+
Index of the first detected face is 0.
|
136 |
+
|
137 |
+
You can set indexes in the order you need.<br>
|
138 |
+
E.g.: 0,1,2 (for Source); 1,0,2 (for Input).<br>
|
139 |
+
This means: the second Input face (index = 1) will be swapped by the first Source face (index = 0) and so on.
|
140 |
+
|
141 |
+
### Genders
|
142 |
+
|
143 |
+
You can specify the gender to detect in images.<br>
|
144 |
+
ReActor will swap a face only if it meets the given condition.
|
145 |
+
|
146 |
+
### The result face is blurry
|
147 |
+
Use the "Restore Face" option. You can also try the "Upscaler" option or for more finer control, use an upscaler from the "Extras" tab.
|
148 |
+
You can also set the postproduction order (from 0.1.0 version):
|
149 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
|
150 |
+
|
151 |
+
*The old logic was the opposite (Upscale -> then Restore), resulting in worse face quality (and big texture differences) after upscaling.*
|
152 |
+
|
153 |
+
### There are multiple faces in result
|
154 |
+
Select the face numbers you wish to swap using the "Comma separated face number(s)" option for swap-source and result images. You can use different index order.
|
155 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
|
156 |
+
|
157 |
+
### ~~The result is totally black~~
|
158 |
+
~~This means NSFW filter detected that your image is NSFW.~~
|
159 |
+
|
160 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
|
161 |
+
|
162 |
+
### Img2Img
|
163 |
+
|
164 |
+
You can choose to activate the swap on the source image or on the generated image, or on both using the checkboxes. Activating on source image allows you to start from a given base and apply the diffusion process to it.
|
165 |
+
|
166 |
+
ReActor works with Inpainting - but only the masked part will be swapped.<br>Please use with the "Only masked" option for "Inpaint area" if you enabled "Upscaler". Otherwise use the upscale option via the Extras tab or via the Script loader (below the screen) with "SD upscale" or "Ultimate SD upscale".
|
167 |
+
|
168 |
+
### Extras Tab
|
169 |
+
|
170 |
+
From the version 0.5.0 you can use ReActor via the Extras Tab. It gives a superfast perfomance and ability to swap face2image avoiding SD pipeline that can cause smushing of original image's details
|
171 |
+
|
172 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
|
173 |
+
|
174 |
+
## API
|
175 |
+
|
176 |
+
You can use ReActor with the built-in Webui API or via an external API.
|
177 |
+
|
178 |
+
Please follow **[this](/API.md)** page for the detailed instruction.
|
179 |
+
|
180 |
+
## Troubleshooting
|
181 |
+
|
182 |
+
### **I. "You should at least have one model in models directory"**
|
183 |
+
|
184 |
+
Please, check the path where "inswapper_128.onnx" model is stored. It must be inside the folder `stable-diffusion-webui\models\insightface`. Move the model there if it's stored in a different directory.
|
185 |
+
|
186 |
+
### **II. Any problems with installing Insightface or other dependencies**
|
187 |
+
|
188 |
+
(for Mac M1/M2 users) If you get errors when trying to install Insightface - please read https://github.com/Gourieff/sd-webui-reactor/issues/42
|
189 |
+
|
190 |
+
(for Windows Users) If you have VS C++ Build Tools or MS VS 2022 installed but still have a problem, then try the next step:
|
191 |
+
1. Close (stop) your SD WebUI Server and start it again
|
192 |
+
|
193 |
+
(for Any OS Users) If the problem still there, then do the following:
|
194 |
+
1. Close (stop) your SD WebUI Server if it's running
|
195 |
+
2. Go to (Windows)`venv\Lib\site-packages` folder or (MacOS/Linux)`venv/lib/python3.10/site-packages`
|
196 |
+
3. If you see any folders with names start from `~` (e.g. "~rotobuf") - delete them
|
197 |
+
4. Go to (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin`
|
198 |
+
5. Run Terminal or Console (cmd) for that folder and type `activate`
|
199 |
+
6. Update your pip at first: `pip install -U pip`
|
200 |
+
7. Then one-by-one:
|
201 |
+
- `pip install insightface==0.7.3`
|
202 |
+
- `pip install onnx`
|
203 |
+
- `pip install "onnxruntime-gpu>=1.16.1"`
|
204 |
+
- `pip install opencv-python`
|
205 |
+
- `pip install tqdm`
|
206 |
+
8. Type `deactivate`, you can close your Terminal or Console and start your SD WebUI, ReActor should start OK - if not, welcome to the Issues section.
|
207 |
+
|
208 |
+
### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
|
209 |
+
|
210 |
+
First of all - you need to disable any other Roop-based extensions:
|
211 |
+
- Go to 'Extensions -> Installed' tab and uncheck any Roop-based extensions except this one
|
212 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>
|
213 |
+
- Click 'Apply and restart UI'
|
214 |
+
|
215 |
+
Alternative solutions:
|
216 |
+
- https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243
|
217 |
+
- https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (can be actual, if you use Vladmandic SD.Next)
|
218 |
+
|
219 |
+
### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
|
220 |
+
|
221 |
+
Probably, you need to disable the "SD-CN-Animation" extension (or perhaps some another that causes the conflict)
|
222 |
+
|
223 |
+
### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed" OR "AttributeError: 'NoneType' object has no attribute 'get'" OR "AttributeError: 'FaceSwapScript' object has no attribute 'save_original'"**
|
224 |
+
|
225 |
+
This error may occur if there's smth wrong with the model file `inswapper_128.onnx`
|
226 |
+
|
227 |
+
Try to download it manually from [here](https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx)
|
228 |
+
and put it to the `stable-diffusion-webui\models\insightface` replacing existing one
|
229 |
+
|
230 |
+
### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" OR "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
|
231 |
+
|
232 |
+
1. Close (stop) your SD WebUI Server if it's running
|
233 |
+
2. Go to the (Windows)`venv\Lib\site-packages` or (MacOS/Linux)`venv/lib/python3.10/site-packages` and see if there are any folders with names start from "~" (for example "~rotobuf"), delete them
|
234 |
+
3. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
|
235 |
+
4. Then:
|
236 |
+
- `python -m pip install -U pip`
|
237 |
+
- `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`
|
238 |
+
- `pip install "onnxruntime-gpu>=1.16.1"`
|
239 |
+
|
240 |
+
If it didn't help - it seems that you have another extension reinstalling `onnxruntime` when SD WebUI checks requirements. Please see your extensions list. Some extensions can causes reinstalling of `onnxruntime-gpu` to `onnxruntime<1.16.1` every time SD WebUI runs.<br>ORT 1.16.0 has a bug https://github.com/microsoft/onnxruntime/issues/17631 - don't install it!
|
241 |
+
|
242 |
+
### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
|
243 |
+
|
244 |
+
1. Close (stop) your SD WebUI Server if it's running
|
245 |
+
2. Go to the (Windows)`venv\Lib\site-packages` or (MacOS/Linux)`venv/lib/python3.10/site-packages` and see if there are any folders with names start from "~" (for example "~rotobuf"), delete them
|
246 |
+
3. Go to the "google" folder (inside the "site-packages") and delete any folders there with names start from "~"
|
247 |
+
4. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
|
248 |
+
5. Then:
|
249 |
+
- `python -m pip install -U pip`
|
250 |
+
- `pip uninstall protobuf`
|
251 |
+
- `pip install "protobuf>=3.20.3"`
|
252 |
+
|
253 |
+
If this method doesn't help - there is some other extension that has a wrong version of protobuf dependence and SD WebUI installs it on a startup requirements check
|
254 |
+
|
255 |
+
<a name="insightfacebuild">
|
256 |
+
|
257 |
+
### **VIII. (For Windows users) If you still cannot build Insightface for some reasons or just don't want to install Visual Studio or VS C++ Build Tools - do the following:**
|
258 |
+
|
259 |
+
1. Close (stop) your SD WebUI Server if it's running
|
260 |
+
2. Download and put [prebuilt Insightface package](https://github.com/Gourieff/sd-webui-reactor/raw/main/example/insightface-0.7.3-cp310-cp310-win_amd64.whl) into the stable-diffusion-webui (or SD.Next) root folder where you have "webui-user.bat" file or (A1111 Portable) "run.bat"
|
261 |
+
3. From stable-diffusion-webui (or SD.Next) root folder run CMD and `.\venv\Scripts\activate`<br>OR<br>(A1111 Portable) Run CMD
|
262 |
+
4. Then update your PIP: `python -m pip install -U pip`<br>OR<br>(A1111 Portable)`system\python\python.exe -m pip install -U pip`
|
263 |
+
5. Then install Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`<br>OR<br>(A1111 Portable)`system\python\python.exe -m pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`
|
264 |
+
6. Enjoy!
|
265 |
+
|
266 |
+
### **IX. 07-August-23 Update problem**
|
267 |
+
|
268 |
+
If after `git pull` you see the message: `Merge made by the 'recursive' strategy` and then when you check `git status` you see `Your branch is ahead of 'origin/main' by`
|
269 |
+
|
270 |
+
Please do the next:
|
271 |
+
|
272 |
+
Inside the folder `extensions\sd-webui-reactor` run Terminal or Console (cmd) and then:
|
273 |
+
- `git reset f48bdf1 --hard`
|
274 |
+
- `git pull`
|
275 |
+
|
276 |
+
OR
|
277 |
+
|
278 |
+
Just delete the folder `sd-webui-reactor` inside the `extensions` directory and then run Terminal or Console (cmd) and type `git clone https://github.com/Gourieff/sd-webui-reactor`
|
279 |
+
|
280 |
+
### **X. StabilityMatrix Issues**
|
281 |
+
|
282 |
+
If you encounter any issues with installing this extension in the StabilityMatrix package manager - read here how to solve: https://github.com/Gourieff/sd-webui-reactor/issues/129#issuecomment-1768210875
|
283 |
+
|
284 |
+
## Updating
|
285 |
+
|
286 |
+
A good and quick way to check for Extensions updates: https://github.com/Gourieff/sd-webui-extensions-updater
|
287 |
+
|
288 |
+
## ComfyUI
|
289 |
+
|
290 |
+
You can use ReActor with ComfyUI.<br>
|
291 |
+
For the installation instruction follow the [ReActor Node repo](https://github.com/Gourieff/comfyui-reactor-node)
|
292 |
+
|
293 |
+
## Disclaimer
|
294 |
+
|
295 |
+
This software is meant to be a productive contribution to the rapidly growing AI-generated media industry. It will help artists with tasks such as animating a custom character or using the character as a model for clothing etc.
|
296 |
+
|
297 |
+
The developers of this software are aware of its possible unethical applicaitons and are committed to take preventative measures against them. We will continue to develop this project in the positive direction while adhering to law and ethics.
|
298 |
+
|
299 |
+
Users of this software are expected to use this software responsibly while abiding the local law. If face of a real person is being used, users are suggested to get consent from the concerned person and clearly mention that it is a deepfake when posting content online. **Developers and Contributors of this software are not responsible for actions of end-users.**
|
300 |
+
|
301 |
+
By using this extension you are agree not to create any content that:
|
302 |
+
- violates any laws;
|
303 |
+
- causes any harm to a person or persons;
|
304 |
+
- propogates (spreads) any information (both public or personal) or images (both public or personal) which could be meant for harm;
|
305 |
+
- spreads misinformation;
|
306 |
+
- targets vulnerable groups of people.
|
307 |
+
|
308 |
+
This software utilizes the pre-trained models `buffalo_l` and `inswapper_128.onnx`, which are provided by [InsightFace](https://github.com/deepinsight/insightface/). These models are included under the following conditions:
|
309 |
+
|
310 |
+
[From insighface licence](https://github.com/deepinsight/insightface/tree/master/python-package): The InsightFace’s pre-trained models are available for non-commercial research purposes only. This includes both auto-downloading models and manually downloaded models.
|
311 |
+
|
312 |
+
Users of this software must strictly adhere to these conditions of use. The developers and maintainers of this software are not responsible for any misuse of InsightFace’s pre-trained models.
|
313 |
+
|
314 |
+
Please note that if you intend to use this software for any commercial purposes, you will need to train your own models or find models that can be used commercially.
|
315 |
+
|
316 |
+
### Models Hashsum
|
317 |
+
|
318 |
+
#### Safe-to-use models have the folowing hash:
|
319 |
+
|
320 |
+
inswapper_128.onnx
|
321 |
+
```
|
322 |
+
MD5:a3a155b90354160350efd66fed6b3d80
|
323 |
+
SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
|
324 |
+
```
|
325 |
+
|
326 |
+
1k3d68.onnx
|
327 |
+
|
328 |
+
```
|
329 |
+
MD5:6fb94fcdb0055e3638bf9158e6a108f4
|
330 |
+
SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
|
331 |
+
```
|
332 |
+
|
333 |
+
2d106det.onnx
|
334 |
+
|
335 |
+
```
|
336 |
+
MD5:a3613ef9eb3662b4ef88eb90db1fcf26
|
337 |
+
SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
|
338 |
+
```
|
339 |
+
|
340 |
+
det_10g.onnx
|
341 |
+
|
342 |
+
```
|
343 |
+
MD5:4c10eef5c9e168357a16fdd580fa8371
|
344 |
+
SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
|
345 |
+
```
|
346 |
+
|
347 |
+
genderage.onnx
|
348 |
+
|
349 |
+
```
|
350 |
+
MD5:81c77ba87ab38163b0dec6b26f8e2af2
|
351 |
+
SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
|
352 |
+
```
|
353 |
+
|
354 |
+
w600k_r50.onnx
|
355 |
+
|
356 |
+
```
|
357 |
+
MD5:80248d427976241cbd1343889ed132b3
|
358 |
+
SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
|
359 |
+
```
|
360 |
+
|
361 |
+
**Please check hashsums if you download these models from unverified (or untrusted) sources**
|
extensions/sd-webui-reactor/README_RU.md
ADDED
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<div align="center">
|
2 |
+
|
3 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_RU.png?raw=true" alt="logo" width="180px"/>
|
4 |
+
|
5 |
+
![Version](https://img.shields.io/badge/версия-0.6.0-brightgreen?style=for-the-badge&labelColor=darkgreen)
|
6 |
+
|
7 |
+
<a href="https://boosty.to/artgourieff" target="_blank">
|
8 |
+
<img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Поддержать проект на Boosty"/>
|
9 |
+
<br>
|
10 |
+
<sup>
|
11 |
+
Поддержать проект
|
12 |
+
</sup>
|
13 |
+
</a>
|
14 |
+
|
15 |
+
<hr>
|
16 |
+
|
17 |
+
[![Commit activity](https://img.shields.io/github/commit-activity/t/Gourieff/sd-webui-reactor/main?cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/commits/main)
|
18 |
+
![Last commit](https://img.shields.io/github/last-commit/Gourieff/sd-webui-reactor/main?cacheSeconds=0)
|
19 |
+
[![Opened issues](https://img.shields.io/github/issues/Gourieff/sd-webui-reactor?color=red)](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
|
20 |
+
[![Closed issues](https://img.shields.io/github/issues-closed/Gourieff/sd-webui-reactor?color=green&cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/issues?q=is%3Aissue+is%3Aclosed)
|
21 |
+
![License](https://img.shields.io/github/license/Gourieff/sd-webui-reactor)
|
22 |
+
|
23 |
+
[English](/README.md) | Русский
|
24 |
+
|
25 |
+
# ReActor для Stable Diffusion
|
26 |
+
### Расширение для быстрой и простой замены лиц на любых изображениях. Без фильтра цензуры, 18+, используйте под вашу собственную [ответственность](#disclaimer)
|
27 |
+
|
28 |
+
---
|
29 |
+
<b>
|
30 |
+
<a href="#latestupdate">Что нового</a> | <a href="#installation">Установка</a> | <a href="#features">Возможности</a> | <a href="#usage">Использование</a> | <a href="#api">API</a> | <a href="#troubleshooting">Устранение проблем</a> | <a href="#updating">Обновление</a> | <a href="#comfyui">ComfyUI</a> | <a href="#disclaimer">Ответственность</a>
|
31 |
+
</b>
|
32 |
+
</div>
|
33 |
+
|
34 |
+
---
|
35 |
+
|
36 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
|
37 |
+
|
38 |
+
<a name="latestupdate">
|
39 |
+
|
40 |
+
## Что нового в последних обновлениях
|
41 |
+
|
42 |
+
### 0.6.0 <sub><sup>ALPHA1
|
43 |
+
|
44 |
+
- UI переработан
|
45 |
+
- Появилась возможность загружать несколько исходных изображений с лицами или задавать путь к папке, содержащей такие изображения
|
46 |
+
|
47 |
+
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_01.png?raw=true" alt="0.6.0-whatsnew-01" width="100%"/>
|
48 |
+
|
49 |
+
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_02.png?raw=true" alt="0.6.0-whatsnew-02" width="100%"/>
|
50 |
+
|
51 |
+
### 0.5.1
|
52 |
+
|
53 |
+
- Теперь можно сохранять модели лиц в качестве файлов "safetensors" (находятся в `<sd-web-ui-folder>\models\reactor\faces`) и загружать их с ReActor, храня супер легкие модели лиц, которые вы чаще всего используете;
|
54 |
+
- Новые опция "Face Mask Correction" - если вы сталкиваетесь с пикселизацией вокруг контуров лица, эта опция будет полезной;
|
55 |
+
|
56 |
+
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/face_model_demo_01.jpg?raw=true" alt="0.5.0-whatsnew-01" width="100%"/>
|
57 |
+
|
58 |
+
<a name="installation">
|
59 |
+
|
60 |
+
## Установка
|
61 |
+
|
62 |
+
[Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
|
63 |
+
|
64 |
+
<a name="a1111">Если вы используете [AUTOMATIC1111 Web-UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
|
65 |
+
|
66 |
+
1. (Для пользователей Windows):
|
67 |
+
- Установите **Visual Studio 2022** (Например, версию Community - этот шаг нужен для правильной компиляции библиотеки Insightface):
|
68 |
+
https://visualstudio.microsoft.com/downloads/
|
69 |
+
- ИЛИ только **VS C++ Build Tools** (если вам не нужен весь пакет Visual Studio), выберите "Desktop Development with C++" в разделе "Workloads -> Desktop & Mobile":
|
70 |
+
https://visualstudio.microsoft.com/visual-cpp-build-tools/
|
71 |
+
- ИЛИ если же вы не хотите устанавливать что-либо из вышеуказанного - выполните [следующие шаги (пункт VIII)](#insightfacebuild)
|
72 |
+
2. Внутри SD Web-UI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"
|
73 |
+
3. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
|
74 |
+
4. Проверьте последнее сообщение в консоли SD-WebUI:
|
75 |
+
* Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) и запустите его заново - ИЛИ же перейдите во вкладку "Installed", нажмите "Apply and restart UI"
|
76 |
+
* Если вы видите "Done!", просто перезагрузите UI, нажав на "Reload UI"
|
77 |
+
5. Готово!
|
78 |
+
|
79 |
+
<a name="sdnext">Если вы используете [SD.Next](https://github.com/vladmandic/automatic):
|
80 |
+
|
81 |
+
1. Закройте (остановите) SD WebUI Сервер, если он запущен
|
82 |
+
2. (Для пользователей Windows) Смотрите [Шаг 1](#a1111) для Automatic1111 (если же вы следовали [данным шагам (пункт VIII)](#insightfacebuild) вместо этого - переходите к Шагу 5)
|
83 |
+
3. Перейдите в (Windows)`automatic\venv\Scripts` или (MacOS/Linux)`automatic/venv/bin`, запустите Терминал или Консоль (cmd) для данной папки и выполните `activate`
|
84 |
+
4. Выполните `pip install insightface==0.7.3`
|
85 |
+
5. Запустите SD.Next, перейдите во вкладку "Extensions", вставьте эту ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
|
86 |
+
6. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
|
87 |
+
7. Проверьте последнее сообщение в консоли SD.Next:
|
88 |
+
* Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) или просто закройте консоль
|
89 |
+
8. Перейдите в директорию `automatic\extensions\sd-webui-reactor` - если вы видите там папку `models\insightface` с файлом `inswapper_128.onnx` внутри, переместите его в папку `automatic\models\insightface`
|
90 |
+
9. Готово, можете запустить SD.Next WebUI!
|
91 |
+
|
92 |
+
<a name="colab">Если вы используете [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
|
93 |
+
|
94 |
+
1. В активном WebUI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"
|
95 |
+
2. Пожалуйста, подождите некоторое время, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
|
96 |
+
3. Когда вы увидите сообщение "--- PLEASE, RESTART the Server! ---" (в секции "Start UI" вашего ноутбука "Start Cagliostro Colab UI") - перейдите во вкладку "Installed" и нажмите "Apply and restart UI"
|
97 |
+
4. Готово!
|
98 |
+
|
99 |
+
<a name="features">
|
100 |
+
|
101 |
+
## Возможности
|
102 |
+
|
103 |
+
- Быстрая и точна **замена лиц (faceswap)** на изображении
|
104 |
+
- **Поддержка нескольких лиц**
|
105 |
+
- **Определение пола**
|
106 |
+
- Функция **сохранения оригинального изображения** (сгенерированного до замены лица)
|
107 |
+
- **Восстановление лица** после замены
|
108 |
+
- **Увеличение размера** полученного изображения
|
109 |
+
- Сохранение и загрузка **Моделей Лиц типа Safetensors**
|
110 |
+
- **Коррекция Маски Лица** для предотвращения какой-либо пикселизации вокруг контуров лиц
|
111 |
+
- Возможность задать **порядок постобработки**
|
112 |
+
- **100% совместимость** с разными **SD WebUI**: Automatic1111, SD.Next, Cagliostro Colab UI
|
113 |
+
- **Отличная производительность** даже с использованием ЦПУ, ReActor для SD WebUI абсолютно не требователен к мощности вашей видеокарты
|
114 |
+
- **Поддержка CUDA**, начиная с версии 0.5.0
|
115 |
+
- **Поддержка [API](/API.md)**: как встроенного в SD WebUI, так и внешнего (через POST/GET запросы)
|
116 |
+
- **[Поддержка](https://github.com/Gourieff/comfyui-reactor-node) ComfyUI**
|
117 |
+
- **[Поддержка](https://github.com/Gourieff/sd-webui-reactor/issues/42) компьютеров Mac M1/M2**
|
118 |
+
- **Регулировка уровня логов** консоли
|
119 |
+
- **Без NSFW фильтров** (данное расширение адресовано высокоразвитым интеллектуальным людям, а не извращенцам; наше общество должно быть ориентировано на своём пути на высшие стандарты, а не на низшие - в этом состоит суть развития и эволюции человеческого общества; поэтому, моя позиция такова - что зрелые умом люди достаточно разумны, чтобы понимать, что есть хорошо, а что плохо и нести полную ответственность за собственные действия; для прочих - никакие "фильтры" не помогут, пока эти люди сами не поймут, как работает Вселенная)
|
120 |
+
|
121 |
+
<a name="usage">
|
122 |
+
|
123 |
+
## Использование
|
124 |
+
|
125 |
+
> Используя данное программное обеспечение, вы соглашаетесь с [ответственностью](#disclaimer)
|
126 |
+
|
127 |
+
1. В раскрывающимся меню "ReActor" импортируйте изображение, содержащее лицо;
|
128 |
+
2. Установите флажок "Enable";
|
129 |
+
3. Готово, теперь результат будет иметь то лицо, которое вы выбрали.
|
130 |
+
|
131 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
|
132 |
+
|
133 |
+
### Индексы Лиц (Face Indexes)
|
134 |
+
|
135 |
+
ReActor определяет лица на изображении в следующей последовательности:<br>
|
136 |
+
слева-направо, сверху-вниз.
|
137 |
+
|
138 |
+
Если вам нужно заменить определенное лицо, вы можете указать индекс для исходного (source, с лицом) и входного (input, где будет замена лица) изображений.
|
139 |
+
|
140 |
+
Индекс первого обнаруженного лица - 0.
|
141 |
+
|
142 |
+
Вы можете задать индексы в том порядке, который вам нужен.<br>
|
143 |
+
Например: 0,1,2 (для Source); 1,0,2 (для Input).<br>
|
144 |
+
Это означает, что: второе лицо из Input (индекс = 1) будет заменено первым лицом из Source (индекс = 0) и так далее.
|
145 |
+
|
146 |
+
### Определение Пола
|
147 |
+
|
148 |
+
Вы можете обозначить, какой пол нужно определять на изображении.<br>
|
149 |
+
ReActor заменит только то лицо, которое удовлетворяет заданному условию.
|
150 |
+
|
151 |
+
### Если лицо получилось нечётким
|
152 |
+
Используйте опцию "Restore Face". Также можете попробовать опцию "Upscaler". Для более точного контроля параметров используйте Upscaler во вкладке "Extras".
|
153 |
+
Также вы можете установить порядок постобработки (начиная с версии 0.1.0):
|
154 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
|
155 |
+
|
156 |
+
*Прежняя логика была противоположенной (Upscale -> затем Restore), что приводило к более худшему качеству изображения лица (а также к значительной разнице текстур) после увеличения.*
|
157 |
+
|
158 |
+
### Результат имеет несколько лиц
|
159 |
+
Выберите номера лиц, которые нужно поменять, используя поля "Comma separated face number(s)" для исходного изображения лица и для результата. Можно устанавливать любой, необходимый вам, порядок лиц.
|
160 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
|
161 |
+
|
162 |
+
### ~~Результат получился чёрным~~
|
163 |
+
~~Это значит, что сработал NSFW фильтр.~~
|
164 |
+
|
165 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
|
166 |
+
|
167 |
+
### Img2Img
|
168 |
+
|
169 |
+
Используйте эту вкладку, чтобы заменить лицо на уже готовом изображении (флажок "Swap in source image") или на сгенерированном на основе готового (флажок "Swap in generated image").
|
170 |
+
|
171 |
+
Inpainting также работает, но замена лица происходит только в области маски.<br>Пожалуйста, используйте с опцией "Only masked" для "Inpaint area", если вы применяете "Upscaler". Иначе, используйте функцию увеличения (апскейла) через вкладку "Extras" или через опциональный загрузчик "Script" (внизу экрана), применив "SD upscale" или "Ultimate SD upscale".
|
172 |
+
|
173 |
+
### Extras
|
174 |
+
|
175 |
+
Начиная с версии 0.5.0, вы можете использовать ReActor через вкладку Extras, что даёт очень быструю производительность и возможность замены лиц в обход пайплайна SD, что иногда вызывает размытие или искажение деталей оригинального изображения
|
176 |
+
|
177 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
|
178 |
+
|
179 |
+
## API
|
180 |
+
|
181 |
+
Вы можете использовать ReActor как со встроенным SD Webui API так и через внешнее API.
|
182 |
+
|
183 |
+
Подробная инструкция **[здесь](/API.md)**.
|
184 |
+
|
185 |
+
<a name="troubleshooting">
|
186 |
+
|
187 |
+
## Устранение проблем
|
188 |
+
|
189 |
+
### **I. "You should at least have one model in models directory"**
|
190 |
+
|
191 |
+
Проверьте путь, где хранится модель "inswapper_128.onnx". Файл должен находиться в папке `stable-diffusion-webui\models\insightface`. Переместите модель туда, если она находится в какой-то иной директории.
|
192 |
+
|
193 |
+
### **II. Какие-либо проблемы с установкой Insightface или прочих пакетов**
|
194 |
+
|
195 |
+
(Для пользователей Mac M1/M2) Если вы получаете ошибки в ходе установки Insightface - читайте https://github.com/Gourieff/sd-webui-reactor/issues/42
|
196 |
+
|
197 |
+
(Для пользователей Windows) Если VS C++ Build Tools или MS VS 2022 установлены но вы видите ошибки, связанные с отсутствием Insightface, попробуйте следующее:
|
198 |
+
1. Закройте (остановите) SD WebUI Сервер и запустите его снова (возможно, не прошла инициализация пакета после его установки)
|
199 |
+
|
200 |
+
(Для пользователей любых ОС) Попробуйте следующее:
|
201 |
+
1. Закройте (остановите) SD WebUI Сервер, если он запущен
|
202 |
+
2. Перейдите в папку (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages`
|
203 |
+
3. Если вы видите к-л папки с именами, начинающимися с `~` (например, "~rotobuf") - удалите их
|
204 |
+
4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`
|
205 |
+
5. Откройте Терминал или Консоль (cmd) для этой папки и выполните `activate`
|
206 |
+
6. Для начала обновите pip: `pip install -U pip`
|
207 |
+
7. Далее:
|
208 |
+
- `pip install insightface==0.7.3`
|
209 |
+
- `pip install onnx`
|
210 |
+
- `pip install "onnxruntime-gpu>=1.16.1"`
|
211 |
+
- `pip install opencv-python`
|
212 |
+
- `pip install tqdm`
|
213 |
+
8. Выполните `deactivate`, закройте Терминал или Консоль и запустите SD WebUI, ReActor должен запуститься без к-л проблем - если же нет, добро пожаловать в раздел "Issues".
|
214 |
+
|
215 |
+
### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
|
216 |
+
|
217 |
+
Для начала отключите любые другие Roop-подобные расширения:
|
218 |
+
- Перейдите в 'Extensions -> Installed' и снимите флажок с ненужных:
|
219 |
+
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>
|
220 |
+
- Нажмите 'Apply and restart UI'
|
221 |
+
|
222 |
+
Альтернативные решения:
|
223 |
+
- https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243
|
224 |
+
- https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (актуально для Vladmandic SD.Next)
|
225 |
+
|
226 |
+
### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
|
227 |
+
|
228 |
+
Отключите расширение "SD-CN-Animation" (или какое-либо другое, вызывающее конфликт)
|
229 |
+
|
230 |
+
### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed" ИЛИ "AttributeError: 'NoneType' object has no attribute 'get'" ИЛИ "AttributeError: 'FaceSwapScript' object has no attribute 'save_original'"**
|
231 |
+
|
232 |
+
Эта ошибка появляется, если что-то не так с файлом модели `inswapper_128.onnx`.
|
233 |
+
|
234 |
+
Скачайте вручную по ссылке [here](https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx)
|
235 |
+
и сохраните в директорию `stable-diffusion-webui\models\insightface`, заменив имеющийся файл.
|
236 |
+
|
237 |
+
### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" ИЛИ "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
|
238 |
+
|
239 |
+
1. Закройте (остановите) SD WebUI Сервер, если он запущен
|
240 |
+
2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
|
241 |
+
3. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
|
242 |
+
4. Затем:
|
243 |
+
- `python -m pip install -U pip`
|
244 |
+
- `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`
|
245 |
+
- `pip install "onnxruntime-gpu>=1.16.1"`
|
246 |
+
|
247 |
+
Если это не помогло - значит какое-то другое расширение переустанавливает `onnxruntime` всякий раз, когда SD WebUI проверяет требования пакетов. Внимательно посмотрите список активных расширений. Некоторые расширения могут вызывать переустановку `onnxruntime-gpu` на версию `onnxruntime<1.16.1` при каждом запуске SD WebUI.<br>ORT 1.16.0 выкатили с ошибкой https://github.com/microsoft/onnxruntime/issues/17631 - не устанавливайте её!
|
248 |
+
|
249 |
+
### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
|
250 |
+
|
251 |
+
1. Закройте (остановите) SD WebUI Сервер, если он запущен
|
252 |
+
2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
|
253 |
+
3. Перейдите в папку "google" (внутри "site-packages") и удалите любые папки с именам, начинающимися на "~"
|
254 |
+
4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
|
255 |
+
5. Затем:
|
256 |
+
- `python -m pip install -U pip`
|
257 |
+
- `pip uninstall protobuf`
|
258 |
+
- `pip install "protobuf>=3.20.3"`
|
259 |
+
|
260 |
+
Если это не помгло - значит, есть к-л другое расширение, которое использует неподходящую версию пакета protobuf, и SD WebUI устанавливает эту версию при каждом запуске.
|
261 |
+
|
262 |
+
<a name="insightfacebuild">
|
263 |
+
|
264 |
+
### **VIII. (Для пользователей Windows) Если вы до сих пор не можете установить пакет Insightface по каким-то причинам или же просто не желаете устанавливать Visual Studio или VS C++ Build Tools - сделайте следующее:**
|
265 |
+
|
266 |
+
1. Закройте (остановите) SD WebUI Сервер, если он запущен
|
267 |
+
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" или (A1111 Portable) "run.bat"
|
268 |
+
3. Из корневой директории откройте Консоль (CMD) и выполните `.\venv\Scripts\activate`<br>ИЛИ<br>(A1111 Portable) Откройте Консоль (CMD)
|
269 |
+
4. Обновите PIP: `python -m pip install -U pip`<br>ИЛИ<br>(A1111 Portable)`system\python\python.exe -m pip install -U pip`
|
270 |
+
5. Затем установите Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`<br>ИЛИ<br>(A1111 Portable)`system\python\python.exe -m pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`
|
271 |
+
6. Готово!
|
272 |
+
|
273 |
+
### **IX. Ошибка обновления 07-Август-23**
|
274 |
+
|
275 |
+
Если после очередного `git pull` вы получили сообщение: `Merge made by the 'recursive' strategy` и затем, когда проверяете статус репозитория через `git status`, вы видите `Your branch is ahead of 'origin/main' by`
|
276 |
+
|
277 |
+
Выполните следующее:
|
278 |
+
|
279 |
+
Внутри папки `extensions\sd-webui-reactor` запустите Т��рминал или Консоль (cmd) и затем:
|
280 |
+
- `git reset f48bdf1 --hard`
|
281 |
+
- `git pull`
|
282 |
+
|
283 |
+
ИЛИ:
|
284 |
+
|
285 |
+
Полностью удалите папку `sd-webui-reactor` внутри директории `extensions`, запустите Терминал или Консоль (cmd) и выполните `git clone https://github.com/Gourieff/sd-webui-reactor`
|
286 |
+
|
287 |
+
### **X. Ошибки установки в StabilityMatrix**
|
288 |
+
|
289 |
+
Если вы столкнулись с ошибками при установки данного расширения в пакетном менеджере StabilityMatrix - изучите информацию по ссылке: https://github.com/Gourieff/sd-webui-reactor/issues/129#issuecomment-1768210875
|
290 |
+
|
291 |
+
<a name="updating">
|
292 |
+
|
293 |
+
## Обновление
|
294 |
+
|
295 |
+
Самый простой и удобный способ обновления SD WebUI и расширений: https://github.com/Gourieff/sd-webui-extensions-updater
|
296 |
+
|
297 |
+
## ComfyUI
|
298 |
+
|
299 |
+
Вы можете использовать ReActor с ComfyUI<br>
|
300 |
+
Инструкция здесь: [ReActor Node](https://github.com/Gourieff/comfyui-reactor-node)
|
301 |
+
|
302 |
+
<a name="disclaimer">
|
303 |
+
|
304 |
+
## Ответственность
|
305 |
+
|
306 |
+
Это программное обеспечение призвано стать продуктивным вкладом в быстрорастущую медиаиндустрию на основе генеративных сетей и искусственного интеллекта. Данное ПО поможет художникам в решении таких задач, как анимация собственного персонажа или использование персонажа в качестве модели для одежды и т.д.
|
307 |
+
|
308 |
+
Разработчики этого программного обеспечения осведомлены о возможных неэтичных применениях и обязуются принять против этого превентивные меры. Мы продолжим развивать этот проект в позитивном направлении, придерживаясь закона и этики.
|
309 |
+
|
310 |
+
Подразумевается, что пользователи этого программного обеспечения будут использовать его ответственно, соблюдая локальное законодательство. Если используется лицо реального человека, пользователь обязан получить согласие заинтересованного лица и четко указать, что это дипфейк при размещении контента в Интернете. **Разработчики и Со-авторы данного программного обеспечения не несут ответственности за действия конечных пользователей.**
|
311 |
+
|
312 |
+
Используя данное расширение, вы соглашаетесь не создавать материалы, которые:
|
313 |
+
- нарушают какие-либо действующие законы тех или иных государств или международных организаций;
|
314 |
+
- причиняют какой-либо вред человеку или лицам;
|
315 |
+
- пропагандируют любую информацию (как общедоступную, так и личную) или изображения (как общедоступные, так и личные), которые могут быть направлены на причинение вреда;
|
316 |
+
- используются для распространения дезинформации;
|
317 |
+
- нацелены на уязвимые группы людей.
|
318 |
+
|
319 |
+
Данное программное обеспечение использует предварительно обученные модели `buffalo_l` и `inswapper_128.onnx`, представленные разработчиками [InsightFace](https://github.com/deepinsight/insightface/). Эти модели распространяются при следующих условиях:
|
320 |
+
|
321 |
+
[Перевод из текста лицензии insighface](https://github.com/deepinsight/insightface/tree/master/python-package): Предварительно обученные модели InsightFace доступны только для некоммерческих исследовательских целей. Сюда входят как модели с автоматической загрузкой, так и модели, загруженные вручную.
|
322 |
+
|
323 |
+
Пользователи данного программного обеспечения должны строго соблюдать данные условия использования. Разработчики и Со-авторы данного программного продукта не несут ответ��твенности за неправильное использование предварительно обученных моделей InsightFace.
|
324 |
+
|
325 |
+
Обратите внимание: если вы собираетесь использовать это программное обеспечение в каких-либо коммерческих целях, вам необходимо будет обучить свои собственные модели или найти модели, которые можно использовать в коммерческих целях.
|
326 |
+
|
327 |
+
### Хэш файлов моделей
|
328 |
+
|
329 |
+
#### Безопасные для использования модели имеют следующий хэш:
|
330 |
+
|
331 |
+
inswapper_128.onnx
|
332 |
+
```
|
333 |
+
MD5:a3a155b90354160350efd66fed6b3d80
|
334 |
+
SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
|
335 |
+
```
|
336 |
+
|
337 |
+
1k3d68.onnx
|
338 |
+
|
339 |
+
```
|
340 |
+
MD5:6fb94fcdb0055e3638bf9158e6a108f4
|
341 |
+
SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
|
342 |
+
```
|
343 |
+
|
344 |
+
2d106det.onnx
|
345 |
+
|
346 |
+
```
|
347 |
+
MD5:a3613ef9eb3662b4ef88eb90db1fcf26
|
348 |
+
SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
|
349 |
+
```
|
350 |
+
|
351 |
+
det_10g.onnx
|
352 |
+
|
353 |
+
```
|
354 |
+
MD5:4c10eef5c9e168357a16fdd580fa8371
|
355 |
+
SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
|
356 |
+
```
|
357 |
+
|
358 |
+
genderage.onnx
|
359 |
+
|
360 |
+
```
|
361 |
+
MD5:81c77ba87ab38163b0dec6b26f8e2af2
|
362 |
+
SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
|
363 |
+
```
|
364 |
+
|
365 |
+
w600k_r50.onnx
|
366 |
+
|
367 |
+
```
|
368 |
+
MD5:80248d427976241cbd1343889ed132b3
|
369 |
+
SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
|
370 |
+
```
|
371 |
+
|
372 |
+
**Пожалуйста, сравните хэш, если вы скачиваете данные модели из непроверенных источников**
|
extensions/sd-webui-reactor/example/IamSFW.jpg
ADDED
Git LFS Details
|
extensions/sd-webui-reactor/example/api_example.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64, io, requests, json
|
2 |
+
from PIL import Image, PngImagePlugin
|
3 |
+
from datetime import datetime, date
|
4 |
+
|
5 |
+
address = 'http://127.0.0.1:7860'
|
6 |
+
input_file = "extensions\sd-webui-reactor\example\IamSFW.jpg" # Input file path
|
7 |
+
time = datetime.now()
|
8 |
+
today = date.today()
|
9 |
+
current_date = today.strftime('%Y-%m-%d')
|
10 |
+
current_time = time.strftime('%H-%M-%S')
|
11 |
+
output = 'outputs/api/output_'+current_date+'_'+current_time # Output file path + name index
|
12 |
+
try:
|
13 |
+
im = Image.open(input_file)
|
14 |
+
except Exception as e:
|
15 |
+
print(e)
|
16 |
+
finally:
|
17 |
+
print(im)
|
18 |
+
|
19 |
+
img_bytes = io.BytesIO()
|
20 |
+
im.save(img_bytes, format='PNG')
|
21 |
+
img_base64 = base64.b64encode(img_bytes.getvalue()).decode('utf-8')
|
22 |
+
|
23 |
+
# ReActor arguments:
|
24 |
+
args=[
|
25 |
+
img_base64, #0
|
26 |
+
True, #1 Enable ReActor
|
27 |
+
'0', #2 Comma separated face number(s) from swap-source image
|
28 |
+
'0', #3 Comma separated face number(s) for target image (result)
|
29 |
+
'C:\stable-diffusion-webui\models\insightface\inswapper_128.onnx', #4 model path
|
30 |
+
'CodeFormer', #4 Restore Face: None; CodeFormer; GFPGAN
|
31 |
+
1, #5 Restore visibility value
|
32 |
+
True, #7 Restore face -> Upscale
|
33 |
+
'4x_NMKD-Superscale-SP_178000_G', #8 Upscaler (type 'None' if doesn't need), see full list here: http://127.0.0.1:7860/sdapi/v1/script-info -> reactor -> sec.8
|
34 |
+
1.5, #9 Upscaler scale value
|
35 |
+
1, #10 Upscaler visibility (if scale = 1)
|
36 |
+
False, #11 Swap in source image
|
37 |
+
True, #12 Swap in generated image
|
38 |
+
1, #13 Console Log Level (0 - min, 1 - med or 2 - max)
|
39 |
+
0, #14 Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)
|
40 |
+
0, #15 Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)
|
41 |
+
False, #16 Save the original image(s) made before swapping
|
42 |
+
0.8, #17 CodeFormer Weight (0 = maximum effect, 1 = minimum effect), 0.5 - by default
|
43 |
+
False, #18 Source Image Hash Check, True - by default
|
44 |
+
False, #19 Target Image Hash Check, False - by default
|
45 |
+
"CUDA", #20 CPU or CUDA (if you have it), CPU - by default
|
46 |
+
True, #21 Face Mask Correction
|
47 |
+
1, #22 Select Source, 0 - Image, 1 - Face Model, 2 - Source Folder
|
48 |
+
"elena.safetensors", #23 Filename of the face model (from "models/reactor/faces"), e.g. elena.safetensors, don't forger to set #22 to 1
|
49 |
+
"C:\PATH_TO_FACES_IMAGES", #24 The path to the folder containing source faces images, don't forger to set #22 to 2
|
50 |
+
]
|
51 |
+
|
52 |
+
# The args for ReActor can be found by
|
53 |
+
# requests.get(url=f'{address}/sdapi/v1/script-info')
|
54 |
+
|
55 |
+
prompt = "(8k, best quality, masterpiece, highly detailed:1.1),realistic photo of fantastic happy woman,hairstyle of blonde and red short bob hair,modern clothing,cinematic lightning,film grain,dynamic pose,bokeh,dof"
|
56 |
+
|
57 |
+
neg = "ng_deepnegative_v1_75t,(badhandv4:1.2),(worst quality:2),(low quality:2),(normal quality:2),lowres,(bad anatomy),(bad hands),((monochrome)),((grayscale)),(verybadimagenegative_v1.3:0.8),negative_hand-neg,badhandv4,nude,naked,(strabismus),cross-eye,heterochromia,((blurred))"
|
58 |
+
|
59 |
+
payload = {
|
60 |
+
"prompt": prompt,
|
61 |
+
"negative_prompt": neg,
|
62 |
+
"seed": -1,
|
63 |
+
"sampler_name": "DPM++ 2M Karras",
|
64 |
+
"steps": 15,
|
65 |
+
"cfg_scale": 7,
|
66 |
+
"width": 512,
|
67 |
+
"height": 768,
|
68 |
+
"restore_faces": False,
|
69 |
+
"alwayson_scripts": {"reactor":{"args":args}}
|
70 |
+
}
|
71 |
+
|
72 |
+
try:
|
73 |
+
print('Working... Please wait...')
|
74 |
+
result = requests.post(url=f'{address}/sdapi/v1/txt2img', json=payload)
|
75 |
+
except Exception as e:
|
76 |
+
print(e)
|
77 |
+
finally:
|
78 |
+
print('Done! Saving file...')
|
79 |
+
|
80 |
+
if result is not None:
|
81 |
+
r = result.json()
|
82 |
+
n = 0
|
83 |
+
|
84 |
+
for i in r['images']:
|
85 |
+
image = Image.open(io.BytesIO(base64.b64decode(i.split(",",1)[0])))
|
86 |
+
|
87 |
+
png_payload = {
|
88 |
+
"image": "data:image/png;base64," + i
|
89 |
+
}
|
90 |
+
response2 = requests.post(url=f'{address}/sdapi/v1/png-info', json=png_payload)
|
91 |
+
|
92 |
+
pnginfo = PngImagePlugin.PngInfo()
|
93 |
+
pnginfo.add_text("parameters", response2.json().get("info"))
|
94 |
+
output_file = output+'_'+str(n)+'_.png'
|
95 |
+
try:
|
96 |
+
image.save(output_file, pnginfo=pnginfo)
|
97 |
+
except Exception as e:
|
98 |
+
print(e)
|
99 |
+
finally:
|
100 |
+
print(f'{output_file} is saved\nAll is done!')
|
101 |
+
n += 1
|
102 |
+
else:
|
103 |
+
print('Something went wrong...')
|
extensions/sd-webui-reactor/example/api_external.curl
ADDED
The diff for this file is too large to render.
See raw diff
|
|
extensions/sd-webui-reactor/example/api_external.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
extensions/sd-webui-reactor/example/insightface-0.7.3-cp310-cp310-win_amd64.whl
ADDED
Binary file (842 kB). View file
|
|
extensions/sd-webui-reactor/install.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import subprocess
|
2 |
+
import os, sys
|
3 |
+
from typing import Any
|
4 |
+
import pkg_resources
|
5 |
+
from tqdm import tqdm
|
6 |
+
import urllib.request
|
7 |
+
from packaging import version as pv
|
8 |
+
|
9 |
+
try:
|
10 |
+
from modules.paths_internal import models_path
|
11 |
+
except:
|
12 |
+
try:
|
13 |
+
from modules.paths import models_path
|
14 |
+
except:
|
15 |
+
model_path = os.path.abspath("models")
|
16 |
+
|
17 |
+
|
18 |
+
BASE_PATH = os.path.dirname(os.path.realpath(__file__))
|
19 |
+
|
20 |
+
req_file = os.path.join(BASE_PATH, "requirements.txt")
|
21 |
+
|
22 |
+
models_dir = os.path.join(models_path, "insightface")
|
23 |
+
|
24 |
+
# DEPRECATED:
|
25 |
+
# models_dir_old = os.path.join(models_path, "roop")
|
26 |
+
# if os.path.exists(models_dir_old):
|
27 |
+
# if not os.listdir(models_dir_old) and (not os.listdir(models_dir) or not os.path.exists(models_dir)):
|
28 |
+
# os.rename(models_dir_old, models_dir)
|
29 |
+
# else:
|
30 |
+
# import shutil
|
31 |
+
# for file in os.listdir(models_dir_old):
|
32 |
+
# shutil.move(os.path.join(models_dir_old, file), os.path.join(models_dir, file))
|
33 |
+
# try:
|
34 |
+
# os.rmdir(models_dir_old)
|
35 |
+
# except Exception as e:
|
36 |
+
# print(f"OSError: {e}")
|
37 |
+
|
38 |
+
model_url = "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx"
|
39 |
+
model_name = os.path.basename(model_url)
|
40 |
+
model_path = os.path.join(models_dir, model_name)
|
41 |
+
|
42 |
+
def pip_install(*args):
|
43 |
+
subprocess.run([sys.executable, "-m", "pip", "install", *args])
|
44 |
+
|
45 |
+
def pip_uninstall(*args):
|
46 |
+
subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", *args])
|
47 |
+
|
48 |
+
def is_installed (
|
49 |
+
package: str, version: str | None = None, strict: bool = True
|
50 |
+
):
|
51 |
+
has_package = None
|
52 |
+
try:
|
53 |
+
has_package = pkg_resources.get_distribution(package)
|
54 |
+
if has_package is not None:
|
55 |
+
installed_version = has_package.version
|
56 |
+
if (installed_version != version and strict == True) or (pv.parse(installed_version) < pv.parse(version) and strict == False):
|
57 |
+
return False
|
58 |
+
else:
|
59 |
+
return True
|
60 |
+
else:
|
61 |
+
return False
|
62 |
+
except Exception as e:
|
63 |
+
print(f"Error: {e}")
|
64 |
+
return False
|
65 |
+
|
66 |
+
def download(url, path):
|
67 |
+
request = urllib.request.urlopen(url)
|
68 |
+
total = int(request.headers.get('Content-Length', 0))
|
69 |
+
with tqdm(total=total, desc='Downloading...', unit='B', unit_scale=True, unit_divisor=1024) as progress:
|
70 |
+
urllib.request.urlretrieve(url, path, reporthook=lambda count, block_size, total_size: progress.update(block_size))
|
71 |
+
|
72 |
+
if not os.path.exists(models_dir):
|
73 |
+
os.makedirs(models_dir)
|
74 |
+
|
75 |
+
if not os.path.exists(model_path):
|
76 |
+
download(model_url, model_path)
|
77 |
+
|
78 |
+
# print("ReActor preheating...", end=' ')
|
79 |
+
|
80 |
+
last_device = None
|
81 |
+
first_run = False
|
82 |
+
available_devices = ["CPU", "CUDA"]
|
83 |
+
|
84 |
+
try:
|
85 |
+
last_device_log = os.path.join(BASE_PATH, "last_device.txt")
|
86 |
+
with open(last_device_log) as f:
|
87 |
+
last_device = f.readline().strip()
|
88 |
+
if last_device not in available_devices:
|
89 |
+
last_device = None
|
90 |
+
except:
|
91 |
+
last_device = "CPU"
|
92 |
+
first_run = True
|
93 |
+
with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
|
94 |
+
txt.write(last_device)
|
95 |
+
|
96 |
+
with open(req_file) as file:
|
97 |
+
install_count = 0
|
98 |
+
ort = "onnxruntime-gpu"
|
99 |
+
import torch
|
100 |
+
try:
|
101 |
+
if torch.cuda.is_available():
|
102 |
+
if first_run or last_device is None:
|
103 |
+
last_device = "CUDA"
|
104 |
+
elif torch.backends.mps.is_available() or hasattr(torch,'dml'):
|
105 |
+
ort = "onnxruntime"
|
106 |
+
# to prevent errors when ORT-GPU is installed but we want ORT instead:
|
107 |
+
if first_run:
|
108 |
+
pip_uninstall("onnxruntime", "onnxruntime-gpu")
|
109 |
+
# just in case:
|
110 |
+
if last_device == "CUDA" or last_device is None:
|
111 |
+
last_device = "CPU"
|
112 |
+
else:
|
113 |
+
if last_device == "CUDA" or last_device is None:
|
114 |
+
last_device = "CPU"
|
115 |
+
with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
|
116 |
+
txt.write(last_device)
|
117 |
+
if not is_installed(ort,"1.16.1",False):
|
118 |
+
install_count += 1
|
119 |
+
pip_install(ort, "-U")
|
120 |
+
except Exception as e:
|
121 |
+
print(e)
|
122 |
+
print(f"\nERROR: Failed to install {ort} - ReActor won't start")
|
123 |
+
raise e
|
124 |
+
# print(f"Device: {last_device}")
|
125 |
+
strict = True
|
126 |
+
for package in file:
|
127 |
+
package_version = None
|
128 |
+
try:
|
129 |
+
package = package.strip()
|
130 |
+
if "==" in package:
|
131 |
+
package_version = package.split('==')[1]
|
132 |
+
elif ">=" in package:
|
133 |
+
package_version = package.split('>=')[1]
|
134 |
+
strict = False
|
135 |
+
if not is_installed(package,package_version,strict):
|
136 |
+
install_count += 1
|
137 |
+
pip_install(package)
|
138 |
+
except Exception as e:
|
139 |
+
print(e)
|
140 |
+
print(f"\nERROR: Failed to install {package} - ReActor won't start")
|
141 |
+
raise e
|
142 |
+
if install_count > 0:
|
143 |
+
print(f"""
|
144 |
+
+---------------------------------+
|
145 |
+
--- PLEASE, RESTART the Server! ---
|
146 |
+
+---------------------------------+
|
147 |
+
""")
|
extensions/sd-webui-reactor/last_device.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
CUDA
|
extensions/sd-webui-reactor/reactor_modules/__pycache__/reactor_mask.cpython-310.pyc
ADDED
Binary file (5.49 kB). View file
|
|
extensions/sd-webui-reactor/reactor_modules/reactor_mask.py
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
from PIL import Image, ImageDraw
|
4 |
+
|
5 |
+
from torchvision.transforms.functional import to_pil_image
|
6 |
+
|
7 |
+
from scripts.reactor_logger import logger
|
8 |
+
from scripts.reactor_inferencers.bisenet_mask_generator import BiSeNetMaskGenerator
|
9 |
+
from scripts.reactor_entities.face import FaceArea
|
10 |
+
from scripts.reactor_entities.rect import Rect
|
11 |
+
|
12 |
+
|
13 |
+
colors = [
|
14 |
+
(255, 0, 0),
|
15 |
+
(0, 255, 0),
|
16 |
+
(0, 0, 255),
|
17 |
+
(255, 255, 0),
|
18 |
+
(255, 0, 255),
|
19 |
+
(0, 255, 255),
|
20 |
+
(255, 255, 255),
|
21 |
+
(128, 0, 0),
|
22 |
+
(0, 128, 0),
|
23 |
+
(128, 128, 0),
|
24 |
+
(0, 0, 128),
|
25 |
+
(0, 128, 128),
|
26 |
+
]
|
27 |
+
|
28 |
+
def color_generator(colors):
|
29 |
+
while True:
|
30 |
+
for color in colors:
|
31 |
+
yield color
|
32 |
+
|
33 |
+
|
34 |
+
def process_face_image(
|
35 |
+
face: FaceArea,
|
36 |
+
**kwargs,
|
37 |
+
) -> Image:
|
38 |
+
image = np.array(face.image)
|
39 |
+
overlay = image.copy()
|
40 |
+
color_iter = color_generator(colors)
|
41 |
+
cv2.rectangle(overlay, (0, 0), (image.shape[1], image.shape[0]), next(color_iter), -1)
|
42 |
+
l, t, r, b = face.face_area_on_image
|
43 |
+
cv2.rectangle(overlay, (l, t), (r, b), (0, 0, 0), 10)
|
44 |
+
if face.landmarks_on_image is not None:
|
45 |
+
for landmark in face.landmarks_on_image:
|
46 |
+
cv2.circle(overlay, (int(landmark.x), int(landmark.y)), 6, (0, 0, 0), 10)
|
47 |
+
alpha = 0.3
|
48 |
+
output = cv2.addWeighted(image, 1 - alpha, overlay, alpha, 0)
|
49 |
+
|
50 |
+
return Image.fromarray(output)
|
51 |
+
|
52 |
+
|
53 |
+
def apply_face_mask(swapped_image:np.ndarray,target_image:np.ndarray,target_face,entire_mask_image:np.array)->np.ndarray:
|
54 |
+
logger.status("Correcting Face Mask")
|
55 |
+
mask_generator = BiSeNetMaskGenerator()
|
56 |
+
face = FaceArea(target_image,Rect.from_ndarray(np.array(target_face.bbox)),1.6,512,"")
|
57 |
+
face_image = np.array(face.image)
|
58 |
+
process_face_image(face)
|
59 |
+
face_area_on_image = face.face_area_on_image
|
60 |
+
mask = mask_generator.generate_mask(
|
61 |
+
face_image,
|
62 |
+
face_area_on_image=face_area_on_image,
|
63 |
+
affected_areas=["Face"],
|
64 |
+
mask_size=0,
|
65 |
+
use_minimal_area=True
|
66 |
+
)
|
67 |
+
mask = cv2.blur(mask, (12, 12))
|
68 |
+
# """entire_mask_image = np.zeros_like(target_image)"""
|
69 |
+
larger_mask = cv2.resize(mask, dsize=(face.width, face.height))
|
70 |
+
entire_mask_image[
|
71 |
+
face.top : face.bottom,
|
72 |
+
face.left : face.right,
|
73 |
+
] = larger_mask
|
74 |
+
|
75 |
+
result = Image.composite(Image.fromarray(swapped_image),Image.fromarray(target_image), Image.fromarray(entire_mask_image).convert("L"))
|
76 |
+
return np.array(result)
|
77 |
+
|
78 |
+
|
79 |
+
def rotate_array(image: np.ndarray, angle: float) -> np.ndarray:
|
80 |
+
if angle == 0:
|
81 |
+
return image
|
82 |
+
|
83 |
+
h, w = image.shape[:2]
|
84 |
+
center = (w // 2, h // 2)
|
85 |
+
|
86 |
+
M = cv2.getRotationMatrix2D(center, angle, 1.0)
|
87 |
+
return cv2.warpAffine(image, M, (w, h))
|
88 |
+
|
89 |
+
|
90 |
+
def rotate_image(image: Image, angle: float) -> Image:
|
91 |
+
if angle == 0:
|
92 |
+
return image
|
93 |
+
return Image.fromarray(rotate_array(np.array(image), angle))
|
94 |
+
|
95 |
+
|
96 |
+
def correct_face_tilt(angle: float) -> bool:
|
97 |
+
angle = abs(angle)
|
98 |
+
if angle > 180:
|
99 |
+
angle = 360 - angle
|
100 |
+
return angle > 40
|
101 |
+
|
102 |
+
|
103 |
+
def _dilate(arr: np.ndarray, value: int) -> np.ndarray:
|
104 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value))
|
105 |
+
return cv2.dilate(arr, kernel, iterations=1)
|
106 |
+
|
107 |
+
|
108 |
+
def _erode(arr: np.ndarray, value: int) -> np.ndarray:
|
109 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value))
|
110 |
+
return cv2.erode(arr, kernel, iterations=1)
|
111 |
+
|
112 |
+
|
113 |
+
def dilate_erode(img: Image.Image, value: int) -> Image.Image:
|
114 |
+
"""
|
115 |
+
The dilate_erode function takes an image and a value.
|
116 |
+
If the value is positive, it dilates the image by that amount.
|
117 |
+
If the value is negative, it erodes the image by that amount.
|
118 |
+
|
119 |
+
Parameters
|
120 |
+
----------
|
121 |
+
img: PIL.Image.Image
|
122 |
+
the image to be processed
|
123 |
+
value: int
|
124 |
+
kernel size of dilation or erosion
|
125 |
+
|
126 |
+
Returns
|
127 |
+
-------
|
128 |
+
PIL.Image.Image
|
129 |
+
The image that has been dilated or eroded
|
130 |
+
"""
|
131 |
+
if value == 0:
|
132 |
+
return img
|
133 |
+
|
134 |
+
arr = np.array(img)
|
135 |
+
arr = _dilate(arr, value) if value > 0 else _erode(arr, -value)
|
136 |
+
|
137 |
+
return Image.fromarray(arr)
|
138 |
+
|
139 |
+
def mask_to_pil(masks, shape: tuple[int, int]) -> list[Image.Image]:
|
140 |
+
"""
|
141 |
+
Parameters
|
142 |
+
----------
|
143 |
+
masks: torch.Tensor, dtype=torch.float32, shape=(N, H, W).
|
144 |
+
The device can be CUDA, but `to_pil_image` takes care of that.
|
145 |
+
|
146 |
+
shape: tuple[int, int]
|
147 |
+
(width, height) of the original image
|
148 |
+
"""
|
149 |
+
n = masks.shape[0]
|
150 |
+
return [to_pil_image(masks[i], mode="L").resize(shape) for i in range(n)]
|
151 |
+
|
152 |
+
def create_mask_from_bbox(
|
153 |
+
bboxes: list[list[float]], shape: tuple[int, int]
|
154 |
+
) -> list[Image.Image]:
|
155 |
+
"""
|
156 |
+
Parameters
|
157 |
+
----------
|
158 |
+
bboxes: list[list[float]]
|
159 |
+
list of [x1, y1, x2, y2]
|
160 |
+
bounding boxes
|
161 |
+
shape: tuple[int, int]
|
162 |
+
shape of the image (width, height)
|
163 |
+
|
164 |
+
Returns
|
165 |
+
-------
|
166 |
+
masks: list[Image.Image]
|
167 |
+
A list of masks
|
168 |
+
|
169 |
+
"""
|
170 |
+
masks = []
|
171 |
+
for bbox in bboxes:
|
172 |
+
mask = Image.new("L", shape, 0)
|
173 |
+
mask_draw = ImageDraw.Draw(mask)
|
174 |
+
mask_draw.rectangle(bbox, fill=255)
|
175 |
+
masks.append(mask)
|
176 |
+
return masks
|
extensions/sd-webui-reactor/reactor_ui/__init__.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import reactor_ui.reactor_upscale_ui as ui_upscale
|
2 |
+
import reactor_ui.reactor_tools_ui as ui_tools
|
3 |
+
import reactor_ui.reactor_settings_ui as ui_settings
|
4 |
+
import reactor_ui.reactor_main_ui as ui_main
|
extensions/sd-webui-reactor/reactor_ui/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (473 Bytes). View file
|
|
extensions/sd-webui-reactor/reactor_ui/__pycache__/reactor_main_ui.cpython-310.pyc
ADDED
Binary file (5.22 kB). View file
|
|
extensions/sd-webui-reactor/reactor_ui/__pycache__/reactor_settings_ui.cpython-310.pyc
ADDED
Binary file (2.54 kB). View file
|
|
extensions/sd-webui-reactor/reactor_ui/__pycache__/reactor_tools_ui.cpython-310.pyc
ADDED
Binary file (1.07 kB). View file
|
|
extensions/sd-webui-reactor/reactor_ui/__pycache__/reactor_upscale_ui.cpython-310.pyc
ADDED
Binary file (1.78 kB). View file
|
|
extensions/sd-webui-reactor/reactor_ui/reactor_main_ui.py
ADDED
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from scripts.reactor_helpers import (
|
3 |
+
get_model_names,
|
4 |
+
get_facemodels
|
5 |
+
)
|
6 |
+
from scripts.reactor_swapper import (
|
7 |
+
clear_faces_list,
|
8 |
+
)
|
9 |
+
from modules import shared
|
10 |
+
|
11 |
+
SAVE_ORIGINAL: bool = False
|
12 |
+
|
13 |
+
def update_fm_list(selected: str):
|
14 |
+
return gr.Dropdown.update(
|
15 |
+
value=selected, choices=get_model_names(get_facemodels)
|
16 |
+
)
|
17 |
+
|
18 |
+
# TAB MAIN
|
19 |
+
def show(is_img2img: bool, show_br: bool = True, **msgs):
|
20 |
+
|
21 |
+
def on_select_source(selected: bool, evt: gr.SelectData):
|
22 |
+
global SAVE_ORIGINAL
|
23 |
+
if evt.index == 2:
|
24 |
+
if SAVE_ORIGINAL != selected:
|
25 |
+
SAVE_ORIGINAL = selected
|
26 |
+
return {
|
27 |
+
control_col_1: gr.Column.update(visible=False),
|
28 |
+
control_col_2: gr.Column.update(visible=False),
|
29 |
+
control_col_3: gr.Column.update(visible=True),
|
30 |
+
save_original: gr.Checkbox.update(value=False,visible=False),
|
31 |
+
imgs_hash_clear: gr.Button.update(visible=True)
|
32 |
+
}
|
33 |
+
if evt.index == 0:
|
34 |
+
return {
|
35 |
+
control_col_1: gr.Column.update(visible=True),
|
36 |
+
control_col_2: gr.Column.update(visible=False),
|
37 |
+
control_col_3: gr.Column.update(visible=False),
|
38 |
+
save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
|
39 |
+
imgs_hash_clear: gr.Button.update(visible=False)
|
40 |
+
}
|
41 |
+
if evt.index == 1:
|
42 |
+
return {
|
43 |
+
control_col_1: gr.Column.update(visible=False),
|
44 |
+
control_col_2: gr.Column.update(visible=True),
|
45 |
+
control_col_3: gr.Column.update(visible=False),
|
46 |
+
save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
|
47 |
+
imgs_hash_clear: gr.Button.update(visible=False)
|
48 |
+
}
|
49 |
+
|
50 |
+
progressbar_area = gr.Markdown("")
|
51 |
+
with gr.Tab("Main"):
|
52 |
+
with gr.Column():
|
53 |
+
with gr.Row():
|
54 |
+
select_source = gr.Radio(
|
55 |
+
["Image(s)","Face Model","Folder"],
|
56 |
+
value="Image(s)",
|
57 |
+
label="Select Source",
|
58 |
+
type="index",
|
59 |
+
scale=1,
|
60 |
+
)
|
61 |
+
with gr.Column(visible=False) as control_col_2:
|
62 |
+
with gr.Row():
|
63 |
+
face_models = get_model_names(get_facemodels)
|
64 |
+
face_model = gr.Dropdown(
|
65 |
+
choices=face_models,
|
66 |
+
label="Choose Face Model",
|
67 |
+
value="None",
|
68 |
+
scale=1,
|
69 |
+
)
|
70 |
+
fm_update = gr.Button(
|
71 |
+
value="🔄",
|
72 |
+
variant="tool",
|
73 |
+
)
|
74 |
+
fm_update.click(
|
75 |
+
update_fm_list,
|
76 |
+
inputs=[face_model],
|
77 |
+
outputs=[face_model],
|
78 |
+
)
|
79 |
+
imgs_hash_clear = gr.Button(
|
80 |
+
value="Clear Source Images Hash",
|
81 |
+
scale=1,
|
82 |
+
visible=False,
|
83 |
+
)
|
84 |
+
imgs_hash_clear.click(clear_faces_list,None,[progressbar_area])
|
85 |
+
gr.Markdown("<br>", visible=show_br)
|
86 |
+
with gr.Column(visible=True) as control_col_1:
|
87 |
+
gr.Markdown("<center>🔽🔽🔽 Single Image has priority when both Areas in use 🔽🔽🔽</center>")
|
88 |
+
with gr.Row():
|
89 |
+
img = gr.Image(
|
90 |
+
type="pil",
|
91 |
+
label="Single Source Image",
|
92 |
+
)
|
93 |
+
imgs = gr.Files(
|
94 |
+
label=f"Multiple Source Images{msgs['extra_multiple_source']}",
|
95 |
+
file_types=["image"],
|
96 |
+
)
|
97 |
+
with gr.Column(visible=False) as control_col_3:
|
98 |
+
gr.Markdown("<span style='display:block;text-align:right;padding-right:3px;margin: -15px 0;font-size:1.1em'><sup>Clear Hash if you see the previous face was swapped instead of the new one</sup></span>")
|
99 |
+
source_folder = gr.Textbox(
|
100 |
+
value="",
|
101 |
+
placeholder="Paste here the path to the folder containing source faces images",
|
102 |
+
label=f"Source Folder{msgs['extra_multiple_source']}",
|
103 |
+
)
|
104 |
+
setattr(face_model, "do_not_save_to_config", True)
|
105 |
+
if is_img2img:
|
106 |
+
save_original = gr.Checkbox(
|
107 |
+
False,
|
108 |
+
label="Save Original (Swap in generated only)",
|
109 |
+
info="Save the original image(s) made before swapping (it always saves Original when you use Multiple Images or Folder)"
|
110 |
+
)
|
111 |
+
else:
|
112 |
+
save_original = gr.Checkbox(
|
113 |
+
False,
|
114 |
+
label="Save Original",
|
115 |
+
info="Save the original image(s) made before swapping (it always saves Original when you use Multiple Images or Folder)",
|
116 |
+
visible=show_br
|
117 |
+
)
|
118 |
+
# imgs.upload(on_files_upload_uncheck_so,[save_original],[save_original],show_progress=False)
|
119 |
+
# imgs.clear(on_files_clear,None,[save_original],show_progress=False)
|
120 |
+
imgs.clear(clear_faces_list,None,None,show_progress=False)
|
121 |
+
mask_face = gr.Checkbox(
|
122 |
+
False,
|
123 |
+
label="Face Mask Correction",
|
124 |
+
info="Apply this option if you see some pixelation around face contours"
|
125 |
+
)
|
126 |
+
gr.Markdown("<br>", visible=show_br)
|
127 |
+
gr.Markdown("Source Image (above):")
|
128 |
+
with gr.Row():
|
129 |
+
source_faces_index = gr.Textbox(
|
130 |
+
value="0",
|
131 |
+
placeholder="Which face(s) to use as Source (comma separated)",
|
132 |
+
label="Comma separated face number(s); Example: 0,2,1",
|
133 |
+
)
|
134 |
+
gender_source = gr.Radio(
|
135 |
+
["No", "Female Only", "Male Only"],
|
136 |
+
value="No",
|
137 |
+
label="Gender Detection (Source)",
|
138 |
+
type="index",
|
139 |
+
)
|
140 |
+
gr.Markdown("<br>", visible=show_br)
|
141 |
+
gr.Markdown("Target Image (result):")
|
142 |
+
with gr.Row():
|
143 |
+
faces_index = gr.Textbox(
|
144 |
+
value="0",
|
145 |
+
placeholder="Which face(s) to Swap into Target (comma separated)",
|
146 |
+
label="Comma separated face number(s); Example: 1,0,2",
|
147 |
+
)
|
148 |
+
gender_target = gr.Radio(
|
149 |
+
["No", "Female Only", "Male Only"],
|
150 |
+
value="No",
|
151 |
+
label="Gender Detection (Target)",
|
152 |
+
type="index",
|
153 |
+
)
|
154 |
+
gr.Markdown("<br>", visible=show_br)
|
155 |
+
with gr.Row():
|
156 |
+
face_restorer_name = gr.Radio(
|
157 |
+
label="Restore Face",
|
158 |
+
choices=["None"] + [x.name() for x in shared.face_restorers],
|
159 |
+
value=shared.face_restorers[0].name(),
|
160 |
+
type="value",
|
161 |
+
)
|
162 |
+
with gr.Column():
|
163 |
+
face_restorer_visibility = gr.Slider(
|
164 |
+
0, 1, 1, step=0.1, label="Restore Face Visibility"
|
165 |
+
)
|
166 |
+
codeformer_weight = gr.Slider(
|
167 |
+
0, 1, 0.5, step=0.1, label="CodeFormer Weight (Fidelity)", info="0 = far from original (max restoration), 1 = close to original (min restoration)"
|
168 |
+
)
|
169 |
+
gr.Markdown("<br>", visible=show_br)
|
170 |
+
swap_in_source = gr.Checkbox(
|
171 |
+
False,
|
172 |
+
label="Swap in source image",
|
173 |
+
visible=is_img2img,
|
174 |
+
)
|
175 |
+
swap_in_generated = gr.Checkbox(
|
176 |
+
True,
|
177 |
+
label="Swap in generated image",
|
178 |
+
visible=is_img2img,
|
179 |
+
)
|
180 |
+
select_source.select(on_select_source,[save_original],[control_col_1,control_col_2,control_col_3,save_original,imgs_hash_clear],show_progress=False)
|
181 |
+
|
182 |
+
return img, imgs, select_source, face_model, source_folder, save_original, mask_face, source_faces_index, gender_source, faces_index, gender_target, face_restorer_name, face_restorer_visibility, codeformer_weight, swap_in_source, swap_in_generated
|
extensions/sd-webui-reactor/reactor_ui/reactor_settings_ui.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from scripts.reactor_logger import logger
|
3 |
+
from scripts.reactor_helpers import get_models, set_Device
|
4 |
+
from scripts.reactor_globals import DEVICE, DEVICE_LIST
|
5 |
+
try:
|
6 |
+
import torch.cuda as cuda
|
7 |
+
EP_is_visible = True if cuda.is_available() else False
|
8 |
+
except:
|
9 |
+
EP_is_visible = False
|
10 |
+
|
11 |
+
def update_models_list(selected: str):
|
12 |
+
return gr.Dropdown.update(
|
13 |
+
value=selected, choices=get_models()
|
14 |
+
)
|
15 |
+
|
16 |
+
def show(hash_check_block: bool = True):
|
17 |
+
# TAB SETTINGS
|
18 |
+
with gr.Tab("Settings"):
|
19 |
+
models = get_models()
|
20 |
+
with gr.Row(visible=EP_is_visible):
|
21 |
+
device = gr.Radio(
|
22 |
+
label="Execution Provider",
|
23 |
+
choices=DEVICE_LIST,
|
24 |
+
value=DEVICE,
|
25 |
+
type="value",
|
26 |
+
info="Click 'Save' to apply. If you already run 'Generate' - RESTART is required: (A1111) Extensions Tab -> 'Apply and restart UI' or (SD.Next) close the Server and start it again",
|
27 |
+
scale=2,
|
28 |
+
)
|
29 |
+
save_device_btn = gr.Button("Save", scale=0)
|
30 |
+
save = gr.Markdown("", visible=EP_is_visible)
|
31 |
+
setattr(device, "do_not_save_to_config", True)
|
32 |
+
save_device_btn.click(
|
33 |
+
set_Device,
|
34 |
+
inputs=[device],
|
35 |
+
outputs=[save],
|
36 |
+
)
|
37 |
+
with gr.Row():
|
38 |
+
if len(models) == 0:
|
39 |
+
logger.warning(
|
40 |
+
"You should at least have one model in models directory, please read the doc here: https://github.com/Gourieff/sd-webui-reactor/"
|
41 |
+
)
|
42 |
+
model = gr.Dropdown(
|
43 |
+
choices=models,
|
44 |
+
label="Model not found, please download one and refresh the list"
|
45 |
+
)
|
46 |
+
else:
|
47 |
+
model = gr.Dropdown(
|
48 |
+
choices=models, label="Model", value=models[0]
|
49 |
+
)
|
50 |
+
models_update = gr.Button(
|
51 |
+
value="🔄",
|
52 |
+
variant="tool",
|
53 |
+
)
|
54 |
+
models_update.click(
|
55 |
+
update_models_list,
|
56 |
+
inputs=[model],
|
57 |
+
outputs=[model],
|
58 |
+
)
|
59 |
+
console_logging_level = gr.Radio(
|
60 |
+
["No log", "Minimum", "Default"],
|
61 |
+
value="Minimum",
|
62 |
+
label="Console Log Level",
|
63 |
+
type="index"
|
64 |
+
)
|
65 |
+
gr.Markdown("<br>", visible=hash_check_block)
|
66 |
+
with gr.Row(visible=hash_check_block):
|
67 |
+
source_hash_check = gr.Checkbox(
|
68 |
+
True,
|
69 |
+
label="Source Image Hash Check",
|
70 |
+
info="Recommended to keep it ON. Processing is faster when Source Image is the same."
|
71 |
+
)
|
72 |
+
target_hash_check = gr.Checkbox(
|
73 |
+
False,
|
74 |
+
label="Target Image Hash Check",
|
75 |
+
info="Affects if you use Extras tab or img2img with only 'Swap in source image' on."
|
76 |
+
)
|
77 |
+
return model, device, console_logging_level, source_hash_check, target_hash_check
|
extensions/sd-webui-reactor/reactor_ui/reactor_tools_ui.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from scripts.reactor_swapper import build_face_model
|
3 |
+
|
4 |
+
# TAB TOOLS
|
5 |
+
def show():
|
6 |
+
with gr.Tab("Tools"):
|
7 |
+
with gr.Tab("Face Models"):
|
8 |
+
gr.Markdown("Load an image containing one person, name it and click 'Build and Save'")
|
9 |
+
img_fm = gr.Image(
|
10 |
+
type="pil",
|
11 |
+
label="Load Image to build Face Model",
|
12 |
+
)
|
13 |
+
with gr.Row(equal_height=True):
|
14 |
+
fm_name = gr.Textbox(
|
15 |
+
value="",
|
16 |
+
placeholder="Please type any name (e.g. Elena)",
|
17 |
+
label="Face Model Name",
|
18 |
+
)
|
19 |
+
save_fm_btn = gr.Button("Build and Save")
|
20 |
+
save_fm = gr.Markdown("You can find saved models in 'models/reactor/faces'")
|
21 |
+
save_fm_btn.click(
|
22 |
+
build_face_model,
|
23 |
+
inputs=[img_fm, fm_name],
|
24 |
+
outputs=[save_fm],
|
25 |
+
)
|
extensions/sd-webui-reactor/reactor_ui/reactor_upscale_ui.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from modules import shared
|
3 |
+
|
4 |
+
def update_upscalers_list(selected: str):
|
5 |
+
return gr.Dropdown.update(
|
6 |
+
value=selected, choices=[upscaler.name for upscaler in shared.sd_upscalers]
|
7 |
+
)
|
8 |
+
|
9 |
+
# TAB UPSCALE
|
10 |
+
def show(show_br: bool = True):
|
11 |
+
with gr.Tab("Upscale"):
|
12 |
+
restore_first = gr.Checkbox(
|
13 |
+
True,
|
14 |
+
label="1. Restore Face -> 2. Upscale (-Uncheck- if you want vice versa)",
|
15 |
+
info="Postprocessing Order"
|
16 |
+
)
|
17 |
+
with gr.Row():
|
18 |
+
upscaler_name = gr.Dropdown(
|
19 |
+
choices=[upscaler.name for upscaler in shared.sd_upscalers],
|
20 |
+
label="Upscaler",
|
21 |
+
value="None",
|
22 |
+
info="Won't scale if you choose -Swap in Source- via img2img, only 1x-postprocessing will affect (texturing, denoising, restyling etc.)"
|
23 |
+
)
|
24 |
+
upscalers_update = gr.Button(
|
25 |
+
value="🔄",
|
26 |
+
variant="tool",
|
27 |
+
)
|
28 |
+
upscalers_update.click(
|
29 |
+
update_upscalers_list,
|
30 |
+
inputs=[upscaler_name],
|
31 |
+
outputs=[upscaler_name],
|
32 |
+
)
|
33 |
+
gr.Markdown("<br>", visible=show_br)
|
34 |
+
with gr.Row():
|
35 |
+
upscaler_scale = gr.Slider(1, 8, 1, step=0.1, label="Scale by")
|
36 |
+
upscaler_visibility = gr.Slider(
|
37 |
+
0, 1, 1, step=0.1, label="Upscaler Visibility (if scale = 1)"
|
38 |
+
)
|
39 |
+
return restore_first, upscaler_name, upscaler_scale, upscaler_visibility
|
extensions/sd-webui-reactor/requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
insightface==0.7.3
|
2 |
+
onnx>=1.14.0
|
3 |
+
opencv-python>=4.7.0.72
|
extensions/sd-webui-reactor/scripts/__pycache__/console_log_patch.cpython-310.pyc
ADDED
Binary file (4.04 kB). View file
|
|
extensions/sd-webui-reactor/scripts/__pycache__/reactor_api.cpython-310.pyc
ADDED
Binary file (5.78 kB). View file
|
|
extensions/sd-webui-reactor/scripts/__pycache__/reactor_faceswap.cpython-310.pyc
ADDED
Binary file (12.8 kB). View file
|
|
extensions/sd-webui-reactor/scripts/__pycache__/reactor_globals.cpython-310.pyc
ADDED
Binary file (1.39 kB). View file
|
|
extensions/sd-webui-reactor/scripts/__pycache__/reactor_helpers.cpython-310.pyc
ADDED
Binary file (7.09 kB). View file
|
|
extensions/sd-webui-reactor/scripts/__pycache__/reactor_logger.cpython-310.pyc
ADDED
Binary file (1.67 kB). View file
|
|
extensions/sd-webui-reactor/scripts/__pycache__/reactor_swapper.cpython-310.pyc
ADDED
Binary file (15.2 kB). View file
|
|
extensions/sd-webui-reactor/scripts/__pycache__/reactor_version.cpython-310.pyc
ADDED
Binary file (473 Bytes). View file
|
|
extensions/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.STATUS)
|
118 |
+
elif console_logging_level == 2:
|
119 |
+
patch_insightface(*original_functions)
|
120 |
+
logger.setLevel(logging.INFO)
|
extensions/sd-webui-reactor/scripts/reactor_api.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'''
|
2 |
+
Thanks SpenserCai for the original version of the roop api script
|
3 |
+
-----------------------------------
|
4 |
+
--- ReActor External API v1.0.1 ---
|
5 |
+
-----------------------------------
|
6 |
+
'''
|
7 |
+
import os, glob
|
8 |
+
from datetime import datetime, date
|
9 |
+
from fastapi import FastAPI, Body
|
10 |
+
|
11 |
+
# from modules.api.models import *
|
12 |
+
from modules import scripts, shared
|
13 |
+
from modules.api import api
|
14 |
+
|
15 |
+
import gradio as gr
|
16 |
+
|
17 |
+
from scripts.reactor_swapper import EnhancementOptions, swap_face
|
18 |
+
from scripts.reactor_logger import logger
|
19 |
+
|
20 |
+
|
21 |
+
def default_file_path():
|
22 |
+
time = datetime.now()
|
23 |
+
today = date.today()
|
24 |
+
current_date = today.strftime('%Y-%m-%d')
|
25 |
+
current_time = time.strftime('%H-%M-%S')
|
26 |
+
output_file = 'output_'+current_date+'_'+current_time+'.png'
|
27 |
+
return os.path.join(os.path.abspath("outputs/api"), output_file)
|
28 |
+
|
29 |
+
def get_face_restorer(name):
|
30 |
+
for restorer in shared.face_restorers:
|
31 |
+
if restorer.name() == name:
|
32 |
+
return restorer
|
33 |
+
return None
|
34 |
+
|
35 |
+
def get_upscaler(name):
|
36 |
+
for upscaler in shared.sd_upscalers:
|
37 |
+
if upscaler.name == name:
|
38 |
+
return upscaler
|
39 |
+
return None
|
40 |
+
|
41 |
+
def get_models():
|
42 |
+
models_path = os.path.join(scripts.basedir(), "models/insightface/*")
|
43 |
+
models = glob.glob(models_path)
|
44 |
+
models = [x for x in models if x.endswith(".onnx") or x.endswith(".pth")]
|
45 |
+
return models
|
46 |
+
|
47 |
+
def get_full_model(model_name):
|
48 |
+
models = get_models()
|
49 |
+
for model in models:
|
50 |
+
model_path = os.path.split(model)
|
51 |
+
if model_path[1] == model_name:
|
52 |
+
return model
|
53 |
+
return None
|
54 |
+
|
55 |
+
def reactor_api(_: gr.Blocks, app: FastAPI):
|
56 |
+
@app.post("/reactor/image")
|
57 |
+
async def reactor_image(
|
58 |
+
source_image: str = Body("",title="Source Face Image"),
|
59 |
+
target_image: str = Body("",title="Target Image"),
|
60 |
+
source_faces_index: list[int] = Body([0],title="Comma separated face number(s) from swap-source image"),
|
61 |
+
face_index: list[int] = Body([0],title="Comma separated face number(s) for target image (result)"),
|
62 |
+
upscaler: str = Body("None",title="Upscaler"),
|
63 |
+
scale: float = Body(1,title="Scale by"),
|
64 |
+
upscale_visibility: float = Body(1,title="Upscaler visibility (if scale = 1)"),
|
65 |
+
face_restorer: str = Body("None",title="Restore Face: 0 - None; 1 - CodeFormer; 2 - GFPGA"),
|
66 |
+
restorer_visibility: float = Body(1,title="Restore visibility value"),
|
67 |
+
codeformer_weight: float = Body(0.5,title="CodeFormer Weight"),
|
68 |
+
restore_first: int = Body(1,title="Restore face -> Then upscale, 1 - True, 0 - False"),
|
69 |
+
model: str = Body("inswapper_128.onnx",title="Model"),
|
70 |
+
gender_source: int = Body(0,title="Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)"),
|
71 |
+
gender_target: int = Body(0,title="Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)"),
|
72 |
+
save_to_file: int = Body(0,title="Save Result to file, 0 - No, 1 - Yes"),
|
73 |
+
result_file_path: str = Body("",title="(if 'save_to_file = 1') Result file path"),
|
74 |
+
device: str = Body("CPU",title="CPU or CUDA (if you have it)"),
|
75 |
+
mask_face: int = Body(0,title="Face Mask Correction, 1 - True, 0 - False"),
|
76 |
+
select_source: int = Body(0,title="Select Source, 0 - Image, 1 - Face Model, 2 - Source Folder"),
|
77 |
+
face_model: str = Body("None",title="Filename of the face model (from 'models/reactor/faces'), e.g. elena.safetensors"),
|
78 |
+
source_folder: str = Body("",title="The path to the folder containing source faces images")
|
79 |
+
):
|
80 |
+
s_image = api.decode_base64_to_image(source_image)
|
81 |
+
t_image = api.decode_base64_to_image(target_image)
|
82 |
+
sf_index = source_faces_index
|
83 |
+
f_index = face_index
|
84 |
+
gender_s = gender_source
|
85 |
+
gender_t = gender_target
|
86 |
+
restore_first_bool = True if restore_first == 1 else False
|
87 |
+
mask_face = True if mask_face == 1 else False
|
88 |
+
up_options = EnhancementOptions(do_restore_first=restore_first_bool, scale=scale, upscaler=get_upscaler(upscaler), upscale_visibility=upscale_visibility,face_restorer=get_face_restorer(face_restorer),restorer_visibility=restorer_visibility,codeformer_weight=codeformer_weight)
|
89 |
+
use_model = get_full_model(model)
|
90 |
+
if use_model is None:
|
91 |
+
Exception("Model not found")
|
92 |
+
result = swap_face(s_image, t_image, use_model, sf_index, f_index, up_options, gender_s, gender_t, True, True, device, mask_face, select_source, face_model, source_folder, None)
|
93 |
+
if save_to_file == 1:
|
94 |
+
if result_file_path == "":
|
95 |
+
result_file_path = default_file_path()
|
96 |
+
try:
|
97 |
+
result[0].save(result_file_path, format='PNG')
|
98 |
+
logger.status("Result has been saved to: %s", result_file_path)
|
99 |
+
except Exception as e:
|
100 |
+
logger.error("Error while saving result: %s",e)
|
101 |
+
return {"image": api.encode_pil_to_base64(result[0])}
|
102 |
+
|
103 |
+
@app.get("/reactor/models")
|
104 |
+
async def reactor_models():
|
105 |
+
model_names = [os.path.split(model)[1] for model in get_models()]
|
106 |
+
return {"models": model_names}
|
107 |
+
|
108 |
+
@app.get("/reactor/upscalers")
|
109 |
+
async def reactor_upscalers():
|
110 |
+
names = [upscaler.name for upscaler in shared.sd_upscalers]
|
111 |
+
return {"upscalers": names}
|
112 |
+
|
113 |
+
try:
|
114 |
+
import modules.script_callbacks as script_callbacks
|
115 |
+
|
116 |
+
script_callbacks.on_app_started(reactor_api)
|
117 |
+
except:
|
118 |
+
pass
|
extensions/sd-webui-reactor/scripts/reactor_entities/__pycache__/face.cpython-310.pyc
ADDED
Binary file (4.29 kB). View file
|
|
extensions/sd-webui-reactor/scripts/reactor_entities/__pycache__/rect.cpython-310.pyc
ADDED
Binary file (2.25 kB). View file
|
|
extensions/sd-webui-reactor/scripts/reactor_entities/face.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import traceback
|
2 |
+
|
3 |
+
import cv2
|
4 |
+
import numpy as np
|
5 |
+
from modules import images
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
|
9 |
+
from scripts.reactor_entities.rect import Point, Rect
|
10 |
+
|
11 |
+
|
12 |
+
class FaceArea:
|
13 |
+
def __init__(self, entire_image: np.ndarray, face_area: Rect, face_margin: float, face_size: int, upscaler: str):
|
14 |
+
self.face_area = face_area
|
15 |
+
self.center = face_area.center
|
16 |
+
left, top, right, bottom = face_area.to_square()
|
17 |
+
|
18 |
+
self.left, self.top, self.right, self.bottom = self.__ensure_margin(
|
19 |
+
left, top, right, bottom, entire_image, face_margin
|
20 |
+
)
|
21 |
+
|
22 |
+
self.width = self.right - self.left
|
23 |
+
self.height = self.bottom - self.top
|
24 |
+
|
25 |
+
self.image = self.__crop_face_image(entire_image, face_size, upscaler)
|
26 |
+
self.face_size = face_size
|
27 |
+
self.scale_factor = face_size / self.width
|
28 |
+
self.face_area_on_image = self.__get_face_area_on_image()
|
29 |
+
self.landmarks_on_image = self.__get_landmarks_on_image()
|
30 |
+
|
31 |
+
def __get_face_area_on_image(self):
|
32 |
+
left = int((self.face_area.left - self.left) * self.scale_factor)
|
33 |
+
top = int((self.face_area.top - self.top) * self.scale_factor)
|
34 |
+
right = int((self.face_area.right - self.left) * self.scale_factor)
|
35 |
+
bottom = int((self.face_area.bottom - self.top) * self.scale_factor)
|
36 |
+
return self.__clip_values(left, top, right, bottom)
|
37 |
+
|
38 |
+
def __get_landmarks_on_image(self):
|
39 |
+
landmarks = []
|
40 |
+
if self.face_area.landmarks is not None:
|
41 |
+
for landmark in self.face_area.landmarks:
|
42 |
+
landmarks.append(
|
43 |
+
Point(
|
44 |
+
int((landmark.x - self.left) * self.scale_factor),
|
45 |
+
int((landmark.y - self.top) * self.scale_factor),
|
46 |
+
)
|
47 |
+
)
|
48 |
+
return landmarks
|
49 |
+
|
50 |
+
def __crop_face_image(self, entire_image: np.ndarray, face_size: int, upscaler: str):
|
51 |
+
cropped = entire_image[self.top : self.bottom, self.left : self.right, :]
|
52 |
+
if upscaler:
|
53 |
+
return images.resize_image(0, Image.fromarray(cropped), face_size, face_size, upscaler)
|
54 |
+
else:
|
55 |
+
return Image.fromarray(cv2.resize(cropped, dsize=(face_size, face_size)))
|
56 |
+
|
57 |
+
def __ensure_margin(self, left: int, top: int, right: int, bottom: int, entire_image: np.ndarray, margin: float):
|
58 |
+
entire_height, entire_width = entire_image.shape[:2]
|
59 |
+
|
60 |
+
side_length = right - left
|
61 |
+
margin = min(min(entire_height, entire_width) / side_length, margin)
|
62 |
+
diff = int((side_length * margin - side_length) / 2)
|
63 |
+
|
64 |
+
top = top - diff
|
65 |
+
bottom = bottom + diff
|
66 |
+
left = left - diff
|
67 |
+
right = right + diff
|
68 |
+
|
69 |
+
if top < 0:
|
70 |
+
bottom = bottom - top
|
71 |
+
top = 0
|
72 |
+
if left < 0:
|
73 |
+
right = right - left
|
74 |
+
left = 0
|
75 |
+
|
76 |
+
if bottom > entire_height:
|
77 |
+
top = top - (bottom - entire_height)
|
78 |
+
bottom = entire_height
|
79 |
+
if right > entire_width:
|
80 |
+
left = left - (right - entire_width)
|
81 |
+
right = entire_width
|
82 |
+
|
83 |
+
return left, top, right, bottom
|
84 |
+
|
85 |
+
def get_angle(self) -> float:
|
86 |
+
landmarks = getattr(self.face_area, "landmarks", None)
|
87 |
+
if landmarks is None:
|
88 |
+
return 0
|
89 |
+
|
90 |
+
eye1 = getattr(landmarks, "eye1", None)
|
91 |
+
eye2 = getattr(landmarks, "eye2", None)
|
92 |
+
if eye2 is None or eye1 is None:
|
93 |
+
return 0
|
94 |
+
|
95 |
+
try:
|
96 |
+
dx = eye2.x - eye1.x
|
97 |
+
dy = eye2.y - eye1.y
|
98 |
+
if dx == 0:
|
99 |
+
dx = 1
|
100 |
+
angle = np.arctan(dy / dx) * 180 / np.pi
|
101 |
+
|
102 |
+
if dx < 0:
|
103 |
+
angle = (angle + 180) % 360
|
104 |
+
return angle
|
105 |
+
except Exception:
|
106 |
+
print(traceback.format_exc())
|
107 |
+
return 0
|
108 |
+
|
109 |
+
def rotate_face_area_on_image(self, angle: float):
|
110 |
+
center = [
|
111 |
+
(self.face_area_on_image[0] + self.face_area_on_image[2]) / 2,
|
112 |
+
(self.face_area_on_image[1] + self.face_area_on_image[3]) / 2,
|
113 |
+
]
|
114 |
+
|
115 |
+
points = [
|
116 |
+
[self.face_area_on_image[0], self.face_area_on_image[1]],
|
117 |
+
[self.face_area_on_image[2], self.face_area_on_image[3]],
|
118 |
+
]
|
119 |
+
|
120 |
+
angle = np.radians(angle)
|
121 |
+
rot_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
|
122 |
+
|
123 |
+
points = np.array(points) - center
|
124 |
+
points = np.dot(points, rot_matrix.T)
|
125 |
+
points += center
|
126 |
+
left, top, right, bottom = (int(points[0][0]), int(points[0][1]), int(points[1][0]), int(points[1][1]))
|
127 |
+
|
128 |
+
left, right = (right, left) if left > right else (left, right)
|
129 |
+
top, bottom = (bottom, top) if top > bottom else (top, bottom)
|
130 |
+
|
131 |
+
width, height = right - left, bottom - top
|
132 |
+
if width < height:
|
133 |
+
left, right = left - (height - width) // 2, right + (height - width) // 2
|
134 |
+
elif height < width:
|
135 |
+
top, bottom = top - (width - height) // 2, bottom + (width - height) // 2
|
136 |
+
return self.__clip_values(left, top, right, bottom)
|
137 |
+
|
138 |
+
def __clip_values(self, *args):
|
139 |
+
result = []
|
140 |
+
for val in args:
|
141 |
+
if val < 0:
|
142 |
+
result.append(0)
|
143 |
+
elif val > self.face_size:
|
144 |
+
result.append(self.face_size)
|
145 |
+
else:
|
146 |
+
result.append(val)
|
147 |
+
return tuple(result)
|
extensions/sd-webui-reactor/scripts/reactor_entities/rect.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, NamedTuple, Tuple
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
|
6 |
+
class Point(NamedTuple):
|
7 |
+
x: int
|
8 |
+
y: int
|
9 |
+
|
10 |
+
|
11 |
+
class Landmarks(NamedTuple):
|
12 |
+
eye1: Point
|
13 |
+
eye2: Point
|
14 |
+
nose: Point
|
15 |
+
mouth1: Point
|
16 |
+
mouth2: Point
|
17 |
+
|
18 |
+
|
19 |
+
class Rect:
|
20 |
+
def __init__(
|
21 |
+
self,
|
22 |
+
left: int,
|
23 |
+
top: int,
|
24 |
+
right: int,
|
25 |
+
bottom: int,
|
26 |
+
tag: str = "face",
|
27 |
+
landmarks: Landmarks = None,
|
28 |
+
attributes: Dict[str, str] = {},
|
29 |
+
) -> None:
|
30 |
+
self.tag = tag
|
31 |
+
self.left = left
|
32 |
+
self.top = top
|
33 |
+
self.right = right
|
34 |
+
self.bottom = bottom
|
35 |
+
self.center = int((right + left) / 2)
|
36 |
+
self.middle = int((top + bottom) / 2)
|
37 |
+
self.width = right - left
|
38 |
+
self.height = bottom - top
|
39 |
+
self.size = self.width * self.height
|
40 |
+
self.landmarks = landmarks
|
41 |
+
self.attributes = attributes
|
42 |
+
|
43 |
+
@classmethod
|
44 |
+
def from_ndarray(
|
45 |
+
cls,
|
46 |
+
face_box: np.ndarray,
|
47 |
+
tag: str = "face",
|
48 |
+
landmarks: Landmarks = None,
|
49 |
+
attributes: Dict[str, str] = {},
|
50 |
+
) -> "Rect":
|
51 |
+
left, top, right, bottom, *_ = list(map(int, face_box))
|
52 |
+
return cls(left, top, right, bottom, tag, landmarks, attributes)
|
53 |
+
|
54 |
+
def to_tuple(self) -> Tuple[int, int, int, int]:
|
55 |
+
return self.left, self.top, self.right, self.bottom
|
56 |
+
|
57 |
+
def to_square(self):
|
58 |
+
left, top, right, bottom = self.to_tuple()
|
59 |
+
|
60 |
+
width = right - left
|
61 |
+
height = bottom - top
|
62 |
+
|
63 |
+
if width % 2 == 1:
|
64 |
+
right = right + 1
|
65 |
+
width = width + 1
|
66 |
+
if height % 2 == 1:
|
67 |
+
bottom = bottom + 1
|
68 |
+
height = height + 1
|
69 |
+
|
70 |
+
diff = int(abs(width - height) / 2)
|
71 |
+
if width > height:
|
72 |
+
top = top - diff
|
73 |
+
bottom = bottom + diff
|
74 |
+
else:
|
75 |
+
left = left - diff
|
76 |
+
right = right + diff
|
77 |
+
|
78 |
+
return left, top, right, bottom
|
extensions/sd-webui-reactor/scripts/reactor_faceswap.py
ADDED
@@ -0,0 +1,589 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, ui_components
|
10 |
+
from modules.processing import (
|
11 |
+
Processed,
|
12 |
+
StableDiffusionProcessing,
|
13 |
+
StableDiffusionProcessingImg2Img,
|
14 |
+
)
|
15 |
+
from modules.face_restoration import FaceRestoration
|
16 |
+
from modules.images import save_image
|
17 |
+
|
18 |
+
from reactor_ui import ui_main, ui_upscale, ui_tools, ui_settings
|
19 |
+
from scripts.reactor_logger import logger
|
20 |
+
from scripts.reactor_swapper import (
|
21 |
+
EnhancementOptions,
|
22 |
+
swap_face,
|
23 |
+
check_process_halt,
|
24 |
+
reset_messaged,
|
25 |
+
)
|
26 |
+
from scripts.reactor_version import version_flag, app_title
|
27 |
+
from scripts.console_log_patch import apply_logging_patch
|
28 |
+
from scripts.reactor_helpers import (
|
29 |
+
make_grid,
|
30 |
+
set_Device,
|
31 |
+
get_SDNEXT
|
32 |
+
)
|
33 |
+
from scripts.reactor_globals import SWAPPER_MODELS_PATH #, DEVICE, DEVICE_LIST
|
34 |
+
|
35 |
+
|
36 |
+
class FaceSwapScript(scripts.Script):
|
37 |
+
def title(self):
|
38 |
+
return f"{app_title}"
|
39 |
+
|
40 |
+
def show(self, is_img2img):
|
41 |
+
return scripts.AlwaysVisible
|
42 |
+
|
43 |
+
def ui(self, is_img2img):
|
44 |
+
with ui_components.InputAccordion(False, label=f"{app_title}") as enable:
|
45 |
+
# with gr.Accordion(f"{app_title}", open=False):
|
46 |
+
|
47 |
+
# def on_files_upload_uncheck_so(selected: bool):
|
48 |
+
# global SAVE_ORIGINAL
|
49 |
+
# SAVE_ORIGINAL = selected
|
50 |
+
# return gr.Checkbox.update(value=False,visible=False)
|
51 |
+
# def on_files_clear():
|
52 |
+
# clear_faces_list()
|
53 |
+
# return gr.Checkbox.update(value=SAVE_ORIGINAL,visible=True)
|
54 |
+
|
55 |
+
# SD.Next fix
|
56 |
+
if get_SDNEXT():
|
57 |
+
enable = gr.Checkbox(False, label="Enable")
|
58 |
+
|
59 |
+
# enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}")
|
60 |
+
gr.Markdown(f"<sup>The Fast and Simple FaceSwap Extension - {version_flag}</sup>")
|
61 |
+
|
62 |
+
# TAB MAIN
|
63 |
+
msgs: dict = {
|
64 |
+
"extra_multiple_source": "",
|
65 |
+
}
|
66 |
+
img, imgs, select_source, face_model, source_folder, save_original, mask_face, source_faces_index, gender_source, faces_index, gender_target, face_restorer_name, face_restorer_visibility, codeformer_weight, swap_in_source, swap_in_generated = ui_main.show(is_img2img=is_img2img, **msgs)
|
67 |
+
|
68 |
+
# TAB UPSCALE
|
69 |
+
restore_first, upscaler_name, upscaler_scale, upscaler_visibility = ui_upscale.show()
|
70 |
+
|
71 |
+
# TAB TOOLS
|
72 |
+
ui_tools.show()
|
73 |
+
|
74 |
+
# TAB SETTINGS
|
75 |
+
model, device, console_logging_level, source_hash_check, target_hash_check = ui_settings.show()
|
76 |
+
|
77 |
+
gr.Markdown("<span style='display:block;text-align:right;padding:3px;font-size:0.666em;margin-bottom:-12px;'>by <a style='font-weight:normal' href='https://github.com/Gourieff' target='_blank'>Eugene Gourieff</a></span>")
|
78 |
+
|
79 |
+
return [
|
80 |
+
img,
|
81 |
+
enable,
|
82 |
+
source_faces_index,
|
83 |
+
faces_index,
|
84 |
+
model,
|
85 |
+
face_restorer_name,
|
86 |
+
face_restorer_visibility,
|
87 |
+
restore_first,
|
88 |
+
upscaler_name,
|
89 |
+
upscaler_scale,
|
90 |
+
upscaler_visibility,
|
91 |
+
swap_in_source,
|
92 |
+
swap_in_generated,
|
93 |
+
console_logging_level,
|
94 |
+
gender_source,
|
95 |
+
gender_target,
|
96 |
+
save_original,
|
97 |
+
codeformer_weight,
|
98 |
+
source_hash_check,
|
99 |
+
target_hash_check,
|
100 |
+
device,
|
101 |
+
mask_face,
|
102 |
+
select_source,
|
103 |
+
face_model,
|
104 |
+
source_folder,
|
105 |
+
imgs,
|
106 |
+
]
|
107 |
+
|
108 |
+
|
109 |
+
@property
|
110 |
+
def upscaler(self) -> UpscalerData:
|
111 |
+
for upscaler in shared.sd_upscalers:
|
112 |
+
if upscaler.name == self.upscaler_name:
|
113 |
+
return upscaler
|
114 |
+
return None
|
115 |
+
|
116 |
+
@property
|
117 |
+
def face_restorer(self) -> FaceRestoration:
|
118 |
+
for face_restorer in shared.face_restorers:
|
119 |
+
if face_restorer.name() == self.face_restorer_name:
|
120 |
+
return face_restorer
|
121 |
+
return None
|
122 |
+
|
123 |
+
@property
|
124 |
+
def enhancement_options(self) -> EnhancementOptions:
|
125 |
+
return EnhancementOptions(
|
126 |
+
do_restore_first = self.restore_first,
|
127 |
+
scale=self.upscaler_scale,
|
128 |
+
upscaler=self.upscaler,
|
129 |
+
face_restorer=self.face_restorer,
|
130 |
+
upscale_visibility=self.upscaler_visibility,
|
131 |
+
restorer_visibility=self.face_restorer_visibility,
|
132 |
+
codeformer_weight=self.codeformer_weight,
|
133 |
+
)
|
134 |
+
|
135 |
+
def process(
|
136 |
+
self,
|
137 |
+
p: StableDiffusionProcessing,
|
138 |
+
img,
|
139 |
+
enable,
|
140 |
+
source_faces_index,
|
141 |
+
faces_index,
|
142 |
+
model,
|
143 |
+
face_restorer_name,
|
144 |
+
face_restorer_visibility,
|
145 |
+
restore_first,
|
146 |
+
upscaler_name,
|
147 |
+
upscaler_scale,
|
148 |
+
upscaler_visibility,
|
149 |
+
swap_in_source,
|
150 |
+
swap_in_generated,
|
151 |
+
console_logging_level,
|
152 |
+
gender_source,
|
153 |
+
gender_target,
|
154 |
+
save_original,
|
155 |
+
codeformer_weight,
|
156 |
+
source_hash_check,
|
157 |
+
target_hash_check,
|
158 |
+
device,
|
159 |
+
mask_face,
|
160 |
+
select_source,
|
161 |
+
face_model,
|
162 |
+
source_folder,
|
163 |
+
imgs,
|
164 |
+
):
|
165 |
+
self.enable = enable
|
166 |
+
if self.enable:
|
167 |
+
|
168 |
+
logger.debug("*** Start process")
|
169 |
+
|
170 |
+
reset_messaged()
|
171 |
+
if check_process_halt():
|
172 |
+
return
|
173 |
+
|
174 |
+
global SWAPPER_MODELS_PATH
|
175 |
+
self.source = img
|
176 |
+
self.face_restorer_name = face_restorer_name
|
177 |
+
self.upscaler_scale = upscaler_scale
|
178 |
+
self.upscaler_visibility = upscaler_visibility
|
179 |
+
self.face_restorer_visibility = face_restorer_visibility
|
180 |
+
self.restore_first = restore_first
|
181 |
+
self.upscaler_name = upscaler_name
|
182 |
+
self.swap_in_source = swap_in_source
|
183 |
+
self.swap_in_generated = swap_in_generated
|
184 |
+
self.model = os.path.join(SWAPPER_MODELS_PATH,model)
|
185 |
+
self.console_logging_level = console_logging_level
|
186 |
+
self.gender_source = gender_source
|
187 |
+
self.gender_target = gender_target
|
188 |
+
self.save_original = save_original
|
189 |
+
self.codeformer_weight = codeformer_weight
|
190 |
+
self.source_hash_check = source_hash_check
|
191 |
+
self.target_hash_check = target_hash_check
|
192 |
+
self.device = device
|
193 |
+
self.mask_face = mask_face
|
194 |
+
self.select_source = select_source
|
195 |
+
self.face_model = face_model
|
196 |
+
self.source_folder = source_folder
|
197 |
+
self.source_imgs = imgs
|
198 |
+
if self.gender_source is None or self.gender_source == "No":
|
199 |
+
self.gender_source = 0
|
200 |
+
if self.gender_target is None or self.gender_target == "No":
|
201 |
+
self.gender_target = 0
|
202 |
+
self.source_faces_index = [
|
203 |
+
int(x) for x in source_faces_index.strip(",").split(",") if x.isnumeric()
|
204 |
+
]
|
205 |
+
self.faces_index = [
|
206 |
+
int(x) for x in faces_index.strip(",").split(",") if x.isnumeric()
|
207 |
+
]
|
208 |
+
if len(self.source_faces_index) == 0:
|
209 |
+
self.source_faces_index = [0]
|
210 |
+
if len(self.faces_index) == 0:
|
211 |
+
self.faces_index = [0]
|
212 |
+
if self.save_original is None:
|
213 |
+
self.save_original = False
|
214 |
+
if self.source_hash_check is None:
|
215 |
+
self.source_hash_check = True
|
216 |
+
if self.target_hash_check is None:
|
217 |
+
self.target_hash_check = False
|
218 |
+
if self.mask_face is None:
|
219 |
+
self.mask_face = False
|
220 |
+
|
221 |
+
logger.debug("*** Set Device")
|
222 |
+
set_Device(self.device)
|
223 |
+
|
224 |
+
if ((self.source is not None or self.source_imgs is not None) and self.select_source == 0) or ((self.face_model is not None and self.face_model != "None") and self.select_source == 1) or ((self.source_folder is not None and self.source_folder != "") and self.select_source == 2):
|
225 |
+
logger.debug("*** Log patch")
|
226 |
+
apply_logging_patch(console_logging_level)
|
227 |
+
if isinstance(p, StableDiffusionProcessingImg2Img) and self.swap_in_source:
|
228 |
+
logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
229 |
+
|
230 |
+
for i in range(len(p.init_images)):
|
231 |
+
if len(p.init_images) > 1:
|
232 |
+
logger.status("Swap in %s", i)
|
233 |
+
result, output, swapped = swap_face(
|
234 |
+
self.source,
|
235 |
+
p.init_images[i],
|
236 |
+
source_faces_index=self.source_faces_index,
|
237 |
+
faces_index=self.faces_index,
|
238 |
+
model=self.model,
|
239 |
+
enhancement_options=self.enhancement_options,
|
240 |
+
gender_source=self.gender_source,
|
241 |
+
gender_target=self.gender_target,
|
242 |
+
source_hash_check=self.source_hash_check,
|
243 |
+
target_hash_check=self.target_hash_check,
|
244 |
+
device=self.device,
|
245 |
+
mask_face=self.mask_face,
|
246 |
+
select_source=self.select_source,
|
247 |
+
face_model = self.face_model,
|
248 |
+
source_folder = None,
|
249 |
+
source_imgs = None,
|
250 |
+
)
|
251 |
+
p.init_images[i] = result
|
252 |
+
# 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")
|
253 |
+
# if len(output) != 0:
|
254 |
+
# with open(result_path, 'w', encoding="utf8") as f:
|
255 |
+
# f.writelines(output)
|
256 |
+
|
257 |
+
if shared.state.interrupted or shared.state.skipped:
|
258 |
+
return
|
259 |
+
|
260 |
+
else:
|
261 |
+
logger.error("Please provide a source face")
|
262 |
+
return
|
263 |
+
|
264 |
+
def postprocess(self, p: StableDiffusionProcessing, processed: Processed, *args):
|
265 |
+
if self.enable:
|
266 |
+
|
267 |
+
logger.debug("*** Check postprocess")
|
268 |
+
|
269 |
+
reset_messaged()
|
270 |
+
if check_process_halt():
|
271 |
+
return
|
272 |
+
|
273 |
+
if self.save_original or ((self.select_source == 2 and self.source_folder is not None and self.source_folder != "") or (self.select_source == 0 and self.source_imgs is not None and self.source is None)):
|
274 |
+
|
275 |
+
postprocess_run: bool = True
|
276 |
+
|
277 |
+
orig_images : List[Image.Image] = processed.images[processed.index_of_first_image:]
|
278 |
+
orig_infotexts : List[str] = processed.infotexts[processed.index_of_first_image:]
|
279 |
+
|
280 |
+
result_images: List = processed.images
|
281 |
+
# result_info: List = processed.infotexts
|
282 |
+
|
283 |
+
if self.swap_in_generated:
|
284 |
+
|
285 |
+
logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
286 |
+
|
287 |
+
if self.source is not None:
|
288 |
+
# self.source_folder = None
|
289 |
+
self.source_imgs = None
|
290 |
+
|
291 |
+
for i,(img,info) in enumerate(zip(orig_images, orig_infotexts)):
|
292 |
+
if check_process_halt():
|
293 |
+
postprocess_run = False
|
294 |
+
break
|
295 |
+
if len(orig_images) > 1:
|
296 |
+
logger.status("Swap in %s", i)
|
297 |
+
result, output, swapped = swap_face(
|
298 |
+
self.source,
|
299 |
+
img,
|
300 |
+
source_faces_index=self.source_faces_index,
|
301 |
+
faces_index=self.faces_index,
|
302 |
+
model=self.model,
|
303 |
+
enhancement_options=self.enhancement_options,
|
304 |
+
gender_source=self.gender_source,
|
305 |
+
gender_target=self.gender_target,
|
306 |
+
source_hash_check=self.source_hash_check,
|
307 |
+
target_hash_check=self.target_hash_check,
|
308 |
+
device=self.device,
|
309 |
+
mask_face=self.mask_face,
|
310 |
+
select_source=self.select_source,
|
311 |
+
face_model = self.face_model,
|
312 |
+
source_folder = self.source_folder,
|
313 |
+
source_imgs = self.source_imgs,
|
314 |
+
)
|
315 |
+
|
316 |
+
if self.select_source == 2 or (self.select_source == 0 and self.source_imgs is not None and self.source is None):
|
317 |
+
if len(result) > 0 and swapped > 0:
|
318 |
+
result_images.extend(result)
|
319 |
+
suffix = "-swapped"
|
320 |
+
for i,x in enumerate(result):
|
321 |
+
try:
|
322 |
+
img_path = save_image(result[i], 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 len(result) == 0:
|
326 |
+
logger.error("Cannot create a result image")
|
327 |
+
|
328 |
+
else:
|
329 |
+
if result is not None and swapped > 0:
|
330 |
+
result_images.append(result)
|
331 |
+
suffix = "-swapped"
|
332 |
+
try:
|
333 |
+
img_path = save_image(result, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png",info=info, p=p, suffix=suffix)
|
334 |
+
except:
|
335 |
+
logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)")
|
336 |
+
elif result is None:
|
337 |
+
logger.error("Cannot create a result image")
|
338 |
+
|
339 |
+
# if len(output) != 0:
|
340 |
+
# split_fullfn = os.path.splitext(img_path[0])
|
341 |
+
# fullfn = split_fullfn[0] + ".txt"
|
342 |
+
# with open(fullfn, 'w', encoding="utf8") as f:
|
343 |
+
# f.writelines(output)
|
344 |
+
|
345 |
+
if shared.opts.return_grid and len(result_images) > 2 and postprocess_run:
|
346 |
+
grid = make_grid(result_images)
|
347 |
+
result_images.insert(0, grid)
|
348 |
+
try:
|
349 |
+
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)
|
350 |
+
except:
|
351 |
+
logger.error("Cannot save a grid - please, check SD WebUI Settings (Saving and Paths)")
|
352 |
+
|
353 |
+
processed.images = result_images
|
354 |
+
# processed.infotexts = result_info
|
355 |
+
|
356 |
+
def postprocess_batch(self, p, *args, **kwargs):
|
357 |
+
if self.enable and not self.save_original:
|
358 |
+
logger.debug("*** Check postprocess_batch")
|
359 |
+
images = kwargs["images"]
|
360 |
+
|
361 |
+
def postprocess_image(self, p, script_pp: scripts.PostprocessImageArgs, *args):
|
362 |
+
if self.enable and self.swap_in_generated and not self.save_original and ((self.select_source == 0 and self.source is not None) or self.select_source == 1):
|
363 |
+
|
364 |
+
logger.debug("*** Check postprocess_image")
|
365 |
+
|
366 |
+
current_job_number = shared.state.job_no + 1
|
367 |
+
job_count = shared.state.job_count
|
368 |
+
if current_job_number == job_count:
|
369 |
+
reset_messaged()
|
370 |
+
if check_process_halt():
|
371 |
+
return
|
372 |
+
|
373 |
+
# if (self.source is not None and self.select_source == 0) or ((self.face_model is not None and self.face_model != "None") and self.select_source == 1):
|
374 |
+
logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
375 |
+
image: Image.Image = script_pp.image
|
376 |
+
result, output, swapped = swap_face(
|
377 |
+
self.source,
|
378 |
+
image,
|
379 |
+
source_faces_index=self.source_faces_index,
|
380 |
+
faces_index=self.faces_index,
|
381 |
+
model=self.model,
|
382 |
+
enhancement_options=self.enhancement_options,
|
383 |
+
gender_source=self.gender_source,
|
384 |
+
gender_target=self.gender_target,
|
385 |
+
source_hash_check=self.source_hash_check,
|
386 |
+
target_hash_check=self.target_hash_check,
|
387 |
+
device=self.device,
|
388 |
+
mask_face=self.mask_face,
|
389 |
+
select_source=self.select_source,
|
390 |
+
face_model = self.face_model,
|
391 |
+
source_folder = None,
|
392 |
+
source_imgs = None,
|
393 |
+
)
|
394 |
+
try:
|
395 |
+
pp = scripts_postprocessing.PostprocessedImage(result)
|
396 |
+
pp.info = {}
|
397 |
+
p.extra_generation_params.update(pp.info)
|
398 |
+
script_pp.image = pp.image
|
399 |
+
|
400 |
+
# if len(output) != 0:
|
401 |
+
# result_path = get_image_path(script_pp.image, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "txt", p=p, suffix="-swapped")
|
402 |
+
# if len(output) != 0:
|
403 |
+
# with open(result_path, 'w', encoding="utf8") as f:
|
404 |
+
# f.writelines(output)
|
405 |
+
except:
|
406 |
+
logger.error("Cannot create a result image")
|
407 |
+
|
408 |
+
|
409 |
+
class FaceSwapScriptExtras(scripts_postprocessing.ScriptPostprocessing):
|
410 |
+
name = 'ReActor'
|
411 |
+
order = 20000
|
412 |
+
|
413 |
+
def ui(self):
|
414 |
+
with ui_components.InputAccordion(False, label=f"{app_title}") as enable:
|
415 |
+
# with gr.Accordion(f"{app_title}", open=False):
|
416 |
+
|
417 |
+
# SD.Next fix
|
418 |
+
if get_SDNEXT():
|
419 |
+
enable = gr.Checkbox(False, label="Enable")
|
420 |
+
|
421 |
+
# enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}")
|
422 |
+
gr.Markdown(f"<span style='display:block;font-size:0.75em;margin-bottom:-24px;'>The Fast and Simple FaceSwap Extension - {version_flag}</span>")
|
423 |
+
|
424 |
+
# TAB MAIN
|
425 |
+
msgs: dict = {
|
426 |
+
"extra_multiple_source": " | Сomparison grid as a result",
|
427 |
+
}
|
428 |
+
img, imgs, select_source, face_model, source_folder, save_original, mask_face, source_faces_index, gender_source, faces_index, gender_target, face_restorer_name, face_restorer_visibility, codeformer_weight, swap_in_source, swap_in_generated = ui_main.show(is_img2img=False, show_br=False, **msgs)
|
429 |
+
|
430 |
+
# TAB UPSCALE
|
431 |
+
restore_first, upscaler_name, upscaler_scale, upscaler_visibility = ui_upscale.show(show_br=False)
|
432 |
+
|
433 |
+
# TAB TOOLS
|
434 |
+
ui_tools.show()
|
435 |
+
|
436 |
+
# TAB SETTINGS
|
437 |
+
model, device, console_logging_level, source_hash_check, target_hash_check = ui_settings.show(hash_check_block=False)
|
438 |
+
|
439 |
+
gr.Markdown("<span style='display:block;text-align:right;padding-right:3px;font-size:0.666em;margin: -9px 0'>by <a style='font-weight:normal' href='https://github.com/Gourieff' target='_blank'>Eugene Gourieff</a></span>")
|
440 |
+
|
441 |
+
args = {
|
442 |
+
'img': img,
|
443 |
+
'enable': enable,
|
444 |
+
'source_faces_index': source_faces_index,
|
445 |
+
'faces_index': faces_index,
|
446 |
+
'model': model,
|
447 |
+
'face_restorer_name': face_restorer_name,
|
448 |
+
'face_restorer_visibility': face_restorer_visibility,
|
449 |
+
'restore_first': restore_first,
|
450 |
+
'upscaler_name': upscaler_name,
|
451 |
+
'upscaler_scale': upscaler_scale,
|
452 |
+
'upscaler_visibility': upscaler_visibility,
|
453 |
+
'console_logging_level': console_logging_level,
|
454 |
+
'gender_source': gender_source,
|
455 |
+
'gender_target': gender_target,
|
456 |
+
'codeformer_weight': codeformer_weight,
|
457 |
+
'device': device,
|
458 |
+
'mask_face': mask_face,
|
459 |
+
'select_source': select_source,
|
460 |
+
'face_model': face_model,
|
461 |
+
'source_folder': source_folder,
|
462 |
+
'imgs': imgs,
|
463 |
+
}
|
464 |
+
return args
|
465 |
+
|
466 |
+
@property
|
467 |
+
def upscaler(self) -> UpscalerData:
|
468 |
+
for upscaler in shared.sd_upscalers:
|
469 |
+
if upscaler.name == self.upscaler_name:
|
470 |
+
return upscaler
|
471 |
+
return None
|
472 |
+
|
473 |
+
@property
|
474 |
+
def face_restorer(self) -> FaceRestoration:
|
475 |
+
for face_restorer in shared.face_restorers:
|
476 |
+
if face_restorer.name() == self.face_restorer_name:
|
477 |
+
return face_restorer
|
478 |
+
return None
|
479 |
+
|
480 |
+
@property
|
481 |
+
def enhancement_options(self) -> EnhancementOptions:
|
482 |
+
return EnhancementOptions(
|
483 |
+
do_restore_first=self.restore_first,
|
484 |
+
scale=self.upscaler_scale,
|
485 |
+
upscaler=self.upscaler,
|
486 |
+
face_restorer=self.face_restorer,
|
487 |
+
upscale_visibility=self.upscaler_visibility,
|
488 |
+
restorer_visibility=self.face_restorer_visibility,
|
489 |
+
codeformer_weight=self.codeformer_weight,
|
490 |
+
)
|
491 |
+
|
492 |
+
def process(self, pp: scripts_postprocessing.PostprocessedImage, **args):
|
493 |
+
if args['enable']:
|
494 |
+
reset_messaged()
|
495 |
+
if check_process_halt():
|
496 |
+
return
|
497 |
+
|
498 |
+
global SWAPPER_MODELS_PATH
|
499 |
+
self.source = args['img']
|
500 |
+
self.face_restorer_name = args['face_restorer_name']
|
501 |
+
self.upscaler_scale = args['upscaler_scale']
|
502 |
+
self.upscaler_visibility = args['upscaler_visibility']
|
503 |
+
self.face_restorer_visibility = args['face_restorer_visibility']
|
504 |
+
self.restore_first = args['restore_first']
|
505 |
+
self.upscaler_name = args['upscaler_name']
|
506 |
+
self.model = os.path.join(SWAPPER_MODELS_PATH, args['model'])
|
507 |
+
self.console_logging_level = args['console_logging_level']
|
508 |
+
self.gender_source = args['gender_source']
|
509 |
+
self.gender_target = args['gender_target']
|
510 |
+
self.codeformer_weight = args['codeformer_weight']
|
511 |
+
self.device = args['device']
|
512 |
+
self.mask_face = args['mask_face']
|
513 |
+
self.select_source = args['select_source']
|
514 |
+
self.face_model = args['face_model']
|
515 |
+
self.source_folder = args['source_folder']
|
516 |
+
self.source_imgs = args['imgs']
|
517 |
+
if self.gender_source is None or self.gender_source == "No":
|
518 |
+
self.gender_source = 0
|
519 |
+
if self.gender_target is None or self.gender_target == "No":
|
520 |
+
self.gender_target = 0
|
521 |
+
self.source_faces_index = [
|
522 |
+
int(x) for x in args['source_faces_index'].strip(",").split(",") if x.isnumeric()
|
523 |
+
]
|
524 |
+
self.faces_index = [
|
525 |
+
int(x) for x in args['faces_index'].strip(",").split(",") if x.isnumeric()
|
526 |
+
]
|
527 |
+
if len(self.source_faces_index) == 0:
|
528 |
+
self.source_faces_index = [0]
|
529 |
+
if len(self.faces_index) == 0:
|
530 |
+
self.faces_index = [0]
|
531 |
+
if self.mask_face is None:
|
532 |
+
self.mask_face = False
|
533 |
+
|
534 |
+
current_job_number = shared.state.job_no + 1
|
535 |
+
job_count = shared.state.job_count
|
536 |
+
if current_job_number == job_count:
|
537 |
+
reset_messaged()
|
538 |
+
|
539 |
+
set_Device(self.device)
|
540 |
+
|
541 |
+
logger.debug("We're here: process() 1")
|
542 |
+
|
543 |
+
if (self.source is not None and self.select_source == 0) or ((self.face_model is not None and self.face_model != "None") and self.select_source == 1) or ((self.source_folder is not None and self.source_folder != "") and self.select_source == 2) or ((self.source_imgs is not None and self.source is None) and self.select_source == 0):
|
544 |
+
|
545 |
+
logger.debug("We're here: process() 2")
|
546 |
+
|
547 |
+
apply_logging_patch(self.console_logging_level)
|
548 |
+
logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
549 |
+
# if self.select_source != 2:
|
550 |
+
image: Image.Image = pp.image
|
551 |
+
result, output, swapped = swap_face(
|
552 |
+
self.source,
|
553 |
+
image,
|
554 |
+
source_faces_index=self.source_faces_index,
|
555 |
+
faces_index=self.faces_index,
|
556 |
+
model=self.model,
|
557 |
+
enhancement_options=self.enhancement_options,
|
558 |
+
gender_source=self.gender_source,
|
559 |
+
gender_target=self.gender_target,
|
560 |
+
source_hash_check=True,
|
561 |
+
target_hash_check=True,
|
562 |
+
device=self.device,
|
563 |
+
mask_face=self.mask_face,
|
564 |
+
select_source=self.select_source,
|
565 |
+
face_model=self.face_model,
|
566 |
+
source_folder=self.source_folder,
|
567 |
+
source_imgs=self.source_imgs,
|
568 |
+
)
|
569 |
+
if self.select_source == 2 or (self.select_source == 0 and self.source_imgs is not None and self.source is None):
|
570 |
+
if len(result) > 0 and swapped > 0:
|
571 |
+
image = result[0]
|
572 |
+
if len(result) > 1:
|
573 |
+
grid = make_grid(result)
|
574 |
+
result.insert(0, grid)
|
575 |
+
image = grid
|
576 |
+
pp.info["ReActor"] = True
|
577 |
+
pp.image = image
|
578 |
+
logger.status("---Done!---")
|
579 |
+
else:
|
580 |
+
logger.error("Cannot create a result image")
|
581 |
+
else:
|
582 |
+
try:
|
583 |
+
pp.info["ReActor"] = True
|
584 |
+
pp.image = result
|
585 |
+
logger.status("---Done!---")
|
586 |
+
except Exception:
|
587 |
+
logger.error("Cannot create a result image")
|
588 |
+
else:
|
589 |
+
logger.error("Please provide a source face")
|
extensions/sd-webui-reactor/scripts/reactor_globals.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from pathlib import Path
|
3 |
+
|
4 |
+
try:
|
5 |
+
from modules.paths_internal import models_path
|
6 |
+
except:
|
7 |
+
try:
|
8 |
+
from modules.paths import models_path
|
9 |
+
except:
|
10 |
+
models_path = os.path.abspath("models")
|
11 |
+
|
12 |
+
IS_RUN: bool = False
|
13 |
+
BASE_PATH = os.path.join(Path(__file__).parents[1])
|
14 |
+
DEVICE_LIST: list = ["CPU", "CUDA"]
|
15 |
+
|
16 |
+
MODELS_PATH = models_path
|
17 |
+
SWAPPER_MODELS_PATH = os.path.join(MODELS_PATH, "insightface")
|
18 |
+
REACTOR_MODELS_PATH = os.path.join(MODELS_PATH, "reactor")
|
19 |
+
FACE_MODELS_PATH = os.path.join(REACTOR_MODELS_PATH, "faces")
|
20 |
+
|
21 |
+
IS_SDNEXT = False
|
22 |
+
|
23 |
+
if not os.path.exists(REACTOR_MODELS_PATH):
|
24 |
+
os.makedirs(REACTOR_MODELS_PATH)
|
25 |
+
if not os.path.exists(FACE_MODELS_PATH):
|
26 |
+
os.makedirs(FACE_MODELS_PATH)
|
27 |
+
|
28 |
+
def updateDevice():
|
29 |
+
try:
|
30 |
+
LAST_DEVICE_PATH = os.path.join(BASE_PATH, "last_device.txt")
|
31 |
+
with open(LAST_DEVICE_PATH) as f:
|
32 |
+
device = f.readline().strip()
|
33 |
+
if device not in DEVICE_LIST:
|
34 |
+
print(f"Error: Device {device} is not in DEVICE_LIST")
|
35 |
+
device = DEVICE_LIST[0]
|
36 |
+
print(f"Execution Provider has been set to {device}")
|
37 |
+
except Exception as e:
|
38 |
+
device = DEVICE_LIST[0]
|
39 |
+
print(f"Error: {e}\nExecution Provider has been set to {device}")
|
40 |
+
return device
|
41 |
+
|
42 |
+
DEVICE = updateDevice()
|
extensions/sd-webui-reactor/scripts/reactor_helpers.py
ADDED
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, glob
|
2 |
+
from collections import Counter
|
3 |
+
from PIL import Image
|
4 |
+
from math import isqrt, ceil
|
5 |
+
from typing import List
|
6 |
+
import logging
|
7 |
+
import hashlib
|
8 |
+
import torch
|
9 |
+
from safetensors.torch import save_file, safe_open
|
10 |
+
from insightface.app.common import Face
|
11 |
+
|
12 |
+
from modules.images import FilenameGenerator, get_next_sequence_number
|
13 |
+
from modules import shared, script_callbacks
|
14 |
+
from scripts.reactor_globals import DEVICE, BASE_PATH, FACE_MODELS_PATH, IS_SDNEXT
|
15 |
+
|
16 |
+
try:
|
17 |
+
from modules.paths_internal import models_path
|
18 |
+
except:
|
19 |
+
try:
|
20 |
+
from modules.paths import models_path
|
21 |
+
except:
|
22 |
+
model_path = os.path.abspath("models")
|
23 |
+
|
24 |
+
MODELS_PATH = None
|
25 |
+
|
26 |
+
def set_Device(value):
|
27 |
+
global DEVICE
|
28 |
+
DEVICE = value
|
29 |
+
with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
|
30 |
+
txt.write(DEVICE)
|
31 |
+
|
32 |
+
def get_Device():
|
33 |
+
global DEVICE
|
34 |
+
return DEVICE
|
35 |
+
|
36 |
+
def set_SDNEXT():
|
37 |
+
global IS_SDNEXT
|
38 |
+
IS_SDNEXT = True
|
39 |
+
|
40 |
+
def get_SDNEXT():
|
41 |
+
global IS_SDNEXT
|
42 |
+
return IS_SDNEXT
|
43 |
+
|
44 |
+
def make_grid(image_list: List):
|
45 |
+
|
46 |
+
# Count the occurrences of each image size in the image_list
|
47 |
+
size_counter = Counter(image.size for image in image_list)
|
48 |
+
|
49 |
+
# Get the most common image size (size with the highest count)
|
50 |
+
common_size = size_counter.most_common(1)[0][0]
|
51 |
+
|
52 |
+
# Filter the image_list to include only images with the common size
|
53 |
+
image_list = [image for image in image_list if image.size == common_size]
|
54 |
+
|
55 |
+
# Get the dimensions (width and height) of the common size
|
56 |
+
size = common_size
|
57 |
+
|
58 |
+
# If there are more than one image in the image_list
|
59 |
+
if len(image_list) > 1:
|
60 |
+
num_images = len(image_list)
|
61 |
+
|
62 |
+
# Calculate the number of rows and columns for the grid
|
63 |
+
rows = isqrt(num_images)
|
64 |
+
cols = ceil(num_images / rows)
|
65 |
+
|
66 |
+
# Calculate the size of the square image
|
67 |
+
square_size = (cols * size[0], rows * size[1])
|
68 |
+
|
69 |
+
# Create a new RGB image with the square size
|
70 |
+
square_image = Image.new("RGB", square_size)
|
71 |
+
|
72 |
+
# Paste each image onto the square image at the appropriate position
|
73 |
+
for i, image in enumerate(image_list):
|
74 |
+
row = i // cols
|
75 |
+
col = i % cols
|
76 |
+
|
77 |
+
square_image.paste(image, (col * size[0], row * size[1]))
|
78 |
+
|
79 |
+
# Return the resulting square image
|
80 |
+
return square_image
|
81 |
+
|
82 |
+
# Return None if there are no images or only one image in the image_list
|
83 |
+
return None
|
84 |
+
|
85 |
+
def get_image_path(image, path, basename, seed=None, prompt=None, extension='png', p=None, suffix=""):
|
86 |
+
|
87 |
+
namegen = FilenameGenerator(p, seed, prompt, image)
|
88 |
+
|
89 |
+
save_to_dirs = shared.opts.save_to_dirs
|
90 |
+
|
91 |
+
if save_to_dirs:
|
92 |
+
dirname = namegen.apply(shared.opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
|
93 |
+
path = os.path.join(path, dirname)
|
94 |
+
|
95 |
+
os.makedirs(path, exist_ok=True)
|
96 |
+
|
97 |
+
if seed is None:
|
98 |
+
file_decoration = ""
|
99 |
+
elif shared.opts.save_to_dirs:
|
100 |
+
file_decoration = shared.opts.samples_filename_pattern or "[seed]"
|
101 |
+
else:
|
102 |
+
file_decoration = shared.opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
|
103 |
+
|
104 |
+
file_decoration = namegen.apply(file_decoration) + suffix
|
105 |
+
|
106 |
+
add_number = shared.opts.save_images_add_number or file_decoration == ''
|
107 |
+
|
108 |
+
if file_decoration != "" and add_number:
|
109 |
+
file_decoration = f"-{file_decoration}"
|
110 |
+
|
111 |
+
if add_number:
|
112 |
+
basecount = get_next_sequence_number(path, basename)
|
113 |
+
fullfn = None
|
114 |
+
for i in range(500):
|
115 |
+
fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
|
116 |
+
fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
|
117 |
+
if not os.path.exists(fullfn):
|
118 |
+
break
|
119 |
+
else:
|
120 |
+
fullfn = os.path.join(path, f"{file_decoration}.{extension}")
|
121 |
+
|
122 |
+
pnginfo = {}
|
123 |
+
|
124 |
+
params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
|
125 |
+
# script_callbacks.before_image_saved_callback(params)
|
126 |
+
|
127 |
+
fullfn = params.filename
|
128 |
+
|
129 |
+
fullfn_without_extension, extension = os.path.splitext(params.filename)
|
130 |
+
if hasattr(os, 'statvfs'):
|
131 |
+
max_name_len = os.statvfs(path).f_namemax
|
132 |
+
fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
|
133 |
+
params.filename = fullfn_without_extension + extension
|
134 |
+
fullfn = params.filename
|
135 |
+
|
136 |
+
return fullfn
|
137 |
+
|
138 |
+
def addLoggingLevel(levelName, levelNum, methodName=None):
|
139 |
+
if not methodName:
|
140 |
+
methodName = levelName.lower()
|
141 |
+
|
142 |
+
def logForLevel(self, message, *args, **kwargs):
|
143 |
+
if self.isEnabledFor(levelNum):
|
144 |
+
self._log(levelNum, message, args, **kwargs)
|
145 |
+
|
146 |
+
def logToRoot(message, *args, **kwargs):
|
147 |
+
logging.log(levelNum, message, *args, **kwargs)
|
148 |
+
|
149 |
+
logging.addLevelName(levelNum, levelName)
|
150 |
+
setattr(logging, levelName, levelNum)
|
151 |
+
setattr(logging.getLoggerClass(), methodName, logForLevel)
|
152 |
+
setattr(logging, methodName, logToRoot)
|
153 |
+
|
154 |
+
def get_image_md5hash(image: Image.Image):
|
155 |
+
md5hash = hashlib.md5(image.tobytes())
|
156 |
+
return md5hash.hexdigest()
|
157 |
+
|
158 |
+
def save_face_model(face: Face, filename: str) -> None:
|
159 |
+
try:
|
160 |
+
tensors = {
|
161 |
+
"bbox": torch.tensor(face["bbox"]),
|
162 |
+
"kps": torch.tensor(face["kps"]),
|
163 |
+
"det_score": torch.tensor(face["det_score"]),
|
164 |
+
"landmark_3d_68": torch.tensor(face["landmark_3d_68"]),
|
165 |
+
"pose": torch.tensor(face["pose"]),
|
166 |
+
"landmark_2d_106": torch.tensor(face["landmark_2d_106"]),
|
167 |
+
"embedding": torch.tensor(face["embedding"]),
|
168 |
+
"gender": torch.tensor(face["gender"]),
|
169 |
+
"age": torch.tensor(face["age"]),
|
170 |
+
}
|
171 |
+
save_file(tensors, filename)
|
172 |
+
# print(f"Face model has been saved to '{filename}'")
|
173 |
+
except Exception as e:
|
174 |
+
print(f"Error: {e}")
|
175 |
+
|
176 |
+
def get_models():
|
177 |
+
global MODELS_PATH
|
178 |
+
models_path_init = os.path.join(models_path, "insightface/*")
|
179 |
+
models = glob.glob(models_path_init)
|
180 |
+
models = [x for x in models if x.endswith(".onnx") or x.endswith(".pth")]
|
181 |
+
models_names = []
|
182 |
+
for model in models:
|
183 |
+
model_path = os.path.split(model)
|
184 |
+
if MODELS_PATH is None:
|
185 |
+
MODELS_PATH = model_path[0]
|
186 |
+
model_name = model_path[1]
|
187 |
+
models_names.append(model_name)
|
188 |
+
return models_names
|
189 |
+
|
190 |
+
def load_face_model(filename: str):
|
191 |
+
face = {}
|
192 |
+
model_path = os.path.join(FACE_MODELS_PATH, filename)
|
193 |
+
with safe_open(model_path, framework="pt") as f:
|
194 |
+
for k in f.keys():
|
195 |
+
face[k] = f.get_tensor(k).numpy()
|
196 |
+
return Face(face)
|
197 |
+
|
198 |
+
def get_facemodels():
|
199 |
+
models_path = os.path.join(FACE_MODELS_PATH, "*")
|
200 |
+
models = glob.glob(models_path)
|
201 |
+
models = [x for x in models if x.endswith(".safetensors")]
|
202 |
+
return models
|
203 |
+
|
204 |
+
def get_model_names(get_models):
|
205 |
+
models = get_models()
|
206 |
+
names = ["None"]
|
207 |
+
for x in models:
|
208 |
+
names.append(os.path.basename(x))
|
209 |
+
return names
|
210 |
+
|
211 |
+
def get_images_from_folder(path: str):
|
212 |
+
images_path = os.path.join(path, "*")
|
213 |
+
images = glob.glob(images_path)
|
214 |
+
return [Image.open(x) for x in images if x.endswith(('jpg', 'png', 'jpeg', 'webp', 'bmp'))]
|
215 |
+
|
216 |
+
def get_images_from_list(imgs: List):
|
217 |
+
return [Image.open(os.path.abspath(x.name)) for x in imgs]
|
extensions/sd-webui-reactor/scripts/reactor_inferencers/__pycache__/bisenet_mask_generator.cpython-310.pyc
ADDED
Binary file (2.98 kB). View file
|
|
extensions/sd-webui-reactor/scripts/reactor_inferencers/__pycache__/mask_generator.cpython-310.pyc
ADDED
Binary file (1.56 kB). View file
|
|
extensions/sd-webui-reactor/scripts/reactor_inferencers/bisenet_mask_generator.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List, Tuple
|
2 |
+
|
3 |
+
import cv2
|
4 |
+
import modules.shared as shared
|
5 |
+
import numpy as np
|
6 |
+
import torch
|
7 |
+
from facexlib.parsing import init_parsing_model
|
8 |
+
from facexlib.utils.misc import img2tensor
|
9 |
+
from torchvision.transforms.functional import normalize
|
10 |
+
from scripts.reactor_inferencers.mask_generator import MaskGenerator
|
11 |
+
|
12 |
+
class BiSeNetMaskGenerator(MaskGenerator):
|
13 |
+
def __init__(self) -> None:
|
14 |
+
self.mask_model = init_parsing_model(device=shared.device)
|
15 |
+
|
16 |
+
def name(self):
|
17 |
+
return "BiSeNet"
|
18 |
+
|
19 |
+
def generate_mask(
|
20 |
+
self,
|
21 |
+
face_image: np.ndarray,
|
22 |
+
face_area_on_image: Tuple[int, int, int, int],
|
23 |
+
affected_areas: List[str],
|
24 |
+
mask_size: int,
|
25 |
+
use_minimal_area: bool,
|
26 |
+
fallback_ratio: float = 0.25,
|
27 |
+
**kwargs,
|
28 |
+
) -> np.ndarray:
|
29 |
+
# original_face_image = face_image
|
30 |
+
face_image = face_image.copy()
|
31 |
+
face_image = face_image[:, :, ::-1]
|
32 |
+
|
33 |
+
if use_minimal_area:
|
34 |
+
face_image = MaskGenerator.mask_non_face_areas(face_image, face_area_on_image)
|
35 |
+
|
36 |
+
h, w, _ = face_image.shape
|
37 |
+
|
38 |
+
if w != 512 or h != 512:
|
39 |
+
rw = (int(w * (512 / w)) // 8) * 8
|
40 |
+
rh = (int(h * (512 / h)) // 8) * 8
|
41 |
+
face_image = cv2.resize(face_image, dsize=(rw, rh))
|
42 |
+
|
43 |
+
face_tensor = img2tensor(face_image.astype("float32") / 255.0, float32=True)
|
44 |
+
normalize(face_tensor, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
|
45 |
+
face_tensor = torch.unsqueeze(face_tensor, 0).to(shared.device)
|
46 |
+
|
47 |
+
with torch.no_grad():
|
48 |
+
face = self.mask_model(face_tensor)[0]
|
49 |
+
face = face.squeeze(0).cpu().numpy().argmax(0)
|
50 |
+
face = face.copy().astype(np.uint8)
|
51 |
+
|
52 |
+
mask = self.__to_mask(face, affected_areas)
|
53 |
+
|
54 |
+
if mask_size > 0:
|
55 |
+
mask = cv2.dilate(mask, np.ones((5, 5), np.uint8), iterations=mask_size)
|
56 |
+
|
57 |
+
if w != 512 or h != 512:
|
58 |
+
mask = cv2.resize(mask, dsize=(w, h))
|
59 |
+
|
60 |
+
# """if MaskGenerator.calculate_mask_coverage(mask) < fallback_ratio:
|
61 |
+
# logger.info("Use fallback mask generator")
|
62 |
+
# mask = self.fallback_mask_generator.generate_mask(
|
63 |
+
# original_face_image, face_area_on_image, use_minimal_area=True
|
64 |
+
# )"""
|
65 |
+
|
66 |
+
return mask
|
67 |
+
|
68 |
+
def __to_mask(self, face: np.ndarray, affected_areas: List[str]) -> np.ndarray:
|
69 |
+
keep_face = "Face" in affected_areas
|
70 |
+
keep_neck = "Neck" in affected_areas
|
71 |
+
keep_hair = "Hair" in affected_areas
|
72 |
+
keep_hat = "Hat" in affected_areas
|
73 |
+
|
74 |
+
mask = np.zeros((face.shape[0], face.shape[1], 3), dtype=np.uint8)
|
75 |
+
num_of_class = np.max(face)
|
76 |
+
for i in range(1, num_of_class + 1):
|
77 |
+
index = np.where(face == i)
|
78 |
+
if i < 14 and keep_face:
|
79 |
+
mask[index[0], index[1], :] = [255, 255, 255]
|
80 |
+
elif i == 14 and keep_neck:
|
81 |
+
mask[index[0], index[1], :] = [255, 255, 255]
|
82 |
+
elif i == 17 and keep_hair:
|
83 |
+
mask[index[0], index[1], :] = [255, 255, 255]
|
84 |
+
elif i == 18 and keep_hat:
|
85 |
+
mask[index[0], index[1], :] = [255, 255, 255]
|
86 |
+
return mask
|
extensions/sd-webui-reactor/scripts/reactor_inferencers/mask_generator.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import ABC, abstractmethod
|
2 |
+
from typing import Tuple
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
class MaskGenerator(ABC):
|
8 |
+
@abstractmethod
|
9 |
+
def name(self) -> str:
|
10 |
+
pass
|
11 |
+
|
12 |
+
@abstractmethod
|
13 |
+
def generate_mask(
|
14 |
+
self,
|
15 |
+
face_image: np.ndarray,
|
16 |
+
face_area_on_image: Tuple[int, int, int, int],
|
17 |
+
**kwargs,
|
18 |
+
) -> np.ndarray:
|
19 |
+
pass
|
20 |
+
|
21 |
+
@staticmethod
|
22 |
+
def mask_non_face_areas(image: np.ndarray, face_area_on_image: Tuple[int, int, int, int]) -> np.ndarray:
|
23 |
+
left, top, right, bottom = face_area_on_image
|
24 |
+
image = image.copy()
|
25 |
+
image[:top, :] = 0
|
26 |
+
image[bottom:, :] = 0
|
27 |
+
image[:, :left] = 0
|
28 |
+
image[:, right:] = 0
|
29 |
+
return image
|
30 |
+
|
31 |
+
@staticmethod
|
32 |
+
def calculate_mask_coverage(mask: np.ndarray):
|
33 |
+
gray_mask = cv2.cvtColor(mask, cv2.COLOR_RGB2GRAY)
|
34 |
+
non_black_pixels = np.count_nonzero(gray_mask)
|
35 |
+
total_pixels = gray_mask.size
|
36 |
+
return non_black_pixels / total_pixels
|
extensions/sd-webui-reactor/scripts/reactor_logger.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import copy
|
3 |
+
import sys
|
4 |
+
|
5 |
+
from modules import shared
|
6 |
+
from scripts.reactor_globals import IS_RUN
|
7 |
+
from scripts.reactor_helpers import addLoggingLevel
|
8 |
+
|
9 |
+
|
10 |
+
class ColoredFormatter(logging.Formatter):
|
11 |
+
COLORS = {
|
12 |
+
"DEBUG": "\033[0;36m", # CYAN
|
13 |
+
"STATUS": "\033[38;5;173m", # Calm ORANGE
|
14 |
+
"INFO": "\033[0;32m", # GREEN
|
15 |
+
"WARNING": "\033[0;33m", # YELLOW
|
16 |
+
"ERROR": "\033[0;31m", # RED
|
17 |
+
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
|
18 |
+
"RESET": "\033[0m", # RESET COLOR
|
19 |
+
}
|
20 |
+
|
21 |
+
def format(self, record):
|
22 |
+
colored_record = copy.copy(record)
|
23 |
+
levelname = colored_record.levelname
|
24 |
+
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
|
25 |
+
colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
|
26 |
+
return super().format(colored_record)
|
27 |
+
|
28 |
+
|
29 |
+
# Create a new logger
|
30 |
+
logger = logging.getLogger("ReActor")
|
31 |
+
logger.propagate = False
|
32 |
+
|
33 |
+
# Add Custom Level
|
34 |
+
addLoggingLevel("STATUS", logging.INFO + 5)
|
35 |
+
|
36 |
+
# Add handler if we don't have one.
|
37 |
+
if not logger.handlers:
|
38 |
+
handler = logging.StreamHandler(sys.stdout)
|
39 |
+
handler.setFormatter(
|
40 |
+
ColoredFormatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s","%H:%M:%S")
|
41 |
+
)
|
42 |
+
logger.addHandler(handler)
|
43 |
+
|
44 |
+
# Configure logger
|
45 |
+
loglevel_string = getattr(shared.cmd_opts, "reactor_loglevel", "INFO")
|
46 |
+
loglevel = getattr(logging, loglevel_string.upper(), "info")
|
47 |
+
logger.setLevel(loglevel)
|
48 |
+
|
49 |
+
def set_Run(value):
|
50 |
+
global IS_RUN
|
51 |
+
IS_RUN = value
|
52 |
+
|
53 |
+
def get_Run():
|
54 |
+
global IS_RUN
|
55 |
+
return IS_RUN
|