Compare commits
113 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c6a6e6352 | ||
|
|
c7b8556856 | ||
|
|
0458e56cb9 | ||
|
|
17f031356a | ||
|
|
58ddc725db | ||
|
|
d74478114f | ||
|
|
f680b43100 | ||
|
|
7298d8650d | ||
|
|
1242914609 | ||
|
|
da963b8796 | ||
|
|
4493fd7133 | ||
|
|
613b7d74ea | ||
|
|
1ee4d0e949 | ||
|
|
5255d497a7 | ||
|
|
9b0cc02791 | ||
|
|
ad51f737d1 | ||
|
|
d2f6b7d29d | ||
|
|
f57c2acc55 | ||
|
|
d2e78be2b3 | ||
|
|
8f2106569c | ||
|
|
be31df8040 | ||
|
|
2b945ae0b2 | ||
|
|
7633e58182 | ||
|
|
97598387b1 | ||
|
|
1b706db767 | ||
|
|
8651bc2639 | ||
|
|
b7b094ba78 | ||
|
|
bb3e97c74c | ||
|
|
ae57149962 | ||
|
|
d7e7ddff7b | ||
|
|
9989610fa7 | ||
|
|
0185d7a2af | ||
|
|
99b0f19553 | ||
|
|
0d03e020bb | ||
|
|
e215bd6763 | ||
|
|
8fc0de58f6 | ||
|
|
b6e394de62 | ||
|
|
6c3bf1c6c4 | ||
|
|
565704285b | ||
|
|
8fafab9777 | ||
|
|
d897370276 | ||
|
|
778ddec96d | ||
|
|
9778e4f208 | ||
|
|
96d7a06291 | ||
|
|
4a7a367ea1 | ||
|
|
a93e04ea13 | ||
|
|
c745fa2911 | ||
|
|
c5ecf9a194 | ||
|
|
de43816a3b | ||
|
|
472c75ee88 | ||
|
|
4b1cfc70e8 | ||
|
|
be546524af | ||
|
|
805a0cae17 | ||
|
|
d8e300b202 | ||
|
|
ed66d91819 | ||
|
|
3b50def406 | ||
|
|
fda111bb3d | ||
|
|
905bd73189 | ||
|
|
e62ff09e5c | ||
|
|
7706d6aa34 | ||
|
|
20d2131e81 | ||
|
|
d11a8a6941 | ||
|
|
70479479b3 | ||
|
|
99e374e4f5 | ||
|
|
bee2c4ee2d | ||
|
|
2c2d40508a | ||
|
|
8b66464e6f | ||
|
|
a59cd5ad41 | ||
|
|
87cd569324 | ||
|
|
24c9502a3c | ||
|
|
16b47606f9 | ||
|
|
67bcfdb16c | ||
|
|
fda2ae3fa1 | ||
|
|
4139d167ff | ||
|
|
ee742ec43e | ||
|
|
0fee58d4bf | ||
|
|
d57dc191d6 | ||
|
|
524c4b78b3 | ||
|
|
bbc2481494 | ||
|
|
b75aa16b11 | ||
|
|
4721a4baef | ||
|
|
6de674ea8a | ||
|
|
0c11aeb640 | ||
|
|
cec1d41dc7 | ||
|
|
6aed6ae141 | ||
|
|
780357ee0c | ||
|
|
44811e02ed | ||
|
|
1f1272ae23 | ||
|
|
6be9162b1a | ||
|
|
4e877445ba | ||
|
|
5cfbd14b04 | ||
|
|
6a110ccaa3 | ||
|
|
55a6c5300b | ||
|
|
f42bc37f2c | ||
|
|
0070cea333 | ||
|
|
077862376e | ||
|
|
6d6981acbb | ||
|
|
7950a546c5 | ||
|
|
929d70c019 | ||
|
|
1930e95658 | ||
|
|
f3457468b0 | ||
|
|
79c123942d | ||
|
|
41d5b1e3ad | ||
|
|
9e33a555bd | ||
|
|
77fbd6ea21 | ||
|
|
bf1814c81a | ||
|
|
74dde0910b | ||
|
|
53f4b3d677 | ||
|
|
96c124491e | ||
|
|
095191a160 | ||
|
|
3c36c6b075 | ||
|
|
0901ab9ed4 | ||
|
|
376c19c62f |
58
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
58
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
name: Bug Report
|
||||||
|
description: You think somethings is broken
|
||||||
|
labels: ["bug", "new"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: checkboxes
|
||||||
|
attributes:
|
||||||
|
label: First, confirm
|
||||||
|
description: Make sure you use the latest version of the ReActor extension and you have already searched to see if an issue already exists for the bug you encountered before you create a new Issue.
|
||||||
|
options:
|
||||||
|
- label: I have read the [instruction](https://github.com/Gourieff/sd-webui-reactor/blob/main/README.md) carefully
|
||||||
|
required: true
|
||||||
|
- label: I have searched the existing issues
|
||||||
|
required: true
|
||||||
|
- label: I have updated the extension to the latest version
|
||||||
|
required: true
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
*Please fill this form with as much information as possible and *provide screenshots if possible**
|
||||||
|
- type: textarea
|
||||||
|
id: what-did
|
||||||
|
attributes:
|
||||||
|
label: What happened?
|
||||||
|
description: Tell what happened in a very clear and simple way
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: steps
|
||||||
|
attributes:
|
||||||
|
label: Steps to reproduce the problem
|
||||||
|
description: Please provide with precise step by step instructions on how to reproduce the bug
|
||||||
|
value: |
|
||||||
|
1. Go to ....
|
||||||
|
2. Press ....
|
||||||
|
3. ...
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: sysinfo
|
||||||
|
attributes:
|
||||||
|
label: Sysinfo
|
||||||
|
description: Describe your platform. OS, browser, GPU, what SD WebUI you use, what version and what extensions are also enabled. If you use A1111 you can generate "System info file" (Settings -> Sysinfo) and put it here.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: Relevant console log
|
||||||
|
description: Please provide cmd/terminal logs from the moment you started UI to the momemt you got an error. This will be automatically formatted into code, so no need for backticks.
|
||||||
|
render: Shell
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: misc
|
||||||
|
attributes:
|
||||||
|
label: Additional information
|
||||||
|
description: Please provide with any relevant additional info or context.
|
||||||
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
contact_links:
|
||||||
|
- name: ReActor Extension Community Support
|
||||||
|
url: https://github.com/Gourieff/sd-webui-reactor/discussions
|
||||||
|
about: Please ask and answer questions here.
|
||||||
16
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
16
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
name: Feature request
|
||||||
|
description: Suggest an idea for this project
|
||||||
|
title: "[Feature]: "
|
||||||
|
labels: ["enhancement", "new"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Feature description
|
||||||
|
description: Describe the feature in a clear and simple way
|
||||||
|
value:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
The best way to propose an idea is to start a new discussion via the [Discussions](https://github.com/Gourieff/sd-webui-reactor/discussions) section (choose the "Idea" category)
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@ -6,4 +6,5 @@ __pycache__/
|
|||||||
.vscode/
|
.vscode/
|
||||||
|
|
||||||
example
|
example
|
||||||
toDo.txt
|
*.txt
|
||||||
|
!requirements.txt
|
||||||
|
|||||||
36
API.md
36
API.md
@ -40,7 +40,7 @@ curl -X POST \
|
|||||||
"target_image": "data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABCAAD/7g...",
|
"target_image": "data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABCAAD/7g...",
|
||||||
"source_faces_index": [0],
|
"source_faces_index": [0],
|
||||||
"face_index": [0],
|
"face_index": [0],
|
||||||
"upscaler": "4x_Struzan_300000",
|
"upscaler": "4x_NMKD-Siax_200k",
|
||||||
"scale": 2,
|
"scale": 2,
|
||||||
"upscale_visibility": 1,
|
"upscale_visibility": 1,
|
||||||
"face_restorer": "CodeFormer",
|
"face_restorer": "CodeFormer",
|
||||||
@ -50,13 +50,26 @@ curl -X POST \
|
|||||||
"gender_source": 0,
|
"gender_source": 0,
|
||||||
"gender_target": 0,
|
"gender_target": 0,
|
||||||
"save_to_file": 0,
|
"save_to_file": 0,
|
||||||
"result_file_path": ""
|
"result_file_path": "",
|
||||||
|
"device": "CUDA",
|
||||||
|
"mask_face": 1,
|
||||||
|
"select_source": 1,
|
||||||
|
"face_model": "elena.safetensors",
|
||||||
|
"source_folder": "C:/faces",
|
||||||
|
"random_image": 1,
|
||||||
|
"upscale_force": 1
|
||||||
}'
|
}'
|
||||||
```
|
```
|
||||||
|
|
||||||
* Set `"upscaler"` to `"None"` and `"scale"` to `1` if you don't need to upscale;
|
* Set `"upscaler"` to `"None"` and `"scale"` to `1` if you don't need to upscale;
|
||||||
* Set `"save_to_file"` to `1` if you need to save result to a file;
|
* Set `"save_to_file"` to `1` if you need to save result to a file;
|
||||||
* `"result_file_path"` is set to the `"outputs/api"` folder by default (please, create the folder beforehand to avoid any errors) with a timestamped filename; (output_YYYY-MM-DD_hh-mm-ss), you can set any specific path, e.g. `"C:/stable-diffusion-webui/outputs/api/output.png"`.
|
* `"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"`;
|
||||||
|
* Set `"mask_face"` to `1` if you want ReActor to mask the face or to `0` if want ReActor to create a bbox around the face;
|
||||||
|
* Set `"select_source"` to: 0 - Image, 1 - Face Model, 2 - Source Folder;
|
||||||
|
* Set `"face_model"` to the face model file you want to choose if you set `"select_source": 1`;
|
||||||
|
* Set `"source_folder"` to the path with source images (with faces you need as the results) if you set `"select_source": 2`;
|
||||||
|
* Set `"random_image"` to `1` if want ReActor to choose a random image from the path of `"source_folder"`;
|
||||||
|
* Set `"upscale_force"` to `1` if you want ReActor to upscale the image even if no face found.
|
||||||
|
|
||||||
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).
|
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).
|
||||||
|
|
||||||
@ -69,3 +82,20 @@ As a result you recieve a "base64" image:
|
|||||||
A list of available models can be seen by GET:
|
A list of available models can be seen by GET:
|
||||||
* http://127.0.0.1:7860/reactor/models
|
* http://127.0.0.1:7860/reactor/models
|
||||||
* http://127.0.0.1:7860/reactor/upscalers
|
* http://127.0.0.1:7860/reactor/upscalers
|
||||||
|
* http://127.0.0.1:7860/reactor/facemodels
|
||||||
|
|
||||||
|
### FaceModel Buid API
|
||||||
|
|
||||||
|
Send POST to http://127.0.0.1:7860/reactor/facemodels with body:
|
||||||
|
|
||||||
|
```
|
||||||
|
{
|
||||||
|
"source_images": ["data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABQAAD/7g...","data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABQAAD/7g...","data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABQAAD/7g..."],
|
||||||
|
"name": "my_super_model",
|
||||||
|
"compute_method": 0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
where:<br>
|
||||||
|
"source_images" is a list of base64 encoded images,<br>
|
||||||
|
"compute_method" is: 0 - Mean, 1- Median, 2 - Mode
|
||||||
|
|||||||
271
README.md
271
README.md
@ -1,8 +1,19 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
<img src="example/ReActor_logo_red.png" alt="logo" width="180px"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_EN.png?raw=true" alt="logo" width="180px"/>
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
<a href="https://boosty.to/artgourieff" target="_blank">
|
||||||
|
<img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/>
|
||||||
|
<br>
|
||||||
|
<sup>
|
||||||
|
Support This Project
|
||||||
|
</sup>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<hr>
|
||||||
|
|
||||||
<hr>
|
|
||||||
[](https://github.com/Gourieff/sd-webui-reactor/commits/main)
|
[](https://github.com/Gourieff/sd-webui-reactor/commits/main)
|
||||||

|

|
||||||
[](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
|
[](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
|
||||||
@ -13,46 +24,102 @@
|
|||||||
|
|
||||||
# ReActor for Stable Diffusion
|
# ReActor for Stable Diffusion
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
### The Fast and Simple FaceSwap Extension with a lot of improvements and without NSFW filter (uncensored, use it on your own [responsibility](#disclaimer))
|
### The Fast and Simple FaceSwap Extension with a lot of improvements and without NSFW filter (uncensored, use it on your own [responsibility](#disclaimer))
|
||||||
|
|
||||||
> Ex "Roop-GE" (GE - Gourieff Edition, aka "NSFW-Roop"), the extension was renamed with the version 0.3.0<br>
|
|
||||||
> Repository old link: `https://github.com/Gourieff/sd-webui-roop-nsfw`
|
|
||||||
|
|
||||||
---
|
---
|
||||||
<div align="center">
|
|
||||||
<b>
|
<b>
|
||||||
<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>
|
<a href="#latestupdate">What's new</a> | <a href="#installation">Installation</a> | <a href="#features">Features</a> | <a href="#usage">Usage</a> | <a href="#api">API</a> | <a href="#troubleshooting">Troubleshooting</a> | <a href="#updating">Updating</a> | <a href="#comfyui">ComfyUI</a> | <a href="#disclaimer">Disclaimer</a>
|
||||||
</b>
|
</b>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
<table>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
|
||||||
<tr>
|
|
||||||
<td width="144px">
|
|
||||||
<a href="https://boosty.to/artgourieff" target="_blank">
|
|
||||||
<img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/>
|
|
||||||
<br>
|
|
||||||
<sup>
|
|
||||||
Support This Project
|
|
||||||
</sup>
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
ReActor is an extension for Stable Diffusion WebUI that allows a very easy and accurate face-replacement (face swap) in images. Based on <a href="https://github.com/Gourieff/ReActor-UI" target="_blank">ReActor-UI</a>.
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<img src="example/demo_crop.jpg" alt="example"/>
|
<a name="latestupdate">
|
||||||
|
|
||||||
|
## What's new in the latest updates
|
||||||
|
|
||||||
|
### 0.7.1 <sub><sup>BETA1
|
||||||
|
|
||||||
|
- Allow spaces for face indexes (e.g.: 0, 1, 2)
|
||||||
|
- Sorting of face models list alphabetically
|
||||||
|
- [FaceModels Build API](./API.md#facemodel-build-api)
|
||||||
|
- Fixes and improvements
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><a>Click to expand more</a></summary>
|
||||||
|
|
||||||
|
### 0.7.0 <sub><sup>BETA2
|
||||||
|
|
||||||
|
- X/Y/Z is improved! One more parameter is ready: you can now select several face models to create a variation of swaps to choose the best one!
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-05.jpg?raw=true" alt="0.7.0-whatsnew-05" width="100%"/>
|
||||||
|
|
||||||
|
To use "Face Model" axis - you should enable ReActor and choose any face model as the Source:<br>
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-07.jpg?raw=true" alt="0.7.0-whatsnew-07" width="50%"/><img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-06.jpg?raw=true" alt="0.7.0-whatsnew-06" width="50%"/>
|
||||||
|
|
||||||
|
Full size demo image: [xyz_demo_2.png](https://raw.githubusercontent.com/Gourieff/Assets/main/sd-webui-reactor/xyz_demo_2.png)
|
||||||
|
|
||||||
|
### 0.7.0 <sub><sup>BETA1
|
||||||
|
|
||||||
|
- X/Y/Z Script support (up to 3 axes: CodeFormer Weight, Restorer Visibility, Face Mask Correction)
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-03.jpg?raw=true" alt="0.7.0-whatsnew-03" width="100%"/>
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-04.jpg?raw=true" alt="0.7.0-whatsnew-04" width="100%"/>
|
||||||
|
|
||||||
|
Full size demo image: [xyz_demo.png](https://raw.githubusercontent.com/Gourieff/Assets/main/sd-webui-reactor/xyz_demo.png)
|
||||||
|
|
||||||
|
__Don't forget to enable ReActor and set any source (to prevent "no source" error)__
|
||||||
|
|
||||||
|
### 0.7.0 <sub><sup>ALPHA1
|
||||||
|
|
||||||
|
- You can now blend faces to build blended face models ("Tools->Face Models->Blend") - due to popular demand
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-01.jpg?raw=true" alt="0.7.0-whatsnew-01" width="100%"/><img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-02.jpg?raw=true" alt="0.7.0-whatsnew-02" width="100%"/>
|
||||||
|
|
||||||
|
- CUDA 12 Support in the Installer script for 1.17.0 ORT-GPU library
|
||||||
|
- New tab "Detection" with "Threshold" and "Max Faces" parameters
|
||||||
|
|
||||||
|
### 0.6.1 <sub><sup>BETA3
|
||||||
|
|
||||||
|
- 'Force Upscale' option inside the 'Upscale' tab: ReActor will run the Upscaler even if there's no face is detected (FR https://github.com/Gourieff/sd-webui-reactor/issues/116)
|
||||||
|
- ReActor shows filenames of source images in-process when the multiple images mode or the folder mode (random as well) is selected
|
||||||
|
|
||||||
|
### 0.6.1 <sub><sup>BETA2
|
||||||
|
|
||||||
|
- 'Save original' option works fine now when you select 'Multiple Images' or 'Source Folder'
|
||||||
|
- Random Mode for 'Source Folder'
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/random_from_folder_demo_01.jpg?raw=true" alt="0.6.1-whatsnew-01" width="100%"/>
|
||||||
|
|
||||||
|
### 0.6.0
|
||||||
|
|
||||||
|
- New Logo
|
||||||
|
- Adaptation to A1111 1.7.0 (appropriate GFPGAN loader)
|
||||||
|
- New URL for the main model file
|
||||||
|
- UI reworked
|
||||||
|
- You can now load several source images (with reference faces) or set the path to the folder containing faces images
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_01.png?raw=true" alt="0.6.0-whatsnew-01" width="100%"/>
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_02.png?raw=true" alt="0.6.0-whatsnew-02" width="100%"/>
|
||||||
|
|
||||||
|
### 0.5.1
|
||||||
|
|
||||||
|
- You can save face models as "safetensors" files (stored in `<sd-web-ui-folder>\models\reactor\faces`) and load them into ReActor, keeping super lightweight face models of the faces you use;
|
||||||
|
- "Face Mask Correction" option - if you encounter some pixelation around face contours, this option will be useful;
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/face_model_demo_01.jpg?raw=true" alt="0.5.0-whatsnew-01" width="100%"/>
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
[Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
|
[A1111 WebUI / WebUI-Forge](#a1111) | [SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
|
||||||
|
|
||||||
<a name="a1111">If you use [AUTOMATIC1111 web-ui](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
|
<a name="a1111">If you use [AUTOMATIC1111 SD WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui/) or [SD WebUI Forge](https://github.com/lllyasviel/stable-diffusion-webui-forge):
|
||||||
|
|
||||||
1. (For Windows Users):
|
1. (For Windows Users):
|
||||||
- Install **Visual Studio 2022** (Community version, for example - you need this step to build some of dependencies):
|
- Install **Visual Studio 2022** (Community version, for example - you need this step to build some of dependencies):
|
||||||
@ -60,11 +127,11 @@
|
|||||||
- 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":
|
- OR only **VS C++ Build Tools** (if you don't need the whole Visual Studio) and select "Desktop Development with C++" under "Workloads -> Desktop & Mobile":
|
||||||
https://visualstudio.microsoft.com/visual-cpp-build-tools/
|
https://visualstudio.microsoft.com/visual-cpp-build-tools/
|
||||||
- OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. VIII)](#insightfacebuild)
|
- OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. VIII)](#insightfacebuild)
|
||||||
2. In web-ui, go to the "Extensions" tab and use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab and click "Install"
|
2. In web-ui, go to the "Extensions" tab, load "Available" extensions and type "ReActor" in the search field or use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab - and click "Install"
|
||||||
3. Please, wait for several minutes until the installation process will be finished
|
3. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
|
||||||
4. Check the last message in your SD-WebUI Console:
|
4. Check the last message in your SD-WebUI Console:
|
||||||
* If you see the message "--- PLEASE, RESTART the Server! ---" - so, do it, stop the Server (CTRL+C or CMD+C) and start it again - or just go to the "Installed" tab (*if you have any other Roop-based extension enabled - disable it, otherwise this extension won't work*), click "Apply and restart UI"
|
* If you see the message "--- PLEASE, RESTART the Server! ---" - so, do it, stop the Server (CTRL+C or CMD+C) and start it again - or just go to the "Installed" tab, click "Apply and restart UI"
|
||||||
* If you see the message "Done!", just go to the "Installed" tab (*if you have any other Roop-based extension enabled - disable it, otherwise this extension won't work*), click "Apply and restart UI" - or you can just simply reload the UI
|
* If you see the message "Done!", just reload the UI
|
||||||
5. Enjoy!
|
5. Enjoy!
|
||||||
|
|
||||||
<a name="sdnext">If you use [SD.Next](https://github.com/vladmandic/automatic):
|
<a name="sdnext">If you use [SD.Next](https://github.com/vladmandic/automatic):
|
||||||
@ -74,17 +141,17 @@
|
|||||||
3. Go to (Windows)`automatic\venv\Scripts` or (MacOS/Linux)`automatic/venv/bin`, run Terminal or Console (cmd) for that folder and type `activate`
|
3. Go to (Windows)`automatic\venv\Scripts` or (MacOS/Linux)`automatic/venv/bin`, run Terminal or Console (cmd) for that folder and type `activate`
|
||||||
4. Run `pip install insightface==0.7.3`
|
4. Run `pip install insightface==0.7.3`
|
||||||
5. Run SD.Next, go to the "Extensions" tab and use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab and click "Install"
|
5. Run SD.Next, go to the "Extensions" tab and use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab and click "Install"
|
||||||
6. Please, wait for several minutes until the installation process will be finished
|
6. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
|
||||||
7. Check the last message in your SD.Next Console:
|
7. Check the last message in your SD.Next Console:
|
||||||
* If you see the message "--- PLEASE, RESTART the Server! ---" - so, do it, stop the Server (CTRL+C or CMD+C) and start it again - or just go to the "Installed" tab (*if you have any other Roop-based extension enabled - disable it, otherwise this extension won't work*), click "Restart the UI"
|
* If you see the message "--- PLEASE, RESTART the Server! ---" - stop the Server (CTRL+C or CMD+C) or just close your console
|
||||||
8. Stop SD.Next, go to the `automatic\extensions\sd-webui-reactor` directory - if you see there `models\insightface` folder with the file `inswapper_128.onnx`, just move the file to the `automatic\models\insightface` folder
|
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
|
||||||
9. Run your SD.Next WebUI and enjoy!
|
9. Run your SD.Next WebUI and enjoy!
|
||||||
|
|
||||||
<a name="colab">If you use [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
|
<a name="colab">If you use [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
|
||||||
|
|
||||||
1. In active WebUI, go to the "Extensions" tab and use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab and click "Install"
|
1. In active WebUI, go to the "Extensions" tab, load "Available" extensions and type "ReActor" in the search field or use this URL `https://github.com/Gourieff/sd-webui-reactor` in the "Install from URL" tab - and click "Install"
|
||||||
2. Please, wait for several minutes until the installation process will be finished
|
2. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
|
||||||
3. When you see the message "--- PLEASE, RESTART the Server! ---" (in your Colab Notebook Start UI section "Start Cagliostro Colab UI") - just go to the "Installed" tab and click "Apply and restart UI" (*if you have any other Roop-based extension enabled - disable it before restart, otherwise this extension won't work*)
|
3. When you see the message "--- PLEASE, RESTART the Server! ---" (in your Colab Notebook Start UI section "Start Cagliostro Colab UI") - just go to the "Installed" tab and click "Apply and restart UI"
|
||||||
4. Enjoy!
|
4. Enjoy!
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
@ -95,9 +162,12 @@
|
|||||||
- Ability to **save original images** (made before swapping)
|
- Ability to **save original images** (made before swapping)
|
||||||
- **Face restoration** of a swapped face
|
- **Face restoration** of a swapped face
|
||||||
- **Upscaling** of a resulting image
|
- **Upscaling** of a resulting image
|
||||||
|
- Saving ans loading **Safetensors Face Models**
|
||||||
|
- **Facial Mask Correction** to avoid any pixelation around face contours
|
||||||
- Ability to set the **Postprocessing order**
|
- Ability to set the **Postprocessing order**
|
||||||
- **100% compatibility** with different **SD WebUIs**: Automatic1111, SD.Next, Cagliostro Colab UI
|
- **100% compatibility** with different **SD WebUIs**: Automatic1111, SD.Next, Cagliostro Colab UI
|
||||||
- **Fast performance** even with CPU, ReActor for SD WebUI is absolutely not picky about how powerful your GPU is
|
- **Fast performance** even with CPU, ReActor for SD WebUI is absolutely not picky about how powerful your GPU is
|
||||||
|
- **CUDA** acceleration support since version 0.5.0
|
||||||
- **[API](/API.md) support**: both SD WebUI built-in and external (via POST/GET requests)
|
- **[API](/API.md) support**: both SD WebUI built-in and external (via POST/GET requests)
|
||||||
- **ComfyUI [support](https://github.com/Gourieff/comfyui-reactor-node)**
|
- **ComfyUI [support](https://github.com/Gourieff/comfyui-reactor-node)**
|
||||||
- **Mac M1/M2 [support](https://github.com/Gourieff/sd-webui-reactor/issues/42)**
|
- **Mac M1/M2 [support](https://github.com/Gourieff/sd-webui-reactor/issues/42)**
|
||||||
@ -112,24 +182,41 @@
|
|||||||
2. Turn on the "Enable" checkbox;
|
2. Turn on the "Enable" checkbox;
|
||||||
3. That's it, now the generated result will have the face you selected.
|
3. That's it, now the generated result will have the face you selected.
|
||||||
|
|
||||||
<img src="example/example.jpg" alt="example" width="808"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
|
||||||
|
|
||||||
|
### Face Indexes
|
||||||
|
|
||||||
|
ReActor detects faces in images in the following order:<br>
|
||||||
|
left->right, top->bottom
|
||||||
|
|
||||||
|
And if you need to specify faces, you can set indexes for source and input images.
|
||||||
|
|
||||||
|
Index of the first detected face is 0.
|
||||||
|
|
||||||
|
You can set indexes in the order you need.<br>
|
||||||
|
E.g.: 0,1,2 (for Source); 1,0,2 (for Input).<br>
|
||||||
|
This means: the second Input face (index = 1) will be swapped by the first Source face (index = 0) and so on.
|
||||||
|
|
||||||
|
### Genders
|
||||||
|
|
||||||
|
You can specify the gender to detect in images.<br>
|
||||||
|
ReActor will swap a face only if it meets the given condition.
|
||||||
|
|
||||||
### The result face is blurry
|
### The result face is blurry
|
||||||
Use the "Restore Face" option. You can also try the "Upscaler" option or for more finer control, use an upscaler from the "Extras" tab.
|
Use the "Restore Face" option. You can also try the "Upscaler" option or for more finer control, use an upscaler from the "Extras" tab.
|
||||||
You can also set the postproduction order (from 0.1.0 version):
|
You can also set the postproduction order (from 0.1.0 version):
|
||||||
<img src="example/pp-order.png" alt="example"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
|
||||||
|
|
||||||
*The old logic was the opposite (Upscale -> then Restore), resulting in worse face quality (and big texture differences) after upscaling.*
|
*The old logic was the opposite (Upscale -> then Restore), resulting in worse face quality (and big texture differences) after upscaling.*
|
||||||
|
|
||||||
### There are multiple faces in result
|
### There are multiple faces in result
|
||||||
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.
|
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.
|
||||||
<img src="example/multiple-faces.png" alt="example"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
|
||||||
|
|
||||||
### ~~The result is totally black~~
|
### ~~The result is totally black~~
|
||||||
~~This means NSFW filter detected that your image is NSFW.~~
|
~~This means NSFW filter detected that your image is NSFW.~~
|
||||||
|
|
||||||
<img src="example/IamSFW.jpg" alt="IamSFW" width="50%"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
|
||||||
|
|
||||||
### Img2Img
|
### Img2Img
|
||||||
|
|
||||||
@ -137,6 +224,12 @@ You can choose to activate the swap on the source image or on the generated imag
|
|||||||
|
|
||||||
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".
|
ReActor works with Inpainting - but only the masked part will be swapped.<br>Please use with the "Only masked" option for "Inpaint area" if you enabled "Upscaler". Otherwise use the upscale option via the Extras tab or via the Script loader (below the screen) with "SD upscale" or "Ultimate SD upscale".
|
||||||
|
|
||||||
|
### Extras Tab
|
||||||
|
|
||||||
|
From the version 0.5.0 you can use ReActor via the Extras Tab. It gives a superfast perfomance and ability to swap face2image avoiding SD pipeline that can cause smushing of original image's details
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
You can use ReActor with the built-in Webui API or via an external API.
|
You can use ReActor with the built-in Webui API or via an external API.
|
||||||
@ -165,9 +258,9 @@ Please, check the path where "inswapper_128.onnx" model is stored. It must be in
|
|||||||
6. Update your pip at first: `pip install -U pip`
|
6. Update your pip at first: `pip install -U pip`
|
||||||
7. Then one-by-one:
|
7. Then one-by-one:
|
||||||
- `pip install insightface==0.7.3`
|
- `pip install insightface==0.7.3`
|
||||||
- `pip install onnx==1.14.0`
|
- `pip install onnx`
|
||||||
- `pip install onnxruntime==1.15.0`
|
- `pip install "onnxruntime-gpu>=1.16.1"`
|
||||||
- `pip install opencv-python==4.7.0.72`
|
- `pip install opencv-python`
|
||||||
- `pip install tqdm`
|
- `pip install tqdm`
|
||||||
8. Type `deactivate`, you can close your Terminal or Console and start your SD WebUI, ReActor should start OK - if not, welcome to the Issues section.
|
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.
|
||||||
|
|
||||||
@ -175,7 +268,7 @@ Please, check the path where "inswapper_128.onnx" model is stored. It must be in
|
|||||||
|
|
||||||
First of all - you need to disable any other Roop-based extensions:
|
First of all - you need to disable any other Roop-based extensions:
|
||||||
- Go to 'Extensions -> Installed' tab and uncheck any Roop-based extensions except this one
|
- Go to 'Extensions -> Installed' tab and uncheck any Roop-based extensions except this one
|
||||||
<img src="example/roop-off.png" alt="uncompatible-with-other-roop"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>
|
||||||
- Click 'Apply and restart UI'
|
- Click 'Apply and restart UI'
|
||||||
|
|
||||||
Alternative solutions:
|
Alternative solutions:
|
||||||
@ -184,26 +277,26 @@ Alternative solutions:
|
|||||||
|
|
||||||
### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
|
### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
|
||||||
|
|
||||||
You need to disable the "SD-CN-Animation" extension (or perhaps some another that causes the conflict)
|
Probably, you need to disable the "SD-CN-Animation" extension (or perhaps some another that causes the conflict)
|
||||||
|
|
||||||
### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed"**
|
### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed" OR "AttributeError: 'NoneType' object has no attribute 'get'" OR "AttributeError: 'FaceSwapScript' object has no attribute 'save_original'"**
|
||||||
|
|
||||||
This error may occur if there's smth wrong with the model file `inswapper_128.onnx`
|
This error may occur if there's smth wrong with the model file `inswapper_128.onnx`
|
||||||
|
|
||||||
Try to download it manually from [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)
|
Try to download it manually from [here](https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx)
|
||||||
and put it to the `stable-diffusion-webui\models\insightface` replacing existing one
|
and put it to the `stable-diffusion-webui\models\insightface` replacing existing one
|
||||||
|
|
||||||
### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled"**
|
### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" OR "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
|
||||||
|
|
||||||
1. Close (stop) your SD WebUI Server if it's running
|
1. Close (stop) your SD WebUI Server if it's running
|
||||||
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
|
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
|
||||||
3. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
|
3. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
|
||||||
4. Then:
|
4. Then:
|
||||||
- `python -m pip install -U pip`
|
- `python -m pip install -U pip`
|
||||||
- `pip uninstall -y onnx onnxruntime onnxruntime-gpu onnxruntime-silicon`
|
- `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`
|
||||||
- `pip install onnx==1.14.0 onnxruntime==1.15.0`
|
- `pip install "onnxruntime-gpu>=1.16.1"`
|
||||||
|
|
||||||
If it didn't help - it seems that you have another extension reinstalling `onnxruntime` when SD WebUI checks requirements. Please see your extensions list. If you find there "WD14 tagger" - try to disable it and then follow the steps above once again. This extension causes reinstalling of `onnxruntime` to `onnxruntime-gpu` every time SD WebUI runs.
|
If it didn't help - it seems that you have another extension reinstalling `onnxruntime` when SD WebUI checks requirements. Please see your extensions list. Some extensions can causes reinstalling of `onnxruntime-gpu` to `onnxruntime<1.16.1` every time SD WebUI runs.<br>ORT 1.16.0 has a bug https://github.com/microsoft/onnxruntime/issues/17631 - don't install it!
|
||||||
|
|
||||||
### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
|
### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
|
||||||
|
|
||||||
@ -214,19 +307,19 @@ If it didn't help - it seems that you have another extension reinstalling `onnxr
|
|||||||
5. Then:
|
5. Then:
|
||||||
- `python -m pip install -U pip`
|
- `python -m pip install -U pip`
|
||||||
- `pip uninstall protobuf`
|
- `pip uninstall protobuf`
|
||||||
- `pip install protobuf==3.20.3`
|
- `pip install "protobuf>=3.20.3"`
|
||||||
|
|
||||||
If this method doesn't help - there is some other extension that has a higher version of protobuf dependence and SD WebUI installs it on a startup requirements check
|
If this method doesn't help - there is some other extension that has a wrong version of protobuf dependence and SD WebUI installs it on a startup requirements check
|
||||||
|
|
||||||
<a name="insightfacebuild">
|
<a name="insightfacebuild">
|
||||||
|
|
||||||
### **VIII. (For Windows users) If you still cannot build Insightface for some reasons or just don't want to install Visual Studio or VS C++ Build Tools - do the following:**
|
### **VIII. (For Windows users) If you still cannot build Insightface for some reasons or just don't want to install Visual Studio or VS C++ Build Tools - do the following:**
|
||||||
|
|
||||||
1. Close (stop) your SD WebUI Server if it's running
|
1. Close (stop) your SD WebUI Server if it's running
|
||||||
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)
|
2. Download and put [prebuilt Insightface package](https://github.com/Gourieff/Assets/raw/main/Insightface/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"
|
||||||
3. From stable-diffusion-webui (or SD.Next) root folder run CMD and `.\venv\Scripts\activate`
|
3. From stable-diffusion-webui (or SD.Next) root folder run CMD and `.\venv\Scripts\activate`<br>OR<br>(A1111 Portable) Run CMD
|
||||||
4. Then update your PIP: `python -m pip install -U pip`
|
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`
|
||||||
5. Then install Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`
|
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`
|
||||||
6. Enjoy!
|
6. Enjoy!
|
||||||
|
|
||||||
### **IX. 07-August-23 Update problem**
|
### **IX. 07-August-23 Update problem**
|
||||||
@ -243,6 +336,9 @@ OR
|
|||||||
|
|
||||||
Just delete the folder `sd-webui-reactor` inside the `extensions` directory and then run Terminal or Console (cmd) and type `git clone https://github.com/Gourieff/sd-webui-reactor`
|
Just delete the folder `sd-webui-reactor` inside the `extensions` directory and then run Terminal or Console (cmd) and type `git clone https://github.com/Gourieff/sd-webui-reactor`
|
||||||
|
|
||||||
|
### **X. StabilityMatrix Issues**
|
||||||
|
|
||||||
|
If you encounter any issues with installing this extension in the StabilityMatrix package manager - read here how to solve: https://github.com/Gourieff/sd-webui-reactor/issues/129#issuecomment-1768210875
|
||||||
|
|
||||||
## Updating
|
## Updating
|
||||||
|
|
||||||
@ -257,7 +353,7 @@ For the installation instruction follow the [ReActor Node repo](https://github.c
|
|||||||
|
|
||||||
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.
|
This software is meant to be a productive contribution to the rapidly growing AI-generated media industry. It will help artists with tasks such as animating a custom character or using the character as a model for clothing etc.
|
||||||
|
|
||||||
The developers of this software are aware of its possible unethical applicaitons and are committed to take preventative measures against them. We will continue to develop this project in the positive direction while adhering to law and ethics.
|
The developers of this software are aware of its possible unethical application and are committed to take preventative measures against them. We will continue to develop this project in the positive direction while adhering to law and ethics.
|
||||||
|
|
||||||
Users of this software are expected to use this software responsibly while abiding the local law. If face of a real person is being used, users are suggested to get consent from the concerned person and clearly mention that it is a deepfake when posting content online. **Developers and Contributors of this software are not responsible for actions of end-users.**
|
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.**
|
||||||
|
|
||||||
@ -267,3 +363,58 @@ By using this extension you are agree not to create any content that:
|
|||||||
- propogates (spreads) any information (both public or personal) or images (both public or personal) which could be meant for harm;
|
- propogates (spreads) any information (both public or personal) or images (both public or personal) which could be meant for harm;
|
||||||
- spreads misinformation;
|
- spreads misinformation;
|
||||||
- targets vulnerable groups of people.
|
- targets vulnerable groups of people.
|
||||||
|
|
||||||
|
This software utilizes the pre-trained models `buffalo_l` and `inswapper_128.onnx`, which are provided by [InsightFace](https://github.com/deepinsight/insightface/). These models are included under the following conditions:
|
||||||
|
|
||||||
|
[From insighface licence](https://github.com/deepinsight/insightface/tree/master/python-package): The InsightFace’s pre-trained models are available for non-commercial research purposes only. This includes both auto-downloading models and manually downloaded models.
|
||||||
|
|
||||||
|
Users of this software must strictly adhere to these conditions of use. The developers and maintainers of this software are not responsible for any misuse of InsightFace’s pre-trained models.
|
||||||
|
|
||||||
|
Please note that if you intend to use this software for any commercial purposes, you will need to train your own models or find models that can be used commercially.
|
||||||
|
|
||||||
|
### Models Hashsum
|
||||||
|
|
||||||
|
#### Safe-to-use models have the folowing hash:
|
||||||
|
|
||||||
|
inswapper_128.onnx
|
||||||
|
```
|
||||||
|
MD5:a3a155b90354160350efd66fed6b3d80
|
||||||
|
SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
|
||||||
|
```
|
||||||
|
|
||||||
|
1k3d68.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:6fb94fcdb0055e3638bf9158e6a108f4
|
||||||
|
SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
|
||||||
|
```
|
||||||
|
|
||||||
|
2d106det.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:a3613ef9eb3662b4ef88eb90db1fcf26
|
||||||
|
SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
|
||||||
|
```
|
||||||
|
|
||||||
|
det_10g.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:4c10eef5c9e168357a16fdd580fa8371
|
||||||
|
SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
|
||||||
|
```
|
||||||
|
|
||||||
|
genderage.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:81c77ba87ab38163b0dec6b26f8e2af2
|
||||||
|
SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
|
||||||
|
```
|
||||||
|
|
||||||
|
w600k_r50.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:80248d427976241cbd1343889ed132b3
|
||||||
|
SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
|
||||||
|
```
|
||||||
|
|
||||||
|
**Please check hashsums if you download these models from unverified (or untrusted) sources**
|
||||||
|
|||||||
260
README_RU.md
260
README_RU.md
@ -1,8 +1,19 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
<img src="example/ReActor_logo_red.png" alt="logo" width="180px"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_RU.png?raw=true" alt="logo" width="180px"/>
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
<a href="https://boosty.to/artgourieff" target="_blank">
|
||||||
|
<img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Поддержать проект на Boosty"/>
|
||||||
|
<br>
|
||||||
|
<sup>
|
||||||
|
Поддержать проект
|
||||||
|
</sup>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<hr>
|
||||||
|
|
||||||
<hr>
|
|
||||||
[](https://github.com/Gourieff/sd-webui-reactor/commits/main)
|
[](https://github.com/Gourieff/sd-webui-reactor/commits/main)
|
||||||

|

|
||||||
[](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
|
[](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
|
||||||
@ -14,43 +25,98 @@
|
|||||||
# ReActor для Stable Diffusion
|
# ReActor для Stable Diffusion
|
||||||
### Расширение для быстрой и простой замены лиц на любых изображениях. Без фильтра цензуры, 18+, используйте под вашу собственную [ответственность](#disclaimer)
|
### Расширение для быстрой и простой замены лиц на любых изображениях. Без фильтра цензуры, 18+, используйте под вашу собственную [ответственность](#disclaimer)
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
---
|
---
|
||||||
<div align="center">
|
|
||||||
<b>
|
<b>
|
||||||
<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>
|
<a href="#latestupdate">Что нового</a> | <a href="#installation">Установка</a> | <a href="#features">Возможности</a> | <a href="#usage">Использование</a> | <a href="#api">API</a> | <a href="#troubleshooting">Устранение проблем</a> | <a href="#updating">Обновление</a> | <a href="#comfyui">ComfyUI</a> | <a href="#disclaimer">Ответственность</a>
|
||||||
</b>
|
</b>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
<table>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
|
||||||
<tr>
|
|
||||||
<td width="144px">
|
|
||||||
<a href="https://boosty.to/artgourieff" target="_blank">
|
|
||||||
<img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/>
|
|
||||||
<br>
|
|
||||||
<sup>
|
|
||||||
Поддержать проект
|
|
||||||
</sup>
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
ReActor это расширение для Stable Diffusion WebUI, которое позволяет делать простую и точную замену лиц на изображениях. Сделано на основе <a href="https://github.com/Gourieff/ReActor-UI" target="_blank">ReActor-UI</a>.
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<img src="example/demo_crop.jpg" alt="example"/>
|
<a name="latestupdate">
|
||||||
|
|
||||||
|
## Что нового в последних обновлениях
|
||||||
|
|
||||||
|
### 0.7.1 <sub><sup>BETA1
|
||||||
|
|
||||||
|
- Использование пробелов в индексах лиц (пример: 0, 1, 2)
|
||||||
|
- Список моделей лиц теперь отсортирован по алфавиту
|
||||||
|
- [API для создания моделей лиц](./API.md#facemodel-build-api)
|
||||||
|
- Правки и улучшения
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><a>Нажмите, чтобы посмотреть больше</a></summary>
|
||||||
|
|
||||||
|
### 0.7.0 <sub><sup>BETA2
|
||||||
|
|
||||||
|
- X/Y/Z опция улучшена! Добавлен ещё один параметр: теперь вы можете выбрать несколько моделей лиц для создания вариации замененных лиц, чтобы выбрать наилучшие!
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-05.jpg?raw=true" alt="0.7.0-whatsnew-05" width="100%"/>
|
||||||
|
|
||||||
|
Чтобы использовать ось "Face Model" - активируйте РеАктор и выбирите любую модель лица в качестве источника:<br>
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-07.jpg?raw=true" alt="0.7.0-whatsnew-07" width="50%"/><img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-06.jpg?raw=true" alt="0.7.0-whatsnew-06" width="50%"/>
|
||||||
|
|
||||||
|
Полноразмерное демо-изображение: [xyz_demo_2.png](https://raw.githubusercontent.com/Gourieff/Assets/main/sd-webui-reactor/xyz_demo_2.png)
|
||||||
|
|
||||||
|
### 0.7.0 <sub><sup>BETA1
|
||||||
|
|
||||||
|
- Поддержка X/Y/Z скрипта (до 3-х параметров: CodeFormer Weight, Restorer Visibility, Face Mask Correction)
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-03.jpg?raw=true" alt="0.7.0-whatsnew-03" width="100%"/>
|
||||||
|
|
||||||
|
Полноразмерное демо-изображение: [xyz_demo.png](https://raw.githubusercontent.com/Gourieff/Assets/main/sd-webui-reactor/xyz_demo.png)
|
||||||
|
|
||||||
|
### 0.7.0 <sub><sup>ALPHA1
|
||||||
|
|
||||||
|
- По многочисленным просьбам появилась возможность строить смешанные модели лиц ("Tools->Face Models->Blend")
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-01.jpg?raw=true" alt="0.7.0-whatsnew-01" width="100%"/><img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/0.7.0-whatsnew-02.jpg?raw=true" alt="0.7.0-whatsnew-02" width="100%"/>
|
||||||
|
|
||||||
|
- Поддержка CUDA 12 в скрипте установщика для библиотеки ORT-GPU версии 1.17.0
|
||||||
|
- Новая вкладка "Detection" с параметрами "Threshold" и "Max Faces"
|
||||||
|
|
||||||
|
### 0.6.1 <sub><sup>BETA3
|
||||||
|
|
||||||
|
- Опция 'Force Upscale' внутри вкладки 'Upscale': апскейл выполнится, даже если не было обнаружено ни одного лица (FR https://github.com/Gourieff/sd-webui-reactor/issues/116)
|
||||||
|
- Отображение имён файлов используемых изображений, когда выбрано несколько изображений или папка (а также режим случайного изображения)
|
||||||
|
|
||||||
|
### 0.6.1 <sub><sup>BETA2
|
||||||
|
|
||||||
|
- Опция 'Save original' теперь работает правильно, когда вы выбираете 'Multiple Images' или 'Source Folder'
|
||||||
|
- Добавлен режим выбора случайного изображения для 'Source Folder'
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/random_from_folder_demo_01.jpg?raw=true" alt="0.6.1-whatsnew-01" width="100%"/>
|
||||||
|
|
||||||
|
### 0.6.0
|
||||||
|
|
||||||
|
- Новый логотип
|
||||||
|
- Адаптация к версии A1111 1.7.0 (правильная загрузка GFPGAN)
|
||||||
|
- Новая ссылка для файла основной модели
|
||||||
|
- UI переработан
|
||||||
|
- Появилась возможность загружать несколько исходных изображений с лицами или задавать путь к папке, содержащей такие изображения
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_01.png?raw=true" alt="0.6.0-whatsnew-01" width="100%"/>
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/multiple_source_images_demo_02.png?raw=true" alt="0.6.0-whatsnew-02" width="100%"/>
|
||||||
|
|
||||||
|
### 0.5.1
|
||||||
|
|
||||||
|
- Теперь можно сохранять модели лиц в качестве файлов "safetensors" (находятся в `<sd-web-ui-folder>\models\reactor\faces`) и загружать их с ReActor, храня супер легкие модели лиц, которые вы чаще всего используете;
|
||||||
|
- Новые опция "Face Mask Correction" - если вы сталкиваетесь с пикселизацией вокруг контуров лица, эта опция будет полезной;
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/blob/main/sd-webui-reactor/face_model_demo_01.jpg?raw=true" alt="0.5.0-whatsnew-01" width="100%"/>
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
<a name="installation">
|
<a name="installation">
|
||||||
|
|
||||||
## Установка
|
## Установка
|
||||||
|
|
||||||
[Automatic1111](#a1111) | [Vladmandic SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
|
[A1111 WebUI / WebUI-Forge](#a1111) | [SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
|
||||||
|
|
||||||
<a name="a1111">Если вы используете [AUTOMATIC1111 Web-UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui/):
|
<a name="a1111">Если вы используете [AUTOMATIC1111 SD WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui/) или [SD WebUI Forge](https://github.com/lllyasviel/stable-diffusion-webui-forge):
|
||||||
|
|
||||||
1. (Для пользователей Windows):
|
1. (Для пользователей Windows):
|
||||||
- Установите **Visual Studio 2022** (Например, версию Community - этот шаг нужен для правильной компиляции библиотеки Insightface):
|
- Установите **Visual Studio 2022** (Например, версию Community - этот шаг нужен для правильной компиляции библиотеки Insightface):
|
||||||
@ -58,11 +124,11 @@
|
|||||||
- ИЛИ только **VS C++ Build Tools** (если вам не нужен весь пакет Visual Studio), выберите "Desktop Development with C++" в разделе "Workloads -> Desktop & Mobile":
|
- ИЛИ только **VS C++ Build Tools** (если вам не нужен весь пакет Visual Studio), выберите "Desktop Development with C++" в разделе "Workloads -> Desktop & Mobile":
|
||||||
https://visualstudio.microsoft.com/visual-cpp-build-tools/
|
https://visualstudio.microsoft.com/visual-cpp-build-tools/
|
||||||
- ИЛИ если же вы не хотите устанавливать что-либо из вышеуказанного - выполните [следующие шаги (пункт VIII)](#insightfacebuild)
|
- ИЛИ если же вы не хотите устанавливать что-либо из вышеуказанного - выполните [следующие шаги (пункт VIII)](#insightfacebuild)
|
||||||
2. Внутри SD Web-UI перейдите во вкладку "Extensions" и вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
|
2. Внутри SD Web-UI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"
|
||||||
3. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится
|
3. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
|
||||||
4. Проверьте последнее сообщение в консоли SD-WebUI:
|
4. Проверьте последнее сообщение в консоли SD-WebUI:
|
||||||
* Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) и запустите его заново - ИЛИ же перейдите во вкладку "Installed" (*если у вас имееются какие-либо другие расширение, основанные на Roop или клонах ReActor - отключите их, иначе данное расширение может не работать*), нажмите "Apply and restart UI"
|
* Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) и запустите его заново - ИЛИ же перейдите во вкладку "Installed", нажмите "Apply and restart UI"
|
||||||
* Если вы видите "Done!", перейдите во вкладку "Installed" (*если у вас имееются какие-либо другие расширение, основанные на Roop или клонах ReActor - отключите их, иначе данное расширение может не работать*), нажмите "Apply and restart UI" - или же просто перезагрузите UI, нажав на "Reload UI"
|
* Если вы видите "Done!", просто перезагрузите UI, нажав на "Reload UI"
|
||||||
5. Готово!
|
5. Готово!
|
||||||
|
|
||||||
<a name="sdnext">Если вы используете [SD.Next](https://github.com/vladmandic/automatic):
|
<a name="sdnext">Если вы используете [SD.Next](https://github.com/vladmandic/automatic):
|
||||||
@ -72,17 +138,17 @@
|
|||||||
3. Перейдите в (Windows)`automatic\venv\Scripts` или (MacOS/Linux)`automatic/venv/bin`, запустите Терминал или Консоль (cmd) для данной папки и выполните `activate`
|
3. Перейдите в (Windows)`automatic\venv\Scripts` или (MacOS/Linux)`automatic/venv/bin`, запустите Терминал или Консоль (cmd) для данной папки и выполните `activate`
|
||||||
4. Выполните `pip install insightface==0.7.3`
|
4. Выполните `pip install insightface==0.7.3`
|
||||||
5. Запустите SD.Next, перейдите во вкладку "Extensions", вставьте эту ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
|
5. Запустите SD.Next, перейдите во вкладку "Extensions", вставьте эту ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
|
||||||
6. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится
|
6. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
|
||||||
7. Проверьте последнее сообщение в консоли SD.Next:
|
7. Проверьте последнее сообщение в консоли SD.Next:
|
||||||
* Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) и запустите его заново - ИЛИ же перейдите во вкладку "Installed" (*если у вас имееются какие-либо другие расширение, основанные на Roop или клонах ReActor - отключите их, иначе данное расширение может не работать*), нажмите "Restart the UI"
|
* Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) или просто закройте консоль
|
||||||
8. Остановите Сервер SD.Next, перейдите в директорию `automatic\extensions\sd-webui-reactor` - если вы видите там папку `models\insightface` с файлом `inswapper_128.onnx` внутри, переместите его в папку `automatic\models\insightface`
|
8. Перейдите в директорию `automatic\extensions\sd-webui-reactor` - если вы видите там папку `models\insightface` с файлом `inswapper_128.onnx` внутри, переместите его в папку `automatic\models\insightface`
|
||||||
9. Готово, можете запустить SD.Next WebUI!
|
9. Готово, можете запустить SD.Next WebUI!
|
||||||
|
|
||||||
<a name="colab">Если вы используете [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
|
<a name="colab">Если вы используете [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
|
||||||
|
|
||||||
1. В активном WebUI, перейдите во вкладку "Extensions", вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
|
1. В активном WebUI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"
|
||||||
2. Пожалуйста, подождите некоторое время, пока процесс установки полностью не завершится
|
2. Пожалуйста, подождите некоторое время, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
|
||||||
3. Когда вы увидите сообщение "--- PLEASE, RESTART the Server! ---" (в секции "Start UI" вашего ноутбука "Start Cagliostro Colab UI") - перейдите во вкладку "Installed" и нажмите "Apply and restart UI" (*если у вас имееются какие-либо другие расширение, основанные на Roop или клонах ReActor - отключите их, иначе данное расширение может не работать*)
|
3. Когда вы увидите сообщение "--- PLEASE, RESTART the Server! ---" (в секции "Start UI" вашего ноутбука "Start Cagliostro Colab UI") - перейдите во вкладку "Installed" и нажмите "Apply and restart UI"
|
||||||
4. Готово!
|
4. Готово!
|
||||||
|
|
||||||
<a name="features">
|
<a name="features">
|
||||||
@ -95,9 +161,12 @@
|
|||||||
- Функция **сохранения оригинального изображения** (сгенерированного до замены лица)
|
- Функция **сохранения оригинального изображения** (сгенерированного до замены лица)
|
||||||
- **Восстановление лица** после замены
|
- **Восстановление лица** после замены
|
||||||
- **Увеличение размера** полученного изображения
|
- **Увеличение размера** полученного изображения
|
||||||
|
- Сохранение и загрузка **Моделей Лиц типа Safetensors**
|
||||||
|
- **Коррекция Маски Лица** для предотвращения какой-либо пикселизации вокруг контуров лиц
|
||||||
- Возможность задать **порядок постобработки**
|
- Возможность задать **порядок постобработки**
|
||||||
- **100% совместимость** с разными **SD WebUI**: Automatic1111, SD.Next, Cagliostro Colab UI
|
- **100% совместимость** с разными **SD WebUI**: Automatic1111, SD.Next, Cagliostro Colab UI
|
||||||
- **Отличная производительность** даже с использованием ЦПУ, ReActor для SD WebUI абсолютно не требователен к мощности вашей видеокарты
|
- **Отличная производительность** даже с использованием ЦПУ, ReActor для SD WebUI абсолютно не требователен к мощности вашей видеокарты
|
||||||
|
- **Поддержка CUDA**, начиная с версии 0.5.0
|
||||||
- **Поддержка [API](/API.md)**: как встроенного в SD WebUI, так и внешнего (через POST/GET запросы)
|
- **Поддержка [API](/API.md)**: как встроенного в SD WebUI, так и внешнего (через POST/GET запросы)
|
||||||
- **[Поддержка](https://github.com/Gourieff/comfyui-reactor-node) ComfyUI**
|
- **[Поддержка](https://github.com/Gourieff/comfyui-reactor-node) ComfyUI**
|
||||||
- **[Поддержка](https://github.com/Gourieff/sd-webui-reactor/issues/42) компьютеров Mac M1/M2**
|
- **[Поддержка](https://github.com/Gourieff/sd-webui-reactor/issues/42) компьютеров Mac M1/M2**
|
||||||
@ -114,24 +183,41 @@
|
|||||||
2. Установите флажок "Enable";
|
2. Установите флажок "Enable";
|
||||||
3. Готово, теперь результат будет иметь то лицо, которое вы выбрали.
|
3. Готово, теперь результат будет иметь то лицо, которое вы выбрали.
|
||||||
|
|
||||||
<img src="example/example.jpg" alt="example" width="808"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
|
||||||
|
|
||||||
|
### Индексы Лиц (Face Indexes)
|
||||||
|
|
||||||
|
ReActor определяет лица на изображении в следующей последовательности:<br>
|
||||||
|
слева-направо, сверху-вниз.
|
||||||
|
|
||||||
|
Если вам нужно заменить определенное лицо, вы можете указать индекс для исходного (source, с лицом) и входного (input, где будет замена лица) изображений.
|
||||||
|
|
||||||
|
Индекс первого обнаруженного лица - 0.
|
||||||
|
|
||||||
|
Вы можете задать индексы в том порядке, который вам нужен.<br>
|
||||||
|
Например: 0,1,2 (для Source); 1,0,2 (для Input).<br>
|
||||||
|
Это означает, что: второе лицо из Input (индекс = 1) будет заменено первым лицом из Source (индекс = 0) и так далее.
|
||||||
|
|
||||||
|
### Определение Пола
|
||||||
|
|
||||||
|
Вы можете обозначить, какой пол нужно определять на изображении.<br>
|
||||||
|
ReActor заменит только то лицо, которое удовлетворяет заданному условию.
|
||||||
|
|
||||||
### Если лицо получилось нечётким
|
### Если лицо получилось нечётким
|
||||||
Используйте опцию "Restore Face". Также можете попробовать опцию "Upscaler". Для более точного контроля параметров используйте Upscaler во вкладке "Extras".
|
Используйте опцию "Restore Face". Также можете попробовать опцию "Upscaler". Для более точного контроля параметров используйте Upscaler во вкладке "Extras".
|
||||||
Также вы можете установить порядок постобработки (начиная с версии 0.1.0):
|
Также вы можете установить порядок постобработки (начиная с версии 0.1.0):
|
||||||
<img src="example/pp-order.png" alt="example"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
|
||||||
|
|
||||||
*Прежняя логика была противоположенной (Upscale -> затем Restore), что приводило к более худшему качеству изображения лица (а также к значительной разнице текстур) после увеличения.*
|
*Прежняя логика была противоположенной (Upscale -> затем Restore), что приводило к более худшему качеству изображения лица (а также к значительной разнице текстур) после увеличения.*
|
||||||
|
|
||||||
### Результат имеет несколько лиц
|
### Результат имеет несколько лиц
|
||||||
Выберите номера лиц, которые нужно поменять, используя поля "Comma separated face number(s)" для исходного изображения лица и для результата. Можно устанавливать любой, необходимый вам, порядок лиц.
|
Выберите номера лиц, которые нужно поменять, используя поля "Comma separated face number(s)" для исходного изображения лица и для результата. Можно устанавливать любой, необходимый вам, порядок лиц.
|
||||||
<img src="example/multiple-faces.png" alt="example"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
|
||||||
|
|
||||||
### ~~Результат получился чёрным~~
|
### ~~Результат получился чёрным~~
|
||||||
~~Это значит, что сработал NSFW фильтр.~~
|
~~Это значит, что сработал NSFW фильтр.~~
|
||||||
|
|
||||||
<img src="example/IamSFW.jpg" alt="IamSFW" width="50%"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
|
||||||
|
|
||||||
### Img2Img
|
### Img2Img
|
||||||
|
|
||||||
@ -139,6 +225,12 @@
|
|||||||
|
|
||||||
Inpainting также работает, но замена лица происходит только в области маски.<br>Пожалуйста, используйте с опцией "Only masked" для "Inpaint area", если вы применяете "Upscaler". Иначе, используйте функцию увеличения (апскейла) через вкладку "Extras" или через опциональный загрузчик "Script" (внизу экрана), применив "SD upscale" или "Ultimate SD upscale".
|
Inpainting также работает, но замена лица происходит только в области маски.<br>Пожалуйста, используйте с опцией "Only masked" для "Inpaint area", если вы применяете "Upscaler". Иначе, используйте функцию увеличения (апскейла) через вкладку "Extras" или через опциональный загрузчик "Script" (внизу экрана), применив "SD upscale" или "Ultimate SD upscale".
|
||||||
|
|
||||||
|
### Extras
|
||||||
|
|
||||||
|
Начиная с версии 0.5.0, вы можете использовать ReActor через вкладку Extras, что даёт очень быструю производительность и возможность замены лиц в обход пайплайна SD, что иногда вызывает размытие или искажение деталей оригинального изображения
|
||||||
|
|
||||||
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
Вы можете использовать ReActor как со встроенным SD Webui API так и через внешнее API.
|
Вы можете использовать ReActor как со встроенным SD Webui API так и через внешнее API.
|
||||||
@ -169,9 +261,9 @@ Inpainting также работает, но замена лица происх
|
|||||||
6. Для начала обновите pip: `pip install -U pip`
|
6. Для начала обновите pip: `pip install -U pip`
|
||||||
7. Далее:
|
7. Далее:
|
||||||
- `pip install insightface==0.7.3`
|
- `pip install insightface==0.7.3`
|
||||||
- `pip install onnx==1.14.0`
|
- `pip install onnx`
|
||||||
- `pip install onnxruntime==1.15.0`
|
- `pip install "onnxruntime-gpu>=1.16.1"`
|
||||||
- `pip install opencv-python==4.7.0.72`
|
- `pip install opencv-python`
|
||||||
- `pip install tqdm`
|
- `pip install tqdm`
|
||||||
8. Выполните `deactivate`, закройте Терминал или Консоль и запустите SD WebUI, ReActor должен запуститься без к-л проблем - если же нет, добро пожаловать в раздел "Issues".
|
8. Выполните `deactivate`, закройте Терминал или Консоль и запустите SD WebUI, ReActor должен запуститься без к-л проблем - если же нет, добро пожаловать в раздел "Issues".
|
||||||
|
|
||||||
@ -179,7 +271,7 @@ Inpainting также работает, но замена лица происх
|
|||||||
|
|
||||||
Для начала отключите любые другие Roop-подобные расширения:
|
Для начала отключите любые другие Roop-подобные расширения:
|
||||||
- Перейдите в 'Extensions -> Installed' и снимите флажок с ненужных:
|
- Перейдите в 'Extensions -> Installed' и снимите флажок с ненужных:
|
||||||
<img src="example/roop-off.png" alt="uncompatible-with-other-roop"/>
|
<img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>
|
||||||
- Нажмите 'Apply and restart UI'
|
- Нажмите 'Apply and restart UI'
|
||||||
|
|
||||||
Альтернативные решения:
|
Альтернативные решения:
|
||||||
@ -190,24 +282,24 @@ Inpainting также работает, но замена лица происх
|
|||||||
|
|
||||||
Отключите расширение "SD-CN-Animation" (или какое-либо другое, вызывающее конфликт)
|
Отключите расширение "SD-CN-Animation" (или какое-либо другое, вызывающее конфликт)
|
||||||
|
|
||||||
### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed"**
|
### **V. "INVALID_PROTOBUF : Load model from <...>\models\insightface\inswapper_128.onnx failed:Protobuf parsing failed" ИЛИ "AttributeError: 'NoneType' object has no attribute 'get'" ИЛИ "AttributeError: 'FaceSwapScript' object has no attribute 'save_original'"**
|
||||||
|
|
||||||
Эта ошибка появляется, если что-то не так с файлом модели `inswapper_128.onnx`.
|
Эта ошибка появляется, если что-то не так с файлом модели `inswapper_128.onnx`.
|
||||||
|
|
||||||
Скачайте вручную по ссылке [here](https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx)
|
Скачайте вручную по ссылке [here](https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx)
|
||||||
и сохраните в директорию `stable-diffusion-webui\models\insightface`, заменив имеющийся файл.
|
и сохраните в директорию `stable-diffusion-webui\models\insightface`, заменив имеющийся файл.
|
||||||
|
|
||||||
### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled"**
|
### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" ИЛИ "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
|
||||||
|
|
||||||
1. Закройте (остановите) SD WebUI Сервер, если он запущен
|
1. Закройте (остановите) SD WebUI Сервер, если он запущен
|
||||||
2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
|
2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
|
||||||
3. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
|
3. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
|
||||||
4. Затем:
|
4. Затем:
|
||||||
- `python -m pip install -U pip`
|
- `python -m pip install -U pip`
|
||||||
- `pip uninstall -y onnx onnxruntime onnxruntime-gpu onnxruntime-silicon`
|
- `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`
|
||||||
- `pip install onnx==1.14.0 onnxruntime==1.15.0`
|
- `pip install "onnxruntime-gpu>=1.16.1"`
|
||||||
|
|
||||||
Если это не помогло - значит какое-то другое расширение переустанавливает `onnxruntime` всякий раз, когда SD WebUI проверяет требования пакетов. Внимательно посмотрите список активных расширений. Если видите там "WD14 tagger" - попробуйте отключить его и ещё раз выполнить шаги выше. Это расширение вызывает переустановку `onnxruntime` на `onnxruntime-gpu` при каждом запуске SD WebUI.
|
Если это не помогло - значит какое-то другое расширение переустанавливает `onnxruntime` всякий раз, когда SD WebUI проверяет требования пакетов. Внимательно посмотрите список активных расширений. Некоторые расширения могут вызывать переустановку `onnxruntime-gpu` на версию `onnxruntime<1.16.1` при каждом запуске SD WebUI.<br>ORT 1.16.0 выкатили с ошибкой https://github.com/microsoft/onnxruntime/issues/17631 - не устанавливайте её!
|
||||||
|
|
||||||
### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
|
### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
|
||||||
|
|
||||||
@ -218,19 +310,19 @@ Inpainting также работает, но замена лица происх
|
|||||||
5. Затем:
|
5. Затем:
|
||||||
- `python -m pip install -U pip`
|
- `python -m pip install -U pip`
|
||||||
- `pip uninstall protobuf`
|
- `pip uninstall protobuf`
|
||||||
- `pip install protobuf==3.20.3`
|
- `pip install "protobuf>=3.20.3"`
|
||||||
|
|
||||||
Если это не помгло - значит, есть к-л другое расширение, которое использует более новую версию пакета protobuf, и SD WebUI устанавливает эту версию при каждом запуске.
|
Если это не помгло - значит, есть к-л другое расширение, которое использует неподходящую версию пакета protobuf, и SD WebUI устанавливает эту версию при каждом запуске.
|
||||||
|
|
||||||
<a name="insightfacebuild">
|
<a name="insightfacebuild">
|
||||||
|
|
||||||
### **VIII. (Для пользователей Windows) Если вы до сих пор не можете установить пакет Insightface по каким-то причинам или же просто не желаете устанавливать Visual Studio или VS C++ Build Tools - сделайте следующее:**
|
### **VIII. (Для пользователей Windows) Если вы до сих пор не можете установить пакет Insightface по каким-то причинам или же просто не желаете устанавливать Visual Studio или VS C++ Build Tools - сделайте следующее:**
|
||||||
|
|
||||||
1. Закройте (остановите) SD WebUI Сервер, если он запущен
|
1. Закройте (остановите) SD WebUI Сервер, если он запущен
|
||||||
2. Скачайте готовый [пакет Insightface](https://github.com/Gourieff/sd-webui-reactor/raw/main/example/insightface-0.7.3-cp310-cp310-win_amd64.whl) и сохраните его в корневую директорию stable-diffusion-webui (или SD.Next) - туда, где лежит файл "webui-user.bat"
|
2. Скачайте готовый [пакет Insightface](https://github.com/Gourieff/Assets/raw/main/Insightface/insightface-0.7.3-cp310-cp310-win_amd64.whl) и сохраните его в корневую директорию stable-diffusion-webui (или SD.Next) - туда, где лежит файл "webui-user.bat" или (A1111 Portable) "run.bat"
|
||||||
3. Из корневой директории откройте Консоль (CMD) и выполните `.\venv\Scripts\activate`
|
3. Из корневой директории откройте Консоль (CMD) и выполните `.\venv\Scripts\activate`<br>ИЛИ<br>(A1111 Portable) Откройте Консоль (CMD)
|
||||||
4. Обновите PIP: `python -m pip install -U pip`
|
4. Обновите PIP: `python -m pip install -U pip`<br>ИЛИ<br>(A1111 Portable)`system\python\python.exe -m pip install -U pip`
|
||||||
5. Затем установите Insightface: `pip install insightface-0.7.3-cp310-cp310-win_amd64.whl`
|
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`
|
||||||
6. Готово!
|
6. Готово!
|
||||||
|
|
||||||
### **IX. Ошибка обновления 07-Август-23**
|
### **IX. Ошибка обновления 07-Август-23**
|
||||||
@ -247,6 +339,9 @@ Inpainting также работает, но замена лица происх
|
|||||||
|
|
||||||
Полностью удалите папку `sd-webui-reactor` внутри директории `extensions`, запустите Терминал или Консоль (cmd) и выполните `git clone https://github.com/Gourieff/sd-webui-reactor`
|
Полностью удалите папку `sd-webui-reactor` внутри директории `extensions`, запустите Терминал или Консоль (cmd) и выполните `git clone https://github.com/Gourieff/sd-webui-reactor`
|
||||||
|
|
||||||
|
### **X. Ошибки установки в StabilityMatrix**
|
||||||
|
|
||||||
|
Если вы столкнулись с ошибками при установки данного расширения в пакетном менеджере StabilityMatrix - изучите информацию по ссылке: https://github.com/Gourieff/sd-webui-reactor/issues/129#issuecomment-1768210875
|
||||||
|
|
||||||
<a name="updating">
|
<a name="updating">
|
||||||
|
|
||||||
@ -275,3 +370,58 @@ Inpainting также работает, но замена лица происх
|
|||||||
- пропагандируют любую информацию (как общедоступную, так и личную) или изображения (как общедоступные, так и личные), которые могут быть направлены на причинение вреда;
|
- пропагандируют любую информацию (как общедоступную, так и личную) или изображения (как общедоступные, так и личные), которые могут быть направлены на причинение вреда;
|
||||||
- используются для распространения дезинформации;
|
- используются для распространения дезинформации;
|
||||||
- нацелены на уязвимые группы людей.
|
- нацелены на уязвимые группы людей.
|
||||||
|
|
||||||
|
Данное программное обеспечение использует предварительно обученные модели `buffalo_l` и `inswapper_128.onnx`, представленные разработчиками [InsightFace](https://github.com/deepinsight/insightface/). Эти модели распространяются при следующих условиях:
|
||||||
|
|
||||||
|
[Перевод из текста лицензии insighface](https://github.com/deepinsight/insightface/tree/master/python-package): Предварительно обученные модели InsightFace доступны только для некоммерческих исследовательских целей. Сюда входят как модели с автоматической загрузкой, так и модели, загруженные вручную.
|
||||||
|
|
||||||
|
Пользователи данного программного обеспечения должны строго соблюдать данные условия использования. Разработчики и Со-авторы данного программного продукта не несут ответственности за неправильное использование предварительно обученных моделей InsightFace.
|
||||||
|
|
||||||
|
Обратите внимание: если вы собираетесь использовать это программное обеспечение в каких-либо коммерческих целях, вам необходимо будет обучить свои собственные модели или найти модели, которые можно использовать в коммерческих целях.
|
||||||
|
|
||||||
|
### Хэш файлов моделей
|
||||||
|
|
||||||
|
#### Безопасные для использования модели имеют следующий хэш:
|
||||||
|
|
||||||
|
inswapper_128.onnx
|
||||||
|
```
|
||||||
|
MD5:a3a155b90354160350efd66fed6b3d80
|
||||||
|
SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
|
||||||
|
```
|
||||||
|
|
||||||
|
1k3d68.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:6fb94fcdb0055e3638bf9158e6a108f4
|
||||||
|
SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
|
||||||
|
```
|
||||||
|
|
||||||
|
2d106det.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:a3613ef9eb3662b4ef88eb90db1fcf26
|
||||||
|
SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
|
||||||
|
```
|
||||||
|
|
||||||
|
det_10g.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:4c10eef5c9e168357a16fdd580fa8371
|
||||||
|
SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
|
||||||
|
```
|
||||||
|
|
||||||
|
genderage.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:81c77ba87ab38163b0dec6b26f8e2af2
|
||||||
|
SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
|
||||||
|
```
|
||||||
|
|
||||||
|
w600k_r50.onnx
|
||||||
|
|
||||||
|
```
|
||||||
|
MD5:80248d427976241cbd1343889ed132b3
|
||||||
|
SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
|
||||||
|
```
|
||||||
|
|
||||||
|
**Пожалуйста, сравните хэш, если вы скачиваете данные модели из непроверенных источников**
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 7.6 KiB |
@ -31,7 +31,7 @@ args=[
|
|||||||
1, #5 Restore visibility value
|
1, #5 Restore visibility value
|
||||||
True, #7 Restore face -> Upscale
|
True, #7 Restore face -> Upscale
|
||||||
'4x_NMKD-Superscale-SP_178000_G', #8 Upscaler (type 'None' if doesn't need), see full list here: http://127.0.0.1:7860/sdapi/v1/script-info -> reactor -> sec.8
|
'4x_NMKD-Superscale-SP_178000_G', #8 Upscaler (type 'None' if doesn't need), see full list here: http://127.0.0.1:7860/sdapi/v1/script-info -> reactor -> sec.8
|
||||||
2, #9 Upscaler scale value
|
1.5, #9 Upscaler scale value
|
||||||
1, #10 Upscaler visibility (if scale = 1)
|
1, #10 Upscaler visibility (if scale = 1)
|
||||||
False, #11 Swap in source image
|
False, #11 Swap in source image
|
||||||
True, #12 Swap in generated image
|
True, #12 Swap in generated image
|
||||||
@ -39,6 +39,19 @@ args=[
|
|||||||
0, #14 Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)
|
0, #14 Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)
|
||||||
0, #15 Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)
|
0, #15 Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)
|
||||||
False, #16 Save the original image(s) made before swapping
|
False, #16 Save the original image(s) made before swapping
|
||||||
|
0.8, #17 CodeFormer Weight (0 = maximum effect, 1 = minimum effect), 0.5 - by default
|
||||||
|
False, #18 Source Image Hash Check, True - by default
|
||||||
|
False, #19 Target Image Hash Check, False - by default
|
||||||
|
"CUDA", #20 CPU or CUDA (if you have it), CPU - by default
|
||||||
|
True, #21 Face Mask Correction
|
||||||
|
1, #22 Select Source, 0 - Image, 1 - Face Model, 2 - Source Folder
|
||||||
|
"elena.safetensors", #23 Filename of the face model (from "models/reactor/faces"), e.g. elena.safetensors, don't forger to set #22 to 1
|
||||||
|
"C:\PATH_TO_FACES_IMAGES", #24 The path to the folder containing source faces images, don't forger to set #22 to 2
|
||||||
|
None, #25 skip it for API
|
||||||
|
True, #26 Randomly select an image from the path
|
||||||
|
True, #27 Force Upscale even if no face found
|
||||||
|
0.6, #28 Face Detection Threshold
|
||||||
|
2, #29 Maximum number of faces to detect (0 is unlimited)
|
||||||
]
|
]
|
||||||
|
|
||||||
# The args for ReActor can be found by
|
# The args for ReActor can be found by
|
||||||
|
|||||||
@ -8,14 +8,22 @@ curl -X POST \
|
|||||||
"source_faces_index": [0],
|
"source_faces_index": [0],
|
||||||
"face_index": [2],
|
"face_index": [2],
|
||||||
"upscaler": "None",
|
"upscaler": "None",
|
||||||
"scale": 1,
|
"scale": 1.5,
|
||||||
"upscale_visibility": 1,
|
"upscale_visibility": 1,
|
||||||
"face_restorer": "CodeFormer",
|
"face_restorer": "CodeFormer",
|
||||||
"restorer_visibility": 1,
|
"restorer_visibility": 1,
|
||||||
|
"codeformer_weight": 0.5,
|
||||||
"restore_first": 1,
|
"restore_first": 1,
|
||||||
"model": "inswapper_128.onnx",
|
"model": "inswapper_128.onnx",
|
||||||
"gender_source": 0,
|
"gender_source": 0,
|
||||||
"gender_target": 0,
|
"gender_target": 0,
|
||||||
"save_to_file": 1,
|
"save_to_file": 1,
|
||||||
"result_file_path": ""
|
"result_file_path": "",
|
||||||
|
"device": "CUDA",
|
||||||
|
"mask_face": 1,
|
||||||
|
"select_source": 1,
|
||||||
|
"face_model": "elena.safetensors",
|
||||||
|
"source_folder": "C:/faces",
|
||||||
|
"random_image": 1,
|
||||||
|
"upscale_force": 1
|
||||||
}'
|
}'
|
||||||
|
|||||||
@ -4,14 +4,22 @@
|
|||||||
"source_faces_index": [0],
|
"source_faces_index": [0],
|
||||||
"face_index": [2],
|
"face_index": [2],
|
||||||
"upscaler": "None",
|
"upscaler": "None",
|
||||||
"scale": 1,
|
"scale": 1.5,
|
||||||
"upscale_visibility": 1,
|
"upscale_visibility": 1,
|
||||||
"face_restorer": "CodeFormer",
|
"face_restorer": "CodeFormer",
|
||||||
"restorer_visibility": 1,
|
"restorer_visibility": 1,
|
||||||
|
"codeformer_weight": 0.5,
|
||||||
"restore_first": 1,
|
"restore_first": 1,
|
||||||
"model": "inswapper_128.onnx",
|
"model": "inswapper_128.onnx",
|
||||||
"gender_source": 0,
|
"gender_source": 0,
|
||||||
"gender_target": 0,
|
"gender_target": 0,
|
||||||
"save_to_file": 1,
|
"save_to_file": 1,
|
||||||
"result_file_path": ""
|
"result_file_path": "",
|
||||||
|
"device": "CUDA",
|
||||||
|
"mask_face": 1,
|
||||||
|
"select_source": 1,
|
||||||
|
"face_model": "elena.safetensors",
|
||||||
|
"source_folder": "C:/faces",
|
||||||
|
"random_image": 1,
|
||||||
|
"upscale_force": 1
|
||||||
}
|
}
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 298 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 89 KiB |
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 31 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 13 KiB |
94
install.py
94
install.py
@ -1,25 +1,36 @@
|
|||||||
import subprocess
|
import subprocess
|
||||||
import os, sys
|
import os, sys
|
||||||
|
from typing import Any
|
||||||
import pkg_resources
|
import pkg_resources
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from packaging import version as pv
|
from packaging import version as pv
|
||||||
|
|
||||||
from modules.paths_internal import models_path
|
try:
|
||||||
|
from modules.paths_internal import models_path
|
||||||
|
except:
|
||||||
|
try:
|
||||||
|
from modules.paths import models_path
|
||||||
|
except:
|
||||||
|
models_path = os.path.abspath("models")
|
||||||
|
|
||||||
req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt")
|
|
||||||
|
|
||||||
models_dir_old = os.path.join(models_path, "roop")
|
BASE_PATH = os.path.dirname(os.path.realpath(__file__))
|
||||||
|
|
||||||
|
req_file = os.path.join(BASE_PATH, "requirements.txt")
|
||||||
|
|
||||||
models_dir = os.path.join(models_path, "insightface")
|
models_dir = os.path.join(models_path, "insightface")
|
||||||
if os.path.exists(models_dir_old):
|
|
||||||
os.rename(models_dir_old, models_dir)
|
model_url = "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx"
|
||||||
model_url = "https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx"
|
|
||||||
model_name = os.path.basename(model_url)
|
model_name = os.path.basename(model_url)
|
||||||
model_path = os.path.join(models_dir, model_name)
|
model_path = os.path.join(models_dir, model_name)
|
||||||
|
|
||||||
def run_pip(*args):
|
def pip_install(*args):
|
||||||
subprocess.run([sys.executable, "-m", "pip", "install", *args])
|
subprocess.run([sys.executable, "-m", "pip", "install", *args])
|
||||||
|
|
||||||
|
def pip_uninstall(*args):
|
||||||
|
subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", *args])
|
||||||
|
|
||||||
def is_installed (
|
def is_installed (
|
||||||
package: str, version: str | None = None, strict: bool = True
|
package: str, version: str | None = None, strict: bool = True
|
||||||
):
|
):
|
||||||
@ -50,9 +61,66 @@ if not os.path.exists(models_dir):
|
|||||||
if not os.path.exists(model_path):
|
if not os.path.exists(model_path):
|
||||||
download(model_url, model_path)
|
download(model_url, model_path)
|
||||||
|
|
||||||
print("Checking ReActor requirements...", end=' ')
|
# print("ReActor preheating...", end=' ')
|
||||||
|
|
||||||
|
last_device = None
|
||||||
|
first_run = False
|
||||||
|
available_devices = ["CPU", "CUDA"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
last_device_log = os.path.join(BASE_PATH, "last_device.txt")
|
||||||
|
with open(last_device_log) as f:
|
||||||
|
last_device = f.readline().strip()
|
||||||
|
if last_device not in available_devices:
|
||||||
|
last_device = None
|
||||||
|
except:
|
||||||
|
last_device = "CPU"
|
||||||
|
first_run = True
|
||||||
|
with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
|
||||||
|
txt.write(last_device)
|
||||||
|
|
||||||
with open(req_file) as file:
|
with open(req_file) as file:
|
||||||
install_count = 0
|
install_count = 0
|
||||||
|
ort = "onnxruntime-gpu"
|
||||||
|
import torch
|
||||||
|
cuda_version = None
|
||||||
|
try:
|
||||||
|
if torch.cuda.is_available():
|
||||||
|
cuda_version = torch.version.cuda
|
||||||
|
print(f"CUDA {cuda_version}")
|
||||||
|
if first_run or last_device is None:
|
||||||
|
last_device = "CUDA"
|
||||||
|
elif torch.backends.mps.is_available() or hasattr(torch,'dml') or hasattr(torch,'privateuseone'):
|
||||||
|
ort = "onnxruntime"
|
||||||
|
# to prevent errors when ORT-GPU is installed but we want ORT instead:
|
||||||
|
if first_run:
|
||||||
|
pip_uninstall("onnxruntime", "onnxruntime-gpu")
|
||||||
|
# just in case:
|
||||||
|
if last_device == "CUDA" or last_device is None:
|
||||||
|
last_device = "CPU"
|
||||||
|
else:
|
||||||
|
if last_device == "CUDA" or last_device is None:
|
||||||
|
last_device = "CPU"
|
||||||
|
with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
|
||||||
|
txt.write(last_device)
|
||||||
|
if cuda_version is not None:
|
||||||
|
if float(cuda_version)>=12: # CU12.x
|
||||||
|
extra_index_url = "https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/"
|
||||||
|
else: # CU11.8
|
||||||
|
extra_index_url = "https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-11/pypi/simple"
|
||||||
|
if not is_installed(ort,"1.17.1",True):
|
||||||
|
install_count += 1
|
||||||
|
ort = "onnxruntime-gpu==1.17.1"
|
||||||
|
pip_uninstall("onnxruntime", "onnxruntime-gpu")
|
||||||
|
pip_install(ort,"--extra-index-url",extra_index_url)
|
||||||
|
elif not is_installed(ort,"1.18.1",False):
|
||||||
|
install_count += 1
|
||||||
|
pip_install(ort, "-U")
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
print(f"\nERROR: Failed to install {ort} - ReActor won't start")
|
||||||
|
raise e
|
||||||
|
# print(f"Device: {last_device}")
|
||||||
strict = True
|
strict = True
|
||||||
for package in file:
|
for package in file:
|
||||||
package_version = None
|
package_version = None
|
||||||
@ -65,12 +133,14 @@ with open(req_file) as file:
|
|||||||
strict = False
|
strict = False
|
||||||
if not is_installed(package,package_version,strict):
|
if not is_installed(package,package_version,strict):
|
||||||
install_count += 1
|
install_count += 1
|
||||||
run_pip(package)
|
pip_install(package)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(e)
|
print(e)
|
||||||
print(f"\nERROR: Failed to install {package} - ReActor won't start")
|
print(f"\nERROR: Failed to install {package} - ReActor won't start")
|
||||||
raise e
|
raise e
|
||||||
if install_count > 0:
|
if install_count > 0:
|
||||||
print(f'\n--- PLEASE, RESTART the Server! ---\n')
|
print(f"""
|
||||||
else:
|
+---------------------------------+
|
||||||
print('Ok')
|
--- PLEASE, RESTART the Server! ---
|
||||||
|
+---------------------------------+
|
||||||
|
""")
|
||||||
|
|||||||
176
reactor_modules/reactor_mask.py
Normal file
176
reactor_modules/reactor_mask.py
Normal file
@ -0,0 +1,176 @@
|
|||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
from torchvision.transforms.functional import to_pil_image
|
||||||
|
|
||||||
|
from scripts.reactor_logger import logger
|
||||||
|
from scripts.reactor_inferencers.bisenet_mask_generator import BiSeNetMaskGenerator
|
||||||
|
from scripts.reactor_entities.face import FaceArea
|
||||||
|
from scripts.reactor_entities.rect import Rect
|
||||||
|
|
||||||
|
|
||||||
|
colors = [
|
||||||
|
(255, 0, 0),
|
||||||
|
(0, 255, 0),
|
||||||
|
(0, 0, 255),
|
||||||
|
(255, 255, 0),
|
||||||
|
(255, 0, 255),
|
||||||
|
(0, 255, 255),
|
||||||
|
(255, 255, 255),
|
||||||
|
(128, 0, 0),
|
||||||
|
(0, 128, 0),
|
||||||
|
(128, 128, 0),
|
||||||
|
(0, 0, 128),
|
||||||
|
(0, 128, 128),
|
||||||
|
]
|
||||||
|
|
||||||
|
def color_generator(colors):
|
||||||
|
while True:
|
||||||
|
for color in colors:
|
||||||
|
yield color
|
||||||
|
|
||||||
|
|
||||||
|
def process_face_image(
|
||||||
|
face: FaceArea,
|
||||||
|
**kwargs,
|
||||||
|
) -> Image:
|
||||||
|
image = np.array(face.image)
|
||||||
|
overlay = image.copy()
|
||||||
|
color_iter = color_generator(colors)
|
||||||
|
cv2.rectangle(overlay, (0, 0), (image.shape[1], image.shape[0]), next(color_iter), -1)
|
||||||
|
l, t, r, b = face.face_area_on_image
|
||||||
|
cv2.rectangle(overlay, (l, t), (r, b), (0, 0, 0), 10)
|
||||||
|
if face.landmarks_on_image is not None:
|
||||||
|
for landmark in face.landmarks_on_image:
|
||||||
|
cv2.circle(overlay, (int(landmark.x), int(landmark.y)), 6, (0, 0, 0), 10)
|
||||||
|
alpha = 0.3
|
||||||
|
output = cv2.addWeighted(image, 1 - alpha, overlay, alpha, 0)
|
||||||
|
|
||||||
|
return Image.fromarray(output)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_face_mask(swapped_image:np.ndarray,target_image:np.ndarray,target_face,entire_mask_image:np.array)->np.ndarray:
|
||||||
|
logger.status("Correcting Face Mask")
|
||||||
|
mask_generator = BiSeNetMaskGenerator()
|
||||||
|
face = FaceArea(target_image,Rect.from_ndarray(np.array(target_face.bbox)),1.6,512,"")
|
||||||
|
face_image = np.array(face.image)
|
||||||
|
process_face_image(face)
|
||||||
|
face_area_on_image = face.face_area_on_image
|
||||||
|
mask = mask_generator.generate_mask(
|
||||||
|
face_image,
|
||||||
|
face_area_on_image=face_area_on_image,
|
||||||
|
affected_areas=["Face"],
|
||||||
|
mask_size=0,
|
||||||
|
use_minimal_area=True
|
||||||
|
)
|
||||||
|
mask = cv2.blur(mask, (12, 12))
|
||||||
|
# """entire_mask_image = np.zeros_like(target_image)"""
|
||||||
|
larger_mask = cv2.resize(mask, dsize=(face.width, face.height))
|
||||||
|
entire_mask_image[
|
||||||
|
face.top : face.bottom,
|
||||||
|
face.left : face.right,
|
||||||
|
] = larger_mask
|
||||||
|
|
||||||
|
result = Image.composite(Image.fromarray(swapped_image),Image.fromarray(target_image), Image.fromarray(entire_mask_image).convert("L"))
|
||||||
|
return np.array(result)
|
||||||
|
|
||||||
|
|
||||||
|
def rotate_array(image: np.ndarray, angle: float) -> np.ndarray:
|
||||||
|
if angle == 0:
|
||||||
|
return image
|
||||||
|
|
||||||
|
h, w = image.shape[:2]
|
||||||
|
center = (w // 2, h // 2)
|
||||||
|
|
||||||
|
M = cv2.getRotationMatrix2D(center, angle, 1.0)
|
||||||
|
return cv2.warpAffine(image, M, (w, h))
|
||||||
|
|
||||||
|
|
||||||
|
def rotate_image(image: Image, angle: float) -> Image:
|
||||||
|
if angle == 0:
|
||||||
|
return image
|
||||||
|
return Image.fromarray(rotate_array(np.array(image), angle))
|
||||||
|
|
||||||
|
|
||||||
|
def correct_face_tilt(angle: float) -> bool:
|
||||||
|
angle = abs(angle)
|
||||||
|
if angle > 180:
|
||||||
|
angle = 360 - angle
|
||||||
|
return angle > 40
|
||||||
|
|
||||||
|
|
||||||
|
def _dilate(arr: np.ndarray, value: int) -> np.ndarray:
|
||||||
|
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value))
|
||||||
|
return cv2.dilate(arr, kernel, iterations=1)
|
||||||
|
|
||||||
|
|
||||||
|
def _erode(arr: np.ndarray, value: int) -> np.ndarray:
|
||||||
|
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value))
|
||||||
|
return cv2.erode(arr, kernel, iterations=1)
|
||||||
|
|
||||||
|
|
||||||
|
def dilate_erode(img: Image.Image, value: int) -> Image.Image:
|
||||||
|
"""
|
||||||
|
The dilate_erode function takes an image and a value.
|
||||||
|
If the value is positive, it dilates the image by that amount.
|
||||||
|
If the value is negative, it erodes the image by that amount.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
img: PIL.Image.Image
|
||||||
|
the image to be processed
|
||||||
|
value: int
|
||||||
|
kernel size of dilation or erosion
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
PIL.Image.Image
|
||||||
|
The image that has been dilated or eroded
|
||||||
|
"""
|
||||||
|
if value == 0:
|
||||||
|
return img
|
||||||
|
|
||||||
|
arr = np.array(img)
|
||||||
|
arr = _dilate(arr, value) if value > 0 else _erode(arr, -value)
|
||||||
|
|
||||||
|
return Image.fromarray(arr)
|
||||||
|
|
||||||
|
def mask_to_pil(masks, shape: tuple[int, int]) -> list[Image.Image]:
|
||||||
|
"""
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
masks: torch.Tensor, dtype=torch.float32, shape=(N, H, W).
|
||||||
|
The device can be CUDA, but `to_pil_image` takes care of that.
|
||||||
|
|
||||||
|
shape: tuple[int, int]
|
||||||
|
(width, height) of the original image
|
||||||
|
"""
|
||||||
|
n = masks.shape[0]
|
||||||
|
return [to_pil_image(masks[i], mode="L").resize(shape) for i in range(n)]
|
||||||
|
|
||||||
|
def create_mask_from_bbox(
|
||||||
|
bboxes: list[list[float]], shape: tuple[int, int]
|
||||||
|
) -> list[Image.Image]:
|
||||||
|
"""
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
bboxes: list[list[float]]
|
||||||
|
list of [x1, y1, x2, y2]
|
||||||
|
bounding boxes
|
||||||
|
shape: tuple[int, int]
|
||||||
|
shape of the image (width, height)
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
masks: list[Image.Image]
|
||||||
|
A list of masks
|
||||||
|
|
||||||
|
"""
|
||||||
|
masks = []
|
||||||
|
for bbox in bboxes:
|
||||||
|
mask = Image.new("L", shape, 0)
|
||||||
|
mask_draw = ImageDraw.Draw(mask)
|
||||||
|
mask_draw.rectangle(bbox, fill=255)
|
||||||
|
masks.append(mask)
|
||||||
|
return masks
|
||||||
5
reactor_ui/__init__.py
Normal file
5
reactor_ui/__init__.py
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import reactor_ui.reactor_upscale_ui as ui_upscale
|
||||||
|
import reactor_ui.reactor_tools_ui as ui_tools
|
||||||
|
import reactor_ui.reactor_settings_ui as ui_settings
|
||||||
|
import reactor_ui.reactor_main_ui as ui_main
|
||||||
|
import reactor_ui.reactor_detection_ui as ui_detection
|
||||||
54
reactor_ui/reactor_detection_ui.py
Normal file
54
reactor_ui/reactor_detection_ui.py
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
import gradio as gr
|
||||||
|
from scripts.reactor_swapper import (
|
||||||
|
clear_faces,
|
||||||
|
clear_faces_list,
|
||||||
|
clear_faces_target,
|
||||||
|
clear_faces_all
|
||||||
|
)
|
||||||
|
|
||||||
|
# TAB DETECTION
|
||||||
|
def show(show_br: bool = True):
|
||||||
|
with gr.Tab("Detection"):
|
||||||
|
with gr.Row():
|
||||||
|
det_thresh = gr.Slider(
|
||||||
|
minimum=0.1,
|
||||||
|
maximum=1.0,
|
||||||
|
value=0.5,
|
||||||
|
step=0.01,
|
||||||
|
label="Threshold",
|
||||||
|
info="The higher the value, the more sensitive the detection is to what is considered a face (0.5 by default)",
|
||||||
|
scale=2
|
||||||
|
)
|
||||||
|
det_maxnum = gr.Slider(
|
||||||
|
minimum=0,
|
||||||
|
maximum=20,
|
||||||
|
value=0,
|
||||||
|
step=1,
|
||||||
|
label="Max Faces",
|
||||||
|
info="Maximum number of faces to detect (0 is unlimited)",
|
||||||
|
scale=1
|
||||||
|
)
|
||||||
|
# gr.Markdown("<br>", visible=show_br)
|
||||||
|
gr.Markdown("Hashed images get processed with previously set detection parameters (the face is hashed with all available parameters to bypass the analyzer and speed up the process). Please clear the hash if you want to apply new detection settings.", visible=show_br)
|
||||||
|
with gr.Row():
|
||||||
|
imgs_hash_clear_single = gr.Button(
|
||||||
|
value="Clear Source Images Hash (Single)",
|
||||||
|
scale=1
|
||||||
|
)
|
||||||
|
imgs_hash_clear_multiple = gr.Button(
|
||||||
|
value="Clear Source Images Hash (Multiple)",
|
||||||
|
scale=1
|
||||||
|
)
|
||||||
|
imgs_hash_clear_target = gr.Button(
|
||||||
|
value="Clear Target Image Hash",
|
||||||
|
scale=1
|
||||||
|
)
|
||||||
|
imgs_hash_clear_all = gr.Button(
|
||||||
|
value="Clear All Hash"
|
||||||
|
)
|
||||||
|
progressbar_area = gr.Markdown("")
|
||||||
|
imgs_hash_clear_single.click(clear_faces,None,[progressbar_area])
|
||||||
|
imgs_hash_clear_multiple.click(clear_faces_list,None,[progressbar_area])
|
||||||
|
imgs_hash_clear_target.click(clear_faces_target,None,[progressbar_area])
|
||||||
|
imgs_hash_clear_all.click(clear_faces_all,None,[progressbar_area])
|
||||||
|
return det_thresh, det_maxnum
|
||||||
229
reactor_ui/reactor_main_ui.py
Normal file
229
reactor_ui/reactor_main_ui.py
Normal file
@ -0,0 +1,229 @@
|
|||||||
|
import gradio as gr
|
||||||
|
from scripts.reactor_helpers import (
|
||||||
|
get_model_names,
|
||||||
|
get_facemodels
|
||||||
|
)
|
||||||
|
from scripts.reactor_swapper import (
|
||||||
|
clear_faces_list,
|
||||||
|
)
|
||||||
|
from modules import shared
|
||||||
|
|
||||||
|
# SAVE_ORIGINAL: bool = False
|
||||||
|
|
||||||
|
def update_fm_list(selected: str):
|
||||||
|
try: # GR3.x
|
||||||
|
return gr.Dropdown.update(
|
||||||
|
value=selected, choices=get_model_names(get_facemodels)
|
||||||
|
)
|
||||||
|
except: # GR4.x
|
||||||
|
return gr.Dropdown(
|
||||||
|
value=selected, choices=get_model_names(get_facemodels)
|
||||||
|
)
|
||||||
|
|
||||||
|
# TAB MAIN
|
||||||
|
def show(is_img2img: bool, show_br: bool = True, **msgs):
|
||||||
|
|
||||||
|
# def on_select_source(selected: bool, evt: gr.SelectData):
|
||||||
|
def on_select_source(evt: gr.SelectData):
|
||||||
|
# global SAVE_ORIGINAL
|
||||||
|
if evt.index == 2:
|
||||||
|
# if SAVE_ORIGINAL != selected:
|
||||||
|
# SAVE_ORIGINAL = selected
|
||||||
|
try: # GR3.x
|
||||||
|
return {
|
||||||
|
control_col_1: gr.Column.update(visible=False),
|
||||||
|
control_col_2: gr.Column.update(visible=False),
|
||||||
|
control_col_3: gr.Column.update(visible=True),
|
||||||
|
# save_original: gr.Checkbox.update(value=False,visible=False),
|
||||||
|
imgs_hash_clear: gr.Button.update(visible=True)
|
||||||
|
}
|
||||||
|
except: # GR4.x
|
||||||
|
return {
|
||||||
|
control_col_1: gr.Column(visible=False),
|
||||||
|
control_col_2: gr.Column(visible=False),
|
||||||
|
control_col_3: gr.Column(visible=True),
|
||||||
|
# save_original: gr.Checkbox.update(value=False,visible=False),
|
||||||
|
imgs_hash_clear: gr.Button(visible=True)
|
||||||
|
}
|
||||||
|
if evt.index == 0:
|
||||||
|
try: # GR3.x
|
||||||
|
return {
|
||||||
|
control_col_1: gr.Column.update(visible=True),
|
||||||
|
control_col_2: gr.Column.update(visible=False),
|
||||||
|
control_col_3: gr.Column.update(visible=False),
|
||||||
|
# save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
|
||||||
|
imgs_hash_clear: gr.Button.update(visible=False)
|
||||||
|
}
|
||||||
|
except: # GR4.x
|
||||||
|
return {
|
||||||
|
control_col_1: gr.Column(visible=True),
|
||||||
|
control_col_2: gr.Column(visible=False),
|
||||||
|
control_col_3: gr.Column(visible=False),
|
||||||
|
# save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
|
||||||
|
imgs_hash_clear: gr.Button(visible=False)
|
||||||
|
}
|
||||||
|
if evt.index == 1:
|
||||||
|
try: # GR3.x
|
||||||
|
return {
|
||||||
|
control_col_1: gr.Column.update(visible=False),
|
||||||
|
control_col_2: gr.Column.update(visible=True),
|
||||||
|
control_col_3: gr.Column.update(visible=False),
|
||||||
|
# save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
|
||||||
|
imgs_hash_clear: gr.Button.update(visible=False)
|
||||||
|
}
|
||||||
|
except: # GR4.x
|
||||||
|
return {
|
||||||
|
control_col_1: gr.Column(visible=False),
|
||||||
|
control_col_2: gr.Column(visible=True),
|
||||||
|
control_col_3: gr.Column(visible=False),
|
||||||
|
# save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
|
||||||
|
imgs_hash_clear: gr.Button(visible=False)
|
||||||
|
}
|
||||||
|
|
||||||
|
progressbar_area = gr.Markdown("")
|
||||||
|
with gr.Tab("Main"):
|
||||||
|
with gr.Column():
|
||||||
|
with gr.Row():
|
||||||
|
select_source = gr.Radio(
|
||||||
|
["Image(s)","Face Model","Folder"],
|
||||||
|
value="Image(s)",
|
||||||
|
label="Select Source",
|
||||||
|
type="index",
|
||||||
|
scale=1,
|
||||||
|
)
|
||||||
|
with gr.Column(visible=False) as control_col_2:
|
||||||
|
with gr.Row():
|
||||||
|
face_models = get_model_names(get_facemodels)
|
||||||
|
face_model = gr.Dropdown(
|
||||||
|
choices=face_models,
|
||||||
|
label="Choose Face Model",
|
||||||
|
value="None",
|
||||||
|
scale=1,
|
||||||
|
)
|
||||||
|
fm_update = gr.Button(
|
||||||
|
value="🔄",
|
||||||
|
variant="tool",
|
||||||
|
)
|
||||||
|
fm_update.click(
|
||||||
|
update_fm_list,
|
||||||
|
inputs=[face_model],
|
||||||
|
outputs=[face_model],
|
||||||
|
)
|
||||||
|
imgs_hash_clear = gr.Button(
|
||||||
|
value="Clear Source Images Hash",
|
||||||
|
scale=1,
|
||||||
|
visible=False,
|
||||||
|
)
|
||||||
|
imgs_hash_clear.click(clear_faces_list,None,[progressbar_area])
|
||||||
|
gr.Markdown("<br>", visible=show_br)
|
||||||
|
with gr.Column(visible=True) as control_col_1:
|
||||||
|
with gr.Row():
|
||||||
|
selected_tab = gr.Textbox('tab_single', visible=False)
|
||||||
|
with gr.Tabs() as tab_single:
|
||||||
|
with gr.Tab('Single'):
|
||||||
|
img = gr.Image(
|
||||||
|
type="pil",
|
||||||
|
label="Single Source Image",
|
||||||
|
)
|
||||||
|
with gr.Tab('Multiple') as tab_multiple:
|
||||||
|
imgs = gr.Files(
|
||||||
|
label=f"Multiple Source Images{msgs['extra_multiple_source']}",
|
||||||
|
file_types=["image"],
|
||||||
|
)
|
||||||
|
tab_single.select(fn=lambda: 'tab_single', inputs=[], outputs=[selected_tab])
|
||||||
|
tab_multiple.select(fn=lambda: 'tab_multiple', inputs=[], outputs=[selected_tab])
|
||||||
|
with gr.Column(visible=False) as control_col_3:
|
||||||
|
gr.Markdown("<span style='display:block;text-align:right;padding-right:3px;margin: -15px 0;font-size:1.1em'><sup>Clear Hash if you see the previous face was swapped instead of the new one</sup></span>")
|
||||||
|
with gr.Row():
|
||||||
|
source_folder = gr.Textbox(
|
||||||
|
value="",
|
||||||
|
placeholder="Paste here the path to the folder containing source faces images",
|
||||||
|
label=f"Source Folder{msgs['extra_multiple_source']}",
|
||||||
|
scale=2,
|
||||||
|
)
|
||||||
|
random_image = gr.Checkbox(
|
||||||
|
False,
|
||||||
|
label="Random Image",
|
||||||
|
info="Randomly select an image from the path",
|
||||||
|
scale=1,
|
||||||
|
)
|
||||||
|
setattr(face_model, "do_not_save_to_config", True)
|
||||||
|
if is_img2img:
|
||||||
|
save_original = gr.Checkbox(
|
||||||
|
False,
|
||||||
|
label="Save Original (Swap in generated only)",
|
||||||
|
info="Save the original image(s) made before swapping"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
save_original = gr.Checkbox(
|
||||||
|
False,
|
||||||
|
label="Save Original",
|
||||||
|
info="Save the original image(s) made before swapping",
|
||||||
|
visible=show_br
|
||||||
|
)
|
||||||
|
# imgs.upload(on_files_upload_uncheck_so,[save_original],[save_original],show_progress=False)
|
||||||
|
# imgs.clear(on_files_clear,None,[save_original],show_progress=False)
|
||||||
|
imgs.clear(clear_faces_list,None,None,show_progress=False)
|
||||||
|
mask_face = gr.Checkbox(
|
||||||
|
False,
|
||||||
|
label="Face Mask Correction",
|
||||||
|
info="Apply this option if you see some pixelation around face contours"
|
||||||
|
)
|
||||||
|
gr.Markdown("<br>", visible=show_br)
|
||||||
|
gr.Markdown("Source Image (above):")
|
||||||
|
with gr.Row():
|
||||||
|
source_faces_index = gr.Textbox(
|
||||||
|
value="0",
|
||||||
|
placeholder="Which face(s) to use as Source (comma separated)",
|
||||||
|
label="Comma separated face number(s); Example: 0,2,1",
|
||||||
|
)
|
||||||
|
gender_source = gr.Radio(
|
||||||
|
["No", "Female Only", "Male Only"],
|
||||||
|
value="No",
|
||||||
|
label="Gender Detection (Source)",
|
||||||
|
type="index",
|
||||||
|
)
|
||||||
|
gr.Markdown("<br>", visible=show_br)
|
||||||
|
gr.Markdown("Target Image (result):")
|
||||||
|
with gr.Row():
|
||||||
|
faces_index = gr.Textbox(
|
||||||
|
value="0",
|
||||||
|
placeholder="Which face(s) to Swap into Target (comma separated)",
|
||||||
|
label="Comma separated face number(s); Example: 1,0,2",
|
||||||
|
)
|
||||||
|
gender_target = gr.Radio(
|
||||||
|
["No", "Female Only", "Male Only"],
|
||||||
|
value="No",
|
||||||
|
label="Gender Detection (Target)",
|
||||||
|
type="index",
|
||||||
|
)
|
||||||
|
gr.Markdown("<br>", visible=show_br)
|
||||||
|
with gr.Row():
|
||||||
|
face_restorer_name = gr.Radio(
|
||||||
|
label="Restore Face",
|
||||||
|
choices=["None"] + [x.name() for x in shared.face_restorers],
|
||||||
|
value=shared.face_restorers[0].name(),
|
||||||
|
type="value",
|
||||||
|
)
|
||||||
|
with gr.Column():
|
||||||
|
face_restorer_visibility = gr.Slider(
|
||||||
|
0, 1, 1, step=0.1, label="Restore Face Visibility"
|
||||||
|
)
|
||||||
|
codeformer_weight = gr.Slider(
|
||||||
|
0, 1, 0.5, step=0.1, label="CodeFormer Weight (Fidelity)", info="0 = far from original (max restoration), 1 = close to original (min restoration)"
|
||||||
|
)
|
||||||
|
gr.Markdown("<br>", visible=show_br)
|
||||||
|
swap_in_source = gr.Checkbox(
|
||||||
|
False,
|
||||||
|
label="Swap in source image",
|
||||||
|
visible=is_img2img,
|
||||||
|
)
|
||||||
|
swap_in_generated = gr.Checkbox(
|
||||||
|
True,
|
||||||
|
label="Swap in generated image",
|
||||||
|
visible=is_img2img,
|
||||||
|
)
|
||||||
|
# select_source.select(on_select_source,[save_original],[control_col_1,control_col_2,control_col_3,save_original,imgs_hash_clear],show_progress=False)
|
||||||
|
select_source.select(on_select_source,None,[control_col_1,control_col_2,control_col_3,imgs_hash_clear],show_progress=False)
|
||||||
|
|
||||||
|
return img, imgs, selected_tab, 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, random_image
|
||||||
77
reactor_ui/reactor_settings_ui.py
Normal file
77
reactor_ui/reactor_settings_ui.py
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
import gradio as gr
|
||||||
|
from scripts.reactor_logger import logger
|
||||||
|
from scripts.reactor_helpers import get_models, set_Device
|
||||||
|
from scripts.reactor_globals import DEVICE, DEVICE_LIST
|
||||||
|
try:
|
||||||
|
import torch.cuda as cuda
|
||||||
|
EP_is_visible = True if cuda.is_available() else False
|
||||||
|
except:
|
||||||
|
EP_is_visible = False
|
||||||
|
|
||||||
|
def update_models_list(selected: str):
|
||||||
|
return gr.Dropdown.update(
|
||||||
|
value=selected, choices=get_models()
|
||||||
|
)
|
||||||
|
|
||||||
|
def show(hash_check_block: bool = True):
|
||||||
|
# TAB SETTINGS
|
||||||
|
with gr.Tab("Settings"):
|
||||||
|
models = get_models()
|
||||||
|
with gr.Row(visible=EP_is_visible):
|
||||||
|
device = gr.Radio(
|
||||||
|
label="Execution Provider",
|
||||||
|
choices=DEVICE_LIST,
|
||||||
|
value=DEVICE,
|
||||||
|
type="value",
|
||||||
|
info="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",
|
||||||
|
scale=2,
|
||||||
|
)
|
||||||
|
save_device_btn = gr.Button("Save", scale=0)
|
||||||
|
save = gr.Markdown("", visible=EP_is_visible)
|
||||||
|
setattr(device, "do_not_save_to_config", True)
|
||||||
|
save_device_btn.click(
|
||||||
|
set_Device,
|
||||||
|
inputs=[device],
|
||||||
|
outputs=[save],
|
||||||
|
)
|
||||||
|
with gr.Row():
|
||||||
|
if len(models) == 0:
|
||||||
|
logger.warning(
|
||||||
|
"You should at least have one model in models directory, please read the doc here: https://github.com/Gourieff/sd-webui-reactor/"
|
||||||
|
)
|
||||||
|
model = gr.Dropdown(
|
||||||
|
choices=models,
|
||||||
|
label="Model not found, please download one and refresh the list"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
model = gr.Dropdown(
|
||||||
|
choices=models, label="Model", value=models[0]
|
||||||
|
)
|
||||||
|
models_update = gr.Button(
|
||||||
|
value="🔄",
|
||||||
|
variant="tool",
|
||||||
|
)
|
||||||
|
models_update.click(
|
||||||
|
update_models_list,
|
||||||
|
inputs=[model],
|
||||||
|
outputs=[model],
|
||||||
|
)
|
||||||
|
console_logging_level = gr.Radio(
|
||||||
|
["No log", "Minimum", "Default"],
|
||||||
|
value="Minimum",
|
||||||
|
label="Console Log Level",
|
||||||
|
type="index"
|
||||||
|
)
|
||||||
|
gr.Markdown("<br>", visible=hash_check_block)
|
||||||
|
with gr.Row(visible=hash_check_block):
|
||||||
|
source_hash_check = gr.Checkbox(
|
||||||
|
True,
|
||||||
|
label="Source Image Hash Check",
|
||||||
|
info="Recommended to keep it ON. Processing is faster when Source Image is the same."
|
||||||
|
)
|
||||||
|
target_hash_check = gr.Checkbox(
|
||||||
|
False,
|
||||||
|
label="Target Image Hash Check",
|
||||||
|
info="Affects if you use Extras tab or img2img with only 'Swap in source image' on."
|
||||||
|
)
|
||||||
|
return model, device, console_logging_level, source_hash_check, target_hash_check
|
||||||
61
reactor_ui/reactor_tools_ui.py
Normal file
61
reactor_ui/reactor_tools_ui.py
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
import gradio as gr
|
||||||
|
from scripts.reactor_swapper import build_face_model, blend_faces
|
||||||
|
|
||||||
|
# TAB TOOLS
|
||||||
|
def show():
|
||||||
|
with gr.Tab("Tools"):
|
||||||
|
with gr.Tab("Face Models"):
|
||||||
|
|
||||||
|
with gr.Tab("Single"):
|
||||||
|
gr.Markdown("Load an image containing one person, name it and click 'Build and Save'")
|
||||||
|
img_fm = gr.Image(
|
||||||
|
type="pil",
|
||||||
|
label="Load an Image to build -Face Model-",
|
||||||
|
)
|
||||||
|
with gr.Row(equal_height=True):
|
||||||
|
fm_name = gr.Textbox(
|
||||||
|
value="",
|
||||||
|
placeholder="Please type any name (e.g. Elena)",
|
||||||
|
label="Face Model Name",
|
||||||
|
)
|
||||||
|
save_fm_btn = gr.Button("Build and Save")
|
||||||
|
save_fm = gr.Markdown("You can find saved models in 'models/reactor/faces'")
|
||||||
|
save_fm_btn.click(
|
||||||
|
build_face_model,
|
||||||
|
inputs=[img_fm, fm_name],
|
||||||
|
outputs=[save_fm],
|
||||||
|
)
|
||||||
|
|
||||||
|
with gr.Tab("Blend"):
|
||||||
|
gr.Markdown("Load a set of images containing any person, name it and click 'Build and Save'")
|
||||||
|
with gr.Row():
|
||||||
|
imgs_fm = gr.Files(
|
||||||
|
label=f"Load Images to build -Blended Face Model-",
|
||||||
|
file_types=["image"]
|
||||||
|
)
|
||||||
|
with gr.Column():
|
||||||
|
compute_method = gr.Radio(
|
||||||
|
["Mean", "Median", "Mode"],
|
||||||
|
value="Mean",
|
||||||
|
label="Compute Method",
|
||||||
|
type="index",
|
||||||
|
info="Mean (recommended) - Average value (best result 👍); Median* - Mid-point value (may be funny 😅); Mode - Most common value (may be scary 😨); *Mean and Median will be similar if you load two images"
|
||||||
|
)
|
||||||
|
shape_check = gr.Checkbox(
|
||||||
|
False,
|
||||||
|
label="Check -Embedding Shape- on Similarity",
|
||||||
|
info="(Experimental) Turn it ON if you want to skip the faces which are too much different from the first one in the list to prevent some probable 'shape mismatches'"
|
||||||
|
)
|
||||||
|
with gr.Row(equal_height=True):
|
||||||
|
fm_name = gr.Textbox(
|
||||||
|
value="",
|
||||||
|
placeholder="Please type any name (e.g. Elena)",
|
||||||
|
label="Face Model Name",
|
||||||
|
)
|
||||||
|
save_fm_btn = gr.Button("Build and Save")
|
||||||
|
save_fm = gr.Markdown("You can find saved models in 'models/reactor/faces'")
|
||||||
|
save_fm_btn.click(
|
||||||
|
blend_faces,
|
||||||
|
inputs=[imgs_fm, fm_name, compute_method, shape_check],
|
||||||
|
outputs=[save_fm],
|
||||||
|
)
|
||||||
47
reactor_ui/reactor_upscale_ui.py
Normal file
47
reactor_ui/reactor_upscale_ui.py
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
import gradio as gr
|
||||||
|
from modules import shared
|
||||||
|
|
||||||
|
def update_upscalers_list(selected: str):
|
||||||
|
return gr.Dropdown.update(
|
||||||
|
value=selected, choices=[upscaler.name for upscaler in shared.sd_upscalers]
|
||||||
|
)
|
||||||
|
|
||||||
|
# TAB UPSCALE
|
||||||
|
def show(show_br: bool = True):
|
||||||
|
with gr.Tab("Upscale"):
|
||||||
|
with gr.Row():
|
||||||
|
restore_first = gr.Checkbox(
|
||||||
|
True,
|
||||||
|
label="1. Restore Face -> 2. Upscale (-Uncheck- if you want vice versa)",
|
||||||
|
info="Postprocessing Order",
|
||||||
|
scale=2
|
||||||
|
)
|
||||||
|
upscale_force = gr.Checkbox(
|
||||||
|
False,
|
||||||
|
label="Force Upscale",
|
||||||
|
info="Upscale anyway - even if no face found",
|
||||||
|
scale=1
|
||||||
|
)
|
||||||
|
with gr.Row():
|
||||||
|
upscaler_name = gr.Dropdown(
|
||||||
|
choices=[upscaler.name for upscaler in shared.sd_upscalers],
|
||||||
|
label="Upscaler",
|
||||||
|
value="None",
|
||||||
|
info="Won't scale if you choose -Swap in Source- via img2img, only 1x-postprocessing will affect (texturing, denoising, restyling etc.)"
|
||||||
|
)
|
||||||
|
upscalers_update = gr.Button(
|
||||||
|
value="🔄",
|
||||||
|
variant="tool",
|
||||||
|
)
|
||||||
|
upscalers_update.click(
|
||||||
|
update_upscalers_list,
|
||||||
|
inputs=[upscaler_name],
|
||||||
|
outputs=[upscaler_name],
|
||||||
|
)
|
||||||
|
gr.Markdown("<br>", visible=show_br)
|
||||||
|
with gr.Row():
|
||||||
|
upscaler_scale = gr.Slider(1, 8, 1, step=0.1, label="Scale by")
|
||||||
|
upscaler_visibility = gr.Slider(
|
||||||
|
0, 1, 1, step=0.1, label="Upscaler Visibility (if scale = 1)"
|
||||||
|
)
|
||||||
|
return restore_first, upscaler_name, upscaler_scale, upscaler_visibility, upscale_force
|
||||||
@ -1,4 +1,4 @@
|
|||||||
|
albumentations==1.4.3
|
||||||
insightface==0.7.3
|
insightface==0.7.3
|
||||||
onnx==1.14.0
|
onnx==1.16.1
|
||||||
onnxruntime==1.15.0
|
|
||||||
opencv-python>=4.7.0.72
|
opencv-python>=4.7.0.72
|
||||||
|
|||||||
@ -2,7 +2,7 @@ import os.path as osp
|
|||||||
import glob
|
import glob
|
||||||
import logging
|
import logging
|
||||||
import insightface
|
import insightface
|
||||||
from insightface.model_zoo.model_zoo import ModelRouter, PickableInferenceSession
|
from insightface.model_zoo.model_zoo import ModelRouter, PickableInferenceSession, get_default_providers
|
||||||
from insightface.model_zoo.retinaface import RetinaFace
|
from insightface.model_zoo.retinaface import RetinaFace
|
||||||
from insightface.model_zoo.landmark import Landmark
|
from insightface.model_zoo.landmark import Landmark
|
||||||
from insightface.model_zoo.attribute import Attribute
|
from insightface.model_zoo.attribute import Attribute
|
||||||
@ -97,15 +97,20 @@ def patched_inswapper_init(self, model_file=None, session=None):
|
|||||||
self.input_size = tuple(input_shape[2:4][::-1])
|
self.input_size = tuple(input_shape[2:4][::-1])
|
||||||
|
|
||||||
|
|
||||||
def patch_insightface(get_model, faceanalysis_init, faceanalysis_prepare, inswapper_init):
|
def patched_get_default_providers():
|
||||||
|
return ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider']
|
||||||
|
|
||||||
|
|
||||||
|
def patch_insightface(get_default_providers, get_model, faceanalysis_init, faceanalysis_prepare, inswapper_init):
|
||||||
|
insightface.model_zoo.model_zoo.get_default_providers = get_default_providers
|
||||||
insightface.model_zoo.model_zoo.ModelRouter.get_model = get_model
|
insightface.model_zoo.model_zoo.ModelRouter.get_model = get_model
|
||||||
insightface.app.FaceAnalysis.__init__ = faceanalysis_init
|
insightface.app.FaceAnalysis.__init__ = faceanalysis_init
|
||||||
insightface.app.FaceAnalysis.prepare = faceanalysis_prepare
|
insightface.app.FaceAnalysis.prepare = faceanalysis_prepare
|
||||||
insightface.model_zoo.inswapper.INSwapper.__init__ = inswapper_init
|
insightface.model_zoo.inswapper.INSwapper.__init__ = inswapper_init
|
||||||
|
|
||||||
|
|
||||||
original_functions = [ModelRouter.get_model, FaceAnalysis.__init__, FaceAnalysis.prepare, INSwapper.__init__]
|
original_functions = [patched_get_default_providers, ModelRouter.get_model, FaceAnalysis.__init__, FaceAnalysis.prepare, INSwapper.__init__]
|
||||||
patched_functions = [patched_get_model, patched_faceanalysis_init, patched_faceanalysis_prepare, patched_inswapper_init]
|
patched_functions = [patched_get_default_providers, patched_get_model, patched_faceanalysis_init, patched_faceanalysis_prepare, patched_inswapper_init]
|
||||||
|
|
||||||
|
|
||||||
def apply_logging_patch(console_logging_level):
|
def apply_logging_patch(console_logging_level):
|
||||||
@ -114,7 +119,7 @@ def apply_logging_patch(console_logging_level):
|
|||||||
logger.setLevel(logging.WARNING)
|
logger.setLevel(logging.WARNING)
|
||||||
elif console_logging_level == 1:
|
elif console_logging_level == 1:
|
||||||
patch_insightface(*patched_functions)
|
patch_insightface(*patched_functions)
|
||||||
logger.setLevel(logging.INFO)
|
logger.setLevel(logging.STATUS)
|
||||||
elif console_logging_level == 2:
|
elif console_logging_level == 2:
|
||||||
patch_insightface(*original_functions)
|
patch_insightface(*original_functions)
|
||||||
logger.setLevel(logging.INFO)
|
logger.setLevel(logging.INFO)
|
||||||
|
|||||||
@ -1,12 +1,23 @@
|
|||||||
'''
|
'''
|
||||||
Thanks SpenserCai for the original version of the roop api script
|
Thanks SpenserCai for the original version of the roop api script
|
||||||
-----------------------------------
|
-----------------------------------
|
||||||
--- ReActor External API v1.0.0 ---
|
--- ReActor External API v1.0.8a ---
|
||||||
-----------------------------------
|
-----------------------------------
|
||||||
'''
|
'''
|
||||||
import os, glob
|
import os, glob
|
||||||
from datetime import datetime, date
|
from datetime import datetime, date
|
||||||
from fastapi import FastAPI, Body
|
from fastapi import FastAPI, Body
|
||||||
|
# from fastapi.exceptions import HTTPException
|
||||||
|
# from io import BytesIO
|
||||||
|
# from PIL import Image
|
||||||
|
# import base64
|
||||||
|
# import numpy as np
|
||||||
|
# import cv2
|
||||||
|
import asyncio
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
# from concurrent.futures.process import ProcessPoolExecutor
|
||||||
|
# from contextlib import asynccontextmanager
|
||||||
|
# import multiprocessing
|
||||||
|
|
||||||
# from modules.api.models import *
|
# from modules.api.models import *
|
||||||
from modules import scripts, shared
|
from modules import scripts, shared
|
||||||
@ -14,8 +25,32 @@ from modules.api import api
|
|||||||
|
|
||||||
import gradio as gr
|
import gradio as gr
|
||||||
|
|
||||||
from scripts.reactor_swapper import UpscaleOptions, swap_face
|
from scripts.reactor_swapper import EnhancementOptions, blend_faces, swap_face, DetectionOptions
|
||||||
from scripts.reactor_logger import logger
|
from scripts.reactor_logger import logger
|
||||||
|
from scripts.reactor_helpers import get_facemodels
|
||||||
|
|
||||||
|
|
||||||
|
# @asynccontextmanager
|
||||||
|
# async def lifespan(app: FastAPI):
|
||||||
|
# app.state.executor = ProcessPoolExecutor(max_workers=4)
|
||||||
|
# yield
|
||||||
|
# app.state.executor.shutdown()
|
||||||
|
|
||||||
|
# app = FastAPI(lifespan=lifespan)
|
||||||
|
|
||||||
|
# def run_app(a: FastAPI):
|
||||||
|
# global app
|
||||||
|
# a = app
|
||||||
|
# return a
|
||||||
|
|
||||||
|
# _executor_tp = ThreadPoolExecutor(max_workers=8)
|
||||||
|
# def entry_point():
|
||||||
|
# _executor_pp = ProcessPoolExecutor(max_workers=8)
|
||||||
|
# pool = multiprocessing.Pool(4)
|
||||||
|
|
||||||
|
async def run_event(app, fn, *args):
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
return await loop.run_in_executor(app.state.executor, fn, *args)
|
||||||
|
|
||||||
|
|
||||||
def default_file_path():
|
def default_file_path():
|
||||||
@ -52,7 +87,21 @@ def get_full_model(model_name):
|
|||||||
return model
|
return model
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
# def decode_base64_to_image_rgba(encoding):
|
||||||
|
# if encoding.startswith("data:image/"):
|
||||||
|
# encoding = encoding.split(";")[1].split(",")[1]
|
||||||
|
# try:
|
||||||
|
# im_bytes = base64.b64decode(encoding)
|
||||||
|
# im_arr = np.frombuffer(im_bytes, dtype=np.uint8) # im_arr is one-dim Numpy array
|
||||||
|
# img = cv2.imdecode(im_arr, flags=cv2.IMREAD_UNCHANGED)
|
||||||
|
# img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA)
|
||||||
|
# image = Image.fromarray(img, mode="RGBA")
|
||||||
|
# return image
|
||||||
|
# except Exception as e:
|
||||||
|
# raise HTTPException(status_code=500, detail="Invalid encoded image") from e
|
||||||
|
|
||||||
def reactor_api(_: gr.Blocks, app: FastAPI):
|
def reactor_api(_: gr.Blocks, app: FastAPI):
|
||||||
|
app.state.executor = ThreadPoolExecutor(max_workers=8)
|
||||||
@app.post("/reactor/image")
|
@app.post("/reactor/image")
|
||||||
async def reactor_image(
|
async def reactor_image(
|
||||||
source_image: str = Body("",title="Source Face Image"),
|
source_image: str = Body("",title="Source Face Image"),
|
||||||
@ -60,38 +109,67 @@ def reactor_api(_: gr.Blocks, app: FastAPI):
|
|||||||
source_faces_index: list[int] = Body([0],title="Comma separated face number(s) from swap-source image"),
|
source_faces_index: list[int] = Body([0],title="Comma separated face number(s) from swap-source image"),
|
||||||
face_index: list[int] = Body([0],title="Comma separated face number(s) for target image (result)"),
|
face_index: list[int] = Body([0],title="Comma separated face number(s) for target image (result)"),
|
||||||
upscaler: str = Body("None",title="Upscaler"),
|
upscaler: str = Body("None",title="Upscaler"),
|
||||||
scale: int = Body(1,title="Scale by"),
|
scale: float = Body(1,title="Scale by"),
|
||||||
upscale_visibility: float = Body(1,title="Upscaler visibility (if scale = 1)"),
|
upscale_visibility: float = Body(1,title="Upscaler visibility (if scale = 1)"),
|
||||||
face_restorer: str = Body("None",title="Restore Face: 0 - None; 1 - CodeFormer; 2 - GFPGA"),
|
face_restorer: str = Body("None",title="Restore Face: 0 - None; 1 - CodeFormer; 2 - GFPGA"),
|
||||||
restorer_visibility: float = Body(1,title="Restore visibility value"),
|
restorer_visibility: float = Body(1,title="Restore visibility value"),
|
||||||
|
codeformer_weight: float = Body(0.5,title="CodeFormer Weight"),
|
||||||
restore_first: int = Body(1,title="Restore face -> Then upscale, 1 - True, 0 - False"),
|
restore_first: int = Body(1,title="Restore face -> Then upscale, 1 - True, 0 - False"),
|
||||||
model: str = Body("inswapper_128.onnx",title="Model"),
|
model: str = Body("inswapper_128.onnx",title="Model"),
|
||||||
gender_source: int = Body(0,title="Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)"),
|
gender_source: int = Body(0,title="Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)"),
|
||||||
gender_target: int = Body(0,title="Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)"),
|
gender_target: int = Body(0,title="Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)"),
|
||||||
save_to_file: int = Body(0,title="Save Result to file, 0 - No, 1 - Yes"),
|
save_to_file: int = Body(0,title="Save Result to file, 0 - No, 1 - Yes"),
|
||||||
result_file_path: str = Body("",title="(if 'save_to_file = 1') Result file path")
|
result_file_path: str = Body("",title="(if 'save_to_file = 1') Result file path"),
|
||||||
|
device: str = Body("CPU",title="CPU or CUDA (if you have it)"),
|
||||||
|
mask_face: int = Body(0,title="Face Mask Correction, 1 - True, 0 - False"),
|
||||||
|
select_source: int = Body(0,title="Select Source, 0 - Image, 1 - Face Model, 2 - Source Folder"),
|
||||||
|
face_model: str = Body("None",title="Filename of the face model (from 'models/reactor/faces'), e.g. elena.safetensors"),
|
||||||
|
source_folder: str = Body("",title="The path to the folder containing source faces images"),
|
||||||
|
random_image: int = Body(0,title="Randomly select an image from the path"),
|
||||||
|
upscale_force: int = Body(0,title="Force Upscale even if no face found"),
|
||||||
|
det_thresh: float = Body(0.5,title="Face Detection Threshold"),
|
||||||
|
det_maxnum: int = Body(0,title="Maximum number of faces to detect (0 is unlimited)"),
|
||||||
):
|
):
|
||||||
s_image = api.decode_base64_to_image(source_image)
|
s_image = api.decode_base64_to_image(source_image) if select_source == 0 else None
|
||||||
t_image = api.decode_base64_to_image(target_image)
|
t_image = api.decode_base64_to_image(target_image)
|
||||||
|
|
||||||
|
if t_image.mode == 'RGBA':
|
||||||
|
_, _, _, alpha = t_image.split()
|
||||||
|
else:
|
||||||
|
alpha = None
|
||||||
|
|
||||||
sf_index = source_faces_index
|
sf_index = source_faces_index
|
||||||
f_index = face_index
|
f_index = face_index
|
||||||
gender_s = gender_source
|
gender_s = gender_source
|
||||||
gender_t = gender_target
|
gender_t = gender_target
|
||||||
restore_first_bool = True if restore_first == 1 else False
|
restore_first_bool = True if restore_first == 1 else False
|
||||||
up_options = UpscaleOptions(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)
|
mask_face = True if mask_face == 1 else False
|
||||||
|
random_image = False if random_image == 0 else True
|
||||||
|
upscale_force = False if upscale_force == 0 else True
|
||||||
|
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,upscale_force=upscale_force)
|
||||||
|
det_options = DetectionOptions(det_thresh=det_thresh, det_maxnum=det_maxnum)
|
||||||
use_model = get_full_model(model)
|
use_model = get_full_model(model)
|
||||||
if use_model is None:
|
if use_model is None:
|
||||||
Exception("Model not found")
|
Exception("Model not found")
|
||||||
result = swap_face(s_image, t_image, use_model, sf_index, f_index, up_options, gender_s, gender_t)
|
|
||||||
|
args = [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, random_image,det_options]
|
||||||
|
# result,_,_ = pool.map(swap_face, *args)
|
||||||
|
result,_,_ = await run_event(app,swap_face,*args)
|
||||||
|
# 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, random_image,det_options)
|
||||||
|
|
||||||
|
if alpha is not None:
|
||||||
|
result = result.convert("RGBA")
|
||||||
|
result.putalpha(alpha)
|
||||||
|
|
||||||
if save_to_file == 1:
|
if save_to_file == 1:
|
||||||
if result_file_path == "":
|
if result_file_path == "":
|
||||||
result_file_path = default_file_path()
|
result_file_path = default_file_path()
|
||||||
try:
|
try:
|
||||||
result.save(result_file_path, format='PNG')
|
file_format = os.path.split(result_file_path)[1].split(".")[1]
|
||||||
|
result.save(result_file_path, format=file_format)
|
||||||
|
logger.status("Result has been saved to: %s", result_file_path)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("Error while saving result: %s",e)
|
logger.error("Error while saving result: %s",e)
|
||||||
finally:
|
|
||||||
logger.info("Result has been saved to: %s", result_file_path)
|
|
||||||
return {"image": api.encode_pil_to_base64(result)}
|
return {"image": api.encode_pil_to_base64(result)}
|
||||||
|
|
||||||
@app.get("/reactor/models")
|
@app.get("/reactor/models")
|
||||||
@ -104,9 +182,23 @@ def reactor_api(_: gr.Blocks, app: FastAPI):
|
|||||||
names = [upscaler.name for upscaler in shared.sd_upscalers]
|
names = [upscaler.name for upscaler in shared.sd_upscalers]
|
||||||
return {"upscalers": names}
|
return {"upscalers": names}
|
||||||
|
|
||||||
|
@app.get("/reactor/facemodels")
|
||||||
|
async def reactor_facemodels():
|
||||||
|
facemodels = [os.path.split(model)[1].split(".")[0] for model in get_facemodels()]
|
||||||
|
return {"facemodels": facemodels}
|
||||||
|
|
||||||
|
@app.post("/reactor/facemodels")
|
||||||
|
async def reactor_facemodels_build(
|
||||||
|
source_images: list[str] = Body([""],title="Source Face Image List"),
|
||||||
|
name: str = Body("",title="Face Model Name"),
|
||||||
|
compute_method: int = Body(0,title="Compute Method (Mean, Median, Mode)"),
|
||||||
|
):
|
||||||
|
images = [api.decode_base64_to_image(img) for img in source_images]
|
||||||
|
blend_faces(images, name, compute_method, False, is_api=True)
|
||||||
|
return {"facemodels": [os.path.split(model)[1].split(".")[0] for model in get_facemodels()]}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import modules.script_callbacks as script_callbacks
|
import modules.script_callbacks as script_callbacks
|
||||||
|
|
||||||
script_callbacks.on_app_started(reactor_api)
|
script_callbacks.on_app_started(reactor_api)
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|||||||
147
scripts/reactor_entities/face.py
Normal file
147
scripts/reactor_entities/face.py
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
import traceback
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
from modules import images
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
|
||||||
|
from scripts.reactor_entities.rect import Point, Rect
|
||||||
|
|
||||||
|
|
||||||
|
class FaceArea:
|
||||||
|
def __init__(self, entire_image: np.ndarray, face_area: Rect, face_margin: float, face_size: int, upscaler: str):
|
||||||
|
self.face_area = face_area
|
||||||
|
self.center = face_area.center
|
||||||
|
left, top, right, bottom = face_area.to_square()
|
||||||
|
|
||||||
|
self.left, self.top, self.right, self.bottom = self.__ensure_margin(
|
||||||
|
left, top, right, bottom, entire_image, face_margin
|
||||||
|
)
|
||||||
|
|
||||||
|
self.width = self.right - self.left
|
||||||
|
self.height = self.bottom - self.top
|
||||||
|
|
||||||
|
self.image = self.__crop_face_image(entire_image, face_size, upscaler)
|
||||||
|
self.face_size = face_size
|
||||||
|
self.scale_factor = face_size / self.width
|
||||||
|
self.face_area_on_image = self.__get_face_area_on_image()
|
||||||
|
self.landmarks_on_image = self.__get_landmarks_on_image()
|
||||||
|
|
||||||
|
def __get_face_area_on_image(self):
|
||||||
|
left = int((self.face_area.left - self.left) * self.scale_factor)
|
||||||
|
top = int((self.face_area.top - self.top) * self.scale_factor)
|
||||||
|
right = int((self.face_area.right - self.left) * self.scale_factor)
|
||||||
|
bottom = int((self.face_area.bottom - self.top) * self.scale_factor)
|
||||||
|
return self.__clip_values(left, top, right, bottom)
|
||||||
|
|
||||||
|
def __get_landmarks_on_image(self):
|
||||||
|
landmarks = []
|
||||||
|
if self.face_area.landmarks is not None:
|
||||||
|
for landmark in self.face_area.landmarks:
|
||||||
|
landmarks.append(
|
||||||
|
Point(
|
||||||
|
int((landmark.x - self.left) * self.scale_factor),
|
||||||
|
int((landmark.y - self.top) * self.scale_factor),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return landmarks
|
||||||
|
|
||||||
|
def __crop_face_image(self, entire_image: np.ndarray, face_size: int, upscaler: str):
|
||||||
|
cropped = entire_image[self.top : self.bottom, self.left : self.right, :]
|
||||||
|
if upscaler:
|
||||||
|
return images.resize_image(0, Image.fromarray(cropped), face_size, face_size, upscaler)
|
||||||
|
else:
|
||||||
|
return Image.fromarray(cv2.resize(cropped, dsize=(face_size, face_size)))
|
||||||
|
|
||||||
|
def __ensure_margin(self, left: int, top: int, right: int, bottom: int, entire_image: np.ndarray, margin: float):
|
||||||
|
entire_height, entire_width = entire_image.shape[:2]
|
||||||
|
|
||||||
|
side_length = right - left
|
||||||
|
margin = min(min(entire_height, entire_width) / side_length, margin)
|
||||||
|
diff = int((side_length * margin - side_length) / 2)
|
||||||
|
|
||||||
|
top = top - diff
|
||||||
|
bottom = bottom + diff
|
||||||
|
left = left - diff
|
||||||
|
right = right + diff
|
||||||
|
|
||||||
|
if top < 0:
|
||||||
|
bottom = bottom - top
|
||||||
|
top = 0
|
||||||
|
if left < 0:
|
||||||
|
right = right - left
|
||||||
|
left = 0
|
||||||
|
|
||||||
|
if bottom > entire_height:
|
||||||
|
top = top - (bottom - entire_height)
|
||||||
|
bottom = entire_height
|
||||||
|
if right > entire_width:
|
||||||
|
left = left - (right - entire_width)
|
||||||
|
right = entire_width
|
||||||
|
|
||||||
|
return left, top, right, bottom
|
||||||
|
|
||||||
|
def get_angle(self) -> float:
|
||||||
|
landmarks = getattr(self.face_area, "landmarks", None)
|
||||||
|
if landmarks is None:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
eye1 = getattr(landmarks, "eye1", None)
|
||||||
|
eye2 = getattr(landmarks, "eye2", None)
|
||||||
|
if eye2 is None or eye1 is None:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
dx = eye2.x - eye1.x
|
||||||
|
dy = eye2.y - eye1.y
|
||||||
|
if dx == 0:
|
||||||
|
dx = 1
|
||||||
|
angle = np.arctan(dy / dx) * 180 / np.pi
|
||||||
|
|
||||||
|
if dx < 0:
|
||||||
|
angle = (angle + 180) % 360
|
||||||
|
return angle
|
||||||
|
except Exception:
|
||||||
|
print(traceback.format_exc())
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def rotate_face_area_on_image(self, angle: float):
|
||||||
|
center = [
|
||||||
|
(self.face_area_on_image[0] + self.face_area_on_image[2]) / 2,
|
||||||
|
(self.face_area_on_image[1] + self.face_area_on_image[3]) / 2,
|
||||||
|
]
|
||||||
|
|
||||||
|
points = [
|
||||||
|
[self.face_area_on_image[0], self.face_area_on_image[1]],
|
||||||
|
[self.face_area_on_image[2], self.face_area_on_image[3]],
|
||||||
|
]
|
||||||
|
|
||||||
|
angle = np.radians(angle)
|
||||||
|
rot_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
|
||||||
|
|
||||||
|
points = np.array(points) - center
|
||||||
|
points = np.dot(points, rot_matrix.T)
|
||||||
|
points += center
|
||||||
|
left, top, right, bottom = (int(points[0][0]), int(points[0][1]), int(points[1][0]), int(points[1][1]))
|
||||||
|
|
||||||
|
left, right = (right, left) if left > right else (left, right)
|
||||||
|
top, bottom = (bottom, top) if top > bottom else (top, bottom)
|
||||||
|
|
||||||
|
width, height = right - left, bottom - top
|
||||||
|
if width < height:
|
||||||
|
left, right = left - (height - width) // 2, right + (height - width) // 2
|
||||||
|
elif height < width:
|
||||||
|
top, bottom = top - (width - height) // 2, bottom + (width - height) // 2
|
||||||
|
return self.__clip_values(left, top, right, bottom)
|
||||||
|
|
||||||
|
def __clip_values(self, *args):
|
||||||
|
result = []
|
||||||
|
for val in args:
|
||||||
|
if val < 0:
|
||||||
|
result.append(0)
|
||||||
|
elif val > self.face_size:
|
||||||
|
result.append(self.face_size)
|
||||||
|
else:
|
||||||
|
result.append(val)
|
||||||
|
return tuple(result)
|
||||||
78
scripts/reactor_entities/rect.py
Normal file
78
scripts/reactor_entities/rect.py
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
from typing import Dict, NamedTuple, Tuple
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
class Point(NamedTuple):
|
||||||
|
x: int
|
||||||
|
y: int
|
||||||
|
|
||||||
|
|
||||||
|
class Landmarks(NamedTuple):
|
||||||
|
eye1: Point
|
||||||
|
eye2: Point
|
||||||
|
nose: Point
|
||||||
|
mouth1: Point
|
||||||
|
mouth2: Point
|
||||||
|
|
||||||
|
|
||||||
|
class Rect:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
left: int,
|
||||||
|
top: int,
|
||||||
|
right: int,
|
||||||
|
bottom: int,
|
||||||
|
tag: str = "face",
|
||||||
|
landmarks: Landmarks = None,
|
||||||
|
attributes: Dict[str, str] = {},
|
||||||
|
) -> None:
|
||||||
|
self.tag = tag
|
||||||
|
self.left = left
|
||||||
|
self.top = top
|
||||||
|
self.right = right
|
||||||
|
self.bottom = bottom
|
||||||
|
self.center = int((right + left) / 2)
|
||||||
|
self.middle = int((top + bottom) / 2)
|
||||||
|
self.width = right - left
|
||||||
|
self.height = bottom - top
|
||||||
|
self.size = self.width * self.height
|
||||||
|
self.landmarks = landmarks
|
||||||
|
self.attributes = attributes
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_ndarray(
|
||||||
|
cls,
|
||||||
|
face_box: np.ndarray,
|
||||||
|
tag: str = "face",
|
||||||
|
landmarks: Landmarks = None,
|
||||||
|
attributes: Dict[str, str] = {},
|
||||||
|
) -> "Rect":
|
||||||
|
left, top, right, bottom, *_ = list(map(int, face_box))
|
||||||
|
return cls(left, top, right, bottom, tag, landmarks, attributes)
|
||||||
|
|
||||||
|
def to_tuple(self) -> Tuple[int, int, int, int]:
|
||||||
|
return self.left, self.top, self.right, self.bottom
|
||||||
|
|
||||||
|
def to_square(self):
|
||||||
|
left, top, right, bottom = self.to_tuple()
|
||||||
|
|
||||||
|
width = right - left
|
||||||
|
height = bottom - top
|
||||||
|
|
||||||
|
if width % 2 == 1:
|
||||||
|
right = right + 1
|
||||||
|
width = width + 1
|
||||||
|
if height % 2 == 1:
|
||||||
|
bottom = bottom + 1
|
||||||
|
height = height + 1
|
||||||
|
|
||||||
|
diff = int(abs(width - height) / 2)
|
||||||
|
if width > height:
|
||||||
|
top = top - diff
|
||||||
|
bottom = bottom + diff
|
||||||
|
else:
|
||||||
|
left = left - diff
|
||||||
|
right = right + diff
|
||||||
|
|
||||||
|
return left, top, right, bottom
|
||||||
@ -13,31 +13,45 @@ from modules.processing import (
|
|||||||
StableDiffusionProcessingImg2Img,
|
StableDiffusionProcessingImg2Img,
|
||||||
)
|
)
|
||||||
from modules.face_restoration import FaceRestoration
|
from modules.face_restoration import FaceRestoration
|
||||||
from modules.paths_internal import models_path
|
|
||||||
from modules.images import save_image
|
from modules.images import save_image
|
||||||
|
|
||||||
|
from reactor_ui import (
|
||||||
|
ui_main,
|
||||||
|
ui_upscale,
|
||||||
|
ui_tools,
|
||||||
|
ui_settings,
|
||||||
|
ui_detection,
|
||||||
|
)
|
||||||
from scripts.reactor_logger import logger
|
from scripts.reactor_logger import logger
|
||||||
from scripts.reactor_swapper import UpscaleOptions, swap_face, check_process_halt, reset_messaged
|
from scripts.reactor_swapper import (
|
||||||
|
EnhancementOptions,
|
||||||
|
DetectionOptions,
|
||||||
|
swap_face,
|
||||||
|
check_process_halt,
|
||||||
|
reset_messaged,
|
||||||
|
)
|
||||||
from scripts.reactor_version import version_flag, app_title
|
from scripts.reactor_version import version_flag, app_title
|
||||||
from scripts.console_log_patch import apply_logging_patch
|
from scripts.console_log_patch import apply_logging_patch
|
||||||
from scripts.reactor_helpers import make_grid
|
from scripts.reactor_helpers import (
|
||||||
|
make_grid,
|
||||||
|
set_Device,
|
||||||
|
get_SDNEXT,
|
||||||
|
)
|
||||||
|
from scripts.reactor_globals import SWAPPER_MODELS_PATH #, DEVICE, DEVICE_LIST
|
||||||
|
|
||||||
|
def IA_cap(cond: bool, label: str=""):
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
from modules.ui_components import InputAccordion
|
||||||
|
NO_IA = False
|
||||||
|
except:
|
||||||
|
NO_IA = True
|
||||||
|
InputAccordion = IA_cap
|
||||||
|
|
||||||
|
|
||||||
MODELS_PATH = None
|
def check_old_webui():
|
||||||
|
return NO_IA
|
||||||
def get_models():
|
|
||||||
global MODELS_PATH
|
|
||||||
models_path_init = os.path.join(models_path, "insightface/*")
|
|
||||||
models = glob.glob(models_path_init)
|
|
||||||
models = [x for x in models if x.endswith(".onnx") or x.endswith(".pth")]
|
|
||||||
models_names = []
|
|
||||||
for model in models:
|
|
||||||
model_path = os.path.split(model)
|
|
||||||
if MODELS_PATH is None:
|
|
||||||
MODELS_PATH = model_path[0]
|
|
||||||
model_name = model_path[1]
|
|
||||||
models_names.append(model_name)
|
|
||||||
return models_names
|
|
||||||
|
|
||||||
|
|
||||||
class FaceSwapScript(scripts.Script):
|
class FaceSwapScript(scripts.Script):
|
||||||
@ -48,99 +62,36 @@ class FaceSwapScript(scripts.Script):
|
|||||||
return scripts.AlwaysVisible
|
return scripts.AlwaysVisible
|
||||||
|
|
||||||
def ui(self, is_img2img):
|
def ui(self, is_img2img):
|
||||||
with gr.Accordion(f"{app_title}", open=False):
|
with (
|
||||||
with gr.Tab("Main"):
|
gr.Accordion(f"{app_title}", open=False) if check_old_webui() else InputAccordion(False, label=f"{app_title}") as enable
|
||||||
with gr.Column():
|
):
|
||||||
img = gr.inputs.Image(type="pil")
|
|
||||||
enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}")
|
# SD.Next or A1111 1.52:
|
||||||
save_original = gr.Checkbox(False, label="Save Original", info="Save the original image(s) made before swapping; If you use \"img2img\" - this option will affect with \"Swap in generated\" only")
|
if get_SDNEXT() or check_old_webui():
|
||||||
gr.Markdown("<br>")
|
enable = gr.Checkbox(False, label="Enable")
|
||||||
gr.Markdown("Source Image (above):")
|
|
||||||
with gr.Row():
|
# enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}")
|
||||||
source_faces_index = gr.Textbox(
|
gr.Markdown(f"<sup>The Fast and Simple FaceSwap Extension - {version_flag}</sup>")
|
||||||
value="0",
|
|
||||||
placeholder="Which face(s) to use as Source (comma separated)",
|
# TAB MAIN
|
||||||
label="Comma separated face number(s); Example: 0,2,1",
|
msgs: dict = {
|
||||||
)
|
"extra_multiple_source": "",
|
||||||
gender_source = gr.Radio(
|
}
|
||||||
["No", "Female Only", "Male Only"],
|
img, imgs, selected_tab, 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, random_image = ui_main.show(is_img2img=is_img2img, **msgs)
|
||||||
value="No",
|
|
||||||
label="Gender Detection (Source)",
|
# TAB DETECTION
|
||||||
type="index",
|
det_thresh, det_maxnum = ui_detection.show()
|
||||||
)
|
|
||||||
gr.Markdown("<br>")
|
# TAB UPSCALE
|
||||||
gr.Markdown("Target Image (result):")
|
restore_first, upscaler_name, upscaler_scale, upscaler_visibility, upscale_force = ui_upscale.show()
|
||||||
with gr.Row():
|
|
||||||
faces_index = gr.Textbox(
|
# TAB TOOLS
|
||||||
value="0",
|
ui_tools.show()
|
||||||
placeholder="Which face(s) to Swap into Target (comma separated)",
|
|
||||||
label="Comma separated face number(s); Example: 1,0,2",
|
# TAB SETTINGS
|
||||||
)
|
model, device, console_logging_level, source_hash_check, target_hash_check = ui_settings.show()
|
||||||
gender_target = gr.Radio(
|
|
||||||
["No", "Female Only", "Male Only"],
|
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>")
|
||||||
value="No",
|
|
||||||
label="Gender Detection (Target)",
|
|
||||||
type="index",
|
|
||||||
)
|
|
||||||
gr.Markdown("<br>")
|
|
||||||
with gr.Row():
|
|
||||||
face_restorer_name = gr.Radio(
|
|
||||||
label="Restore Face",
|
|
||||||
choices=["None"] + [x.name() for x in shared.face_restorers],
|
|
||||||
value=shared.face_restorers[0].name(),
|
|
||||||
type="value",
|
|
||||||
)
|
|
||||||
face_restorer_visibility = gr.Slider(
|
|
||||||
0, 1, 1, step=0.1, label="Restore Face Visibility"
|
|
||||||
)
|
|
||||||
gr.Markdown("<br>")
|
|
||||||
swap_in_source = gr.Checkbox(
|
|
||||||
False,
|
|
||||||
label="Swap in source image",
|
|
||||||
visible=is_img2img,
|
|
||||||
)
|
|
||||||
swap_in_generated = gr.Checkbox(
|
|
||||||
True,
|
|
||||||
label="Swap in generated image",
|
|
||||||
visible=is_img2img,
|
|
||||||
)
|
|
||||||
with gr.Tab("Upscale"):
|
|
||||||
restore_first = gr.Checkbox(
|
|
||||||
True,
|
|
||||||
label="1. Restore Face -> 2. Upscale (-Uncheck- if you want vice versa)",
|
|
||||||
info="Postprocessing Order"
|
|
||||||
)
|
|
||||||
upscaler_name = gr.inputs.Dropdown(
|
|
||||||
choices=[upscaler.name for upscaler in shared.sd_upscalers],
|
|
||||||
label="Upscaler",
|
|
||||||
)
|
|
||||||
gr.Markdown("<br>")
|
|
||||||
with gr.Row():
|
|
||||||
upscaler_scale = gr.Slider(1, 8, 1, step=0.1, label="Scale by")
|
|
||||||
upscaler_visibility = gr.Slider(
|
|
||||||
0, 1, 1, step=0.1, label="Upscaler Visibility (if scale = 1)"
|
|
||||||
)
|
|
||||||
with gr.Tab("Settings"):
|
|
||||||
models = get_models()
|
|
||||||
with gr.Row():
|
|
||||||
if len(models) == 0:
|
|
||||||
logger.warning(
|
|
||||||
"You should at least have one model in models directory, please read the doc here : https://github.com/Gourieff/sd-webui-reactor/"
|
|
||||||
)
|
|
||||||
model = gr.inputs.Dropdown(
|
|
||||||
choices=models,
|
|
||||||
label="Model not found, please download one and reload WebUI",
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
model = gr.inputs.Dropdown(
|
|
||||||
choices=models, label="Model", default=models[0]
|
|
||||||
)
|
|
||||||
console_logging_level = gr.Radio(
|
|
||||||
["No log", "Minimum", "Default"],
|
|
||||||
value="Minimum",
|
|
||||||
label="Console Log Level",
|
|
||||||
type="index",
|
|
||||||
)
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
img,
|
img,
|
||||||
@ -160,6 +111,20 @@ class FaceSwapScript(scripts.Script):
|
|||||||
gender_source,
|
gender_source,
|
||||||
gender_target,
|
gender_target,
|
||||||
save_original,
|
save_original,
|
||||||
|
codeformer_weight,
|
||||||
|
source_hash_check,
|
||||||
|
target_hash_check,
|
||||||
|
device,
|
||||||
|
mask_face,
|
||||||
|
select_source,
|
||||||
|
face_model,
|
||||||
|
source_folder,
|
||||||
|
imgs,
|
||||||
|
random_image,
|
||||||
|
upscale_force,
|
||||||
|
det_thresh,
|
||||||
|
det_maxnum,
|
||||||
|
selected_tab,
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -178,14 +143,23 @@ class FaceSwapScript(scripts.Script):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def upscale_options(self) -> UpscaleOptions:
|
def enhancement_options(self) -> EnhancementOptions:
|
||||||
return UpscaleOptions(
|
return EnhancementOptions(
|
||||||
do_restore_first = self.restore_first,
|
do_restore_first=self.restore_first,
|
||||||
scale=self.upscaler_scale,
|
scale=self.upscaler_scale,
|
||||||
upscaler=self.upscaler,
|
upscaler=self.upscaler,
|
||||||
face_restorer=self.face_restorer,
|
face_restorer=self.face_restorer,
|
||||||
upscale_visibility=self.upscaler_visibility,
|
upscale_visibility=self.upscaler_visibility,
|
||||||
restorer_visibility=self.face_restorer_visibility,
|
restorer_visibility=self.face_restorer_visibility,
|
||||||
|
codeformer_weight=self.codeformer_weight,
|
||||||
|
upscale_force=self.upscale_force
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def detection_options(self) -> DetectionOptions:
|
||||||
|
return DetectionOptions(
|
||||||
|
det_thresh=self.det_thresh,
|
||||||
|
det_maxnum=self.det_maxnum
|
||||||
)
|
)
|
||||||
|
|
||||||
def process(
|
def process(
|
||||||
@ -208,77 +182,162 @@ class FaceSwapScript(scripts.Script):
|
|||||||
gender_source,
|
gender_source,
|
||||||
gender_target,
|
gender_target,
|
||||||
save_original,
|
save_original,
|
||||||
|
codeformer_weight,
|
||||||
|
source_hash_check,
|
||||||
|
target_hash_check,
|
||||||
|
device,
|
||||||
|
mask_face,
|
||||||
|
select_source,
|
||||||
|
face_model,
|
||||||
|
source_folder,
|
||||||
|
imgs,
|
||||||
|
random_image,
|
||||||
|
upscale_force,
|
||||||
|
det_thresh,
|
||||||
|
det_maxnum,
|
||||||
|
selected_tab,
|
||||||
):
|
):
|
||||||
self.enable = enable
|
self.enable = enable
|
||||||
if self.enable:
|
if self.enable:
|
||||||
|
|
||||||
|
logger.debug("*** Start process")
|
||||||
|
|
||||||
reset_messaged()
|
reset_messaged()
|
||||||
if check_process_halt():
|
if check_process_halt():
|
||||||
return
|
return
|
||||||
|
|
||||||
global MODELS_PATH
|
global SWAPPER_MODELS_PATH
|
||||||
|
if selected_tab == "tab_single":
|
||||||
self.source = img
|
self.source = img
|
||||||
|
else:
|
||||||
|
self.source = None
|
||||||
self.face_restorer_name = face_restorer_name
|
self.face_restorer_name = face_restorer_name
|
||||||
self.upscaler_scale = upscaler_scale
|
self.upscaler_scale = upscaler_scale
|
||||||
self.upscaler_visibility = upscaler_visibility
|
self.upscaler_visibility = upscaler_visibility
|
||||||
self.face_restorer_visibility = face_restorer_visibility
|
self.face_restorer_visibility = face_restorer_visibility
|
||||||
self.restore_first = restore_first
|
self.restore_first = restore_first
|
||||||
self.upscaler_name = upscaler_name
|
self.upscaler_name = upscaler_name
|
||||||
|
self.swap_in_source = swap_in_source
|
||||||
self.swap_in_generated = swap_in_generated
|
self.swap_in_generated = swap_in_generated
|
||||||
self.model = os.path.join(MODELS_PATH,model)
|
self.model = os.path.join(SWAPPER_MODELS_PATH,model)
|
||||||
self.console_logging_level = console_logging_level
|
self.console_logging_level = console_logging_level
|
||||||
self.gender_source = gender_source
|
self.gender_source = gender_source
|
||||||
self.gender_target = gender_target
|
self.gender_target = gender_target
|
||||||
self.save_original = save_original
|
self.save_original = save_original
|
||||||
|
self.codeformer_weight = codeformer_weight
|
||||||
|
self.source_hash_check = source_hash_check
|
||||||
|
self.target_hash_check = target_hash_check
|
||||||
|
self.device = device
|
||||||
|
self.mask_face = mask_face
|
||||||
|
self.select_source = select_source
|
||||||
|
self.face_model = face_model
|
||||||
|
self.source_folder = source_folder
|
||||||
|
if selected_tab == "tab_single":
|
||||||
|
self.source_imgs = None
|
||||||
|
else:
|
||||||
|
self.source_imgs = imgs
|
||||||
|
self.random_image = random_image
|
||||||
|
self.upscale_force = upscale_force
|
||||||
|
self.det_thresh=det_thresh
|
||||||
|
self.det_maxnum=det_maxnum
|
||||||
if self.gender_source is None or self.gender_source == "No":
|
if self.gender_source is None or self.gender_source == "No":
|
||||||
self.gender_source = 0
|
self.gender_source = 0
|
||||||
if self.gender_target is None or self.gender_target == "No":
|
if self.gender_target is None or self.gender_target == "No":
|
||||||
self.gender_target = 0
|
self.gender_target = 0
|
||||||
self.source_faces_index = [
|
self.source_faces_index = [
|
||||||
int(x) for x in source_faces_index.strip(",").split(",") if x.isnumeric()
|
int(x) for x in source_faces_index.strip().replace(" ", "").strip(",").split(",") if x.isnumeric()
|
||||||
]
|
]
|
||||||
self.faces_index = [
|
self.faces_index = [
|
||||||
int(x) for x in faces_index.strip(",").split(",") if x.isnumeric()
|
int(x) for x in faces_index.strip().replace(" ", "").strip(",").split(",") if x.isnumeric()
|
||||||
]
|
]
|
||||||
if len(self.source_faces_index) == 0:
|
if len(self.source_faces_index) == 0:
|
||||||
self.source_faces_index = [0]
|
self.source_faces_index = [0]
|
||||||
if len(self.faces_index) == 0:
|
if len(self.faces_index) == 0:
|
||||||
self.faces_index = [0]
|
self.faces_index = [0]
|
||||||
|
if self.save_original is None:
|
||||||
|
self.save_original = False
|
||||||
|
if self.source_hash_check is None:
|
||||||
|
self.source_hash_check = True
|
||||||
|
if self.target_hash_check is None:
|
||||||
|
self.target_hash_check = False
|
||||||
|
if self.mask_face is None:
|
||||||
|
self.mask_face = False
|
||||||
|
if self.random_image is None:
|
||||||
|
self.random_image = False
|
||||||
|
if self.upscale_force is None:
|
||||||
|
self.upscale_force = False
|
||||||
|
|
||||||
if self.source is not None:
|
if shared.state.job_count > 0:
|
||||||
|
# logger.debug(f"Job count: {shared.state.job_count}")
|
||||||
|
self.face_restorer_visibility = shared.opts.data['restorer_visibility'] if 'restorer_visibility' in shared.opts.data.keys() else face_restorer_visibility
|
||||||
|
self.codeformer_weight = shared.opts.data['codeformer_weight'] if 'codeformer_weight' in shared.opts.data.keys() else codeformer_weight
|
||||||
|
self.mask_face = shared.opts.data['mask_face'] if 'mask_face' in shared.opts.data.keys() else mask_face
|
||||||
|
self.face_model = shared.opts.data['face_model'] if 'face_model' in shared.opts.data.keys() else face_model
|
||||||
|
|
||||||
|
logger.debug("*** Set Device")
|
||||||
|
set_Device(self.device)
|
||||||
|
|
||||||
|
if (self.save_original is None or not self.save_original) and (self.select_source == 2 or self.source_imgs is not None):
|
||||||
|
p.do_not_save_samples = True
|
||||||
|
|
||||||
|
if ((self.source is not None or self.source_imgs is not None) and self.select_source == 0) or ((self.face_model is not None and self.face_model != "None") and self.select_source == 1) or ((self.source_folder is not None and self.source_folder != "") and self.select_source == 2):
|
||||||
|
logger.debug("*** Log patch")
|
||||||
apply_logging_patch(console_logging_level)
|
apply_logging_patch(console_logging_level)
|
||||||
if isinstance(p, StableDiffusionProcessingImg2Img) and swap_in_source:
|
|
||||||
logger.info("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
if isinstance(p, StableDiffusionProcessingImg2Img) and self.swap_in_source:
|
||||||
|
|
||||||
|
logger.debug("*** Check process")
|
||||||
|
|
||||||
|
logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
||||||
|
|
||||||
for i in range(len(p.init_images)):
|
for i in range(len(p.init_images)):
|
||||||
if len(p.init_images) > 1:
|
if len(p.init_images) > 1:
|
||||||
logger.info("Swap in %s", i)
|
logger.status("Swap in %s", i)
|
||||||
result = swap_face(
|
result, output, swapped = swap_face(
|
||||||
self.source,
|
self.source,
|
||||||
p.init_images[i],
|
p.init_images[i],
|
||||||
source_faces_index=self.source_faces_index,
|
source_faces_index=self.source_faces_index,
|
||||||
faces_index=self.faces_index,
|
faces_index=self.faces_index,
|
||||||
model=self.model,
|
model=self.model,
|
||||||
upscale_options=self.upscale_options,
|
enhancement_options=self.enhancement_options,
|
||||||
gender_source=self.gender_source,
|
gender_source=self.gender_source,
|
||||||
gender_target=self.gender_target,
|
gender_target=self.gender_target,
|
||||||
|
source_hash_check=self.source_hash_check,
|
||||||
|
target_hash_check=self.target_hash_check,
|
||||||
|
device=self.device,
|
||||||
|
mask_face=self.mask_face,
|
||||||
|
select_source=self.select_source,
|
||||||
|
face_model = self.face_model,
|
||||||
|
source_folder = None,
|
||||||
|
source_imgs = None,
|
||||||
|
random_image = False,
|
||||||
|
detection_options=self.detection_options,
|
||||||
)
|
)
|
||||||
p.init_images[i] = result
|
p.init_images[i] = result
|
||||||
|
# result_path = get_image_path(p.init_images[i], p.outpath_samples, "", p.all_seeds[i], p.all_prompts[i], "txt", p=p, suffix="-swapped")
|
||||||
|
# if len(output) != 0:
|
||||||
|
# with open(result_path, 'w', encoding="utf8") as f:
|
||||||
|
# f.writelines(output)
|
||||||
|
|
||||||
if shared.state.interrupted or shared.state.skipped:
|
if shared.state.interrupted or shared.state.skipped:
|
||||||
return
|
return
|
||||||
|
|
||||||
else:
|
else:
|
||||||
logger.error("Please provide a source face")
|
logger.error("Please provide a source face")
|
||||||
|
return
|
||||||
|
|
||||||
def postprocess(self, p: StableDiffusionProcessing, processed: Processed, *args):
|
def postprocess(self, p: StableDiffusionProcessing, processed: Processed, *args):
|
||||||
if self.enable:
|
if self.enable:
|
||||||
|
|
||||||
|
logger.debug("*** Check postprocess - before IF")
|
||||||
|
|
||||||
reset_messaged()
|
reset_messaged()
|
||||||
if check_process_halt():
|
if check_process_halt():
|
||||||
return
|
return
|
||||||
|
|
||||||
if self.save_original:
|
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)):
|
||||||
|
|
||||||
|
logger.debug("*** Check postprocess - after IF")
|
||||||
|
|
||||||
postprocess_run: bool = True
|
postprocess_run: bool = True
|
||||||
|
|
||||||
@ -286,36 +345,77 @@ class FaceSwapScript(scripts.Script):
|
|||||||
orig_infotexts : List[str] = processed.infotexts[processed.index_of_first_image:]
|
orig_infotexts : List[str] = processed.infotexts[processed.index_of_first_image:]
|
||||||
|
|
||||||
result_images: List = processed.images
|
result_images: List = processed.images
|
||||||
|
# result_info: List = processed.infotexts
|
||||||
|
|
||||||
if self.swap_in_generated:
|
if self.swap_in_generated:
|
||||||
logger.info("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
|
||||||
|
logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
||||||
|
|
||||||
if self.source is not None:
|
if self.source is not None:
|
||||||
|
# self.source_folder = None
|
||||||
|
self.source_imgs = None
|
||||||
|
|
||||||
for i,(img,info) in enumerate(zip(orig_images, orig_infotexts)):
|
for i,(img,info) in enumerate(zip(orig_images, orig_infotexts)):
|
||||||
if check_process_halt():
|
if check_process_halt():
|
||||||
postprocess_run = False
|
postprocess_run = False
|
||||||
break
|
break
|
||||||
if len(orig_images) > 1:
|
if len(orig_images) > 1:
|
||||||
logger.info("Swap in %s", i)
|
logger.status("Swap in %s", i)
|
||||||
result = swap_face(
|
result, output, swapped = swap_face(
|
||||||
self.source,
|
self.source,
|
||||||
img,
|
img,
|
||||||
source_faces_index=self.source_faces_index,
|
source_faces_index=self.source_faces_index,
|
||||||
faces_index=self.faces_index,
|
faces_index=self.faces_index,
|
||||||
model=self.model,
|
model=self.model,
|
||||||
upscale_options=self.upscale_options,
|
enhancement_options=self.enhancement_options,
|
||||||
gender_source=self.gender_source,
|
gender_source=self.gender_source,
|
||||||
gender_target=self.gender_target,
|
gender_target=self.gender_target,
|
||||||
|
source_hash_check=self.source_hash_check,
|
||||||
|
target_hash_check=self.target_hash_check,
|
||||||
|
device=self.device,
|
||||||
|
mask_face=self.mask_face,
|
||||||
|
select_source=self.select_source,
|
||||||
|
face_model = self.face_model,
|
||||||
|
source_folder = self.source_folder,
|
||||||
|
source_imgs = self.source_imgs,
|
||||||
|
random_image = self.random_image,
|
||||||
|
detection_options=self.detection_options,
|
||||||
)
|
)
|
||||||
if result is not None:
|
|
||||||
|
if self.select_source == 2 or (self.select_source == 0 and self.source_imgs is not None and self.source is None):
|
||||||
|
if len(result) > 0 and swapped > 0:
|
||||||
|
# result_images.extend(result)
|
||||||
|
if self.save_original:
|
||||||
|
result_images.extend(result)
|
||||||
|
else:
|
||||||
|
result_images = result
|
||||||
suffix = "-swapped"
|
suffix = "-swapped"
|
||||||
result_images.append(result)
|
for i,x in enumerate(result):
|
||||||
try:
|
try:
|
||||||
save_image(result, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png",info=info, p=p, suffix=suffix)
|
img_path = save_image(result[i], p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png", info=info, p=p, suffix=suffix)
|
||||||
except:
|
except:
|
||||||
logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)")
|
logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)")
|
||||||
else:
|
|
||||||
|
elif len(result) == 0:
|
||||||
logger.error("Cannot create a result image")
|
logger.error("Cannot create a result image")
|
||||||
|
|
||||||
|
else:
|
||||||
|
if result is not None and swapped > 0:
|
||||||
|
result_images.append(result)
|
||||||
|
suffix = "-swapped"
|
||||||
|
try:
|
||||||
|
img_path = save_image(result, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png", info=info, p=p, suffix=suffix)
|
||||||
|
except:
|
||||||
|
logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)")
|
||||||
|
elif result is None:
|
||||||
|
logger.error("Cannot create a result image")
|
||||||
|
|
||||||
|
# if len(output) != 0:
|
||||||
|
# split_fullfn = os.path.splitext(img_path[0])
|
||||||
|
# fullfn = split_fullfn[0] + ".txt"
|
||||||
|
# with open(fullfn, 'w', encoding="utf8") as f:
|
||||||
|
# f.writelines(output)
|
||||||
|
|
||||||
if shared.opts.return_grid and len(result_images) > 2 and postprocess_run:
|
if shared.opts.return_grid and len(result_images) > 2 and postprocess_run:
|
||||||
grid = make_grid(result_images)
|
grid = make_grid(result_images)
|
||||||
result_images.insert(0, grid)
|
result_images.insert(0, grid)
|
||||||
@ -325,13 +425,32 @@ class FaceSwapScript(scripts.Script):
|
|||||||
logger.error("Cannot save a grid - please, check SD WebUI Settings (Saving and Paths)")
|
logger.error("Cannot save a grid - please, check SD WebUI Settings (Saving and Paths)")
|
||||||
|
|
||||||
processed.images = result_images
|
processed.images = result_images
|
||||||
|
# processed.infotexts = result_info
|
||||||
|
|
||||||
|
elif self.select_source == 0 and self.source is not None and self.source_imgs is not None:
|
||||||
|
|
||||||
|
logger.debug("*** Check postprocess - after ELIF")
|
||||||
|
|
||||||
|
if self.result is not None:
|
||||||
|
orig_infotexts : List[str] = processed.infotexts[processed.index_of_first_image:]
|
||||||
|
processed.images = [self.result]
|
||||||
|
try:
|
||||||
|
img_path = save_image(self.result, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "png", info=orig_infotexts[0], p=p, suffix="")
|
||||||
|
except:
|
||||||
|
logger.error("Cannot save a result image - please, check SD WebUI Settings (Saving and Paths)")
|
||||||
|
else:
|
||||||
|
logger.error("Cannot create a result image")
|
||||||
|
|
||||||
|
|
||||||
def postprocess_batch(self, p, *args, **kwargs):
|
def postprocess_batch(self, p, *args, **kwargs):
|
||||||
if self.enable and not self.save_original:
|
if self.enable and not self.save_original:
|
||||||
|
logger.debug("*** Check postprocess_batch")
|
||||||
images = kwargs["images"]
|
images = kwargs["images"]
|
||||||
|
|
||||||
def postprocess_image(self, p, script_pp: scripts.PostprocessImageArgs, *args):
|
def postprocess_image(self, p, script_pp: scripts.PostprocessImageArgs, *args):
|
||||||
if self.enable and self.swap_in_generated and not self.save_original:
|
if self.enable and self.swap_in_generated and not self.save_original and ((self.select_source == 0 and self.source is not None) or self.select_source == 1):
|
||||||
|
|
||||||
|
logger.debug("*** Check postprocess_image")
|
||||||
|
|
||||||
current_job_number = shared.state.job_no + 1
|
current_job_number = shared.state.job_no + 1
|
||||||
job_count = shared.state.job_count
|
job_count = shared.state.job_count
|
||||||
@ -340,23 +459,281 @@ class FaceSwapScript(scripts.Script):
|
|||||||
if check_process_halt():
|
if check_process_halt():
|
||||||
return
|
return
|
||||||
|
|
||||||
if self.source is not None:
|
# if (self.source is not None and self.select_source == 0) or ((self.face_model is not None and self.face_model != "None") and self.select_source == 1):
|
||||||
logger.info("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
||||||
image: Image.Image = script_pp.image
|
image: Image.Image = script_pp.image
|
||||||
result = swap_face(
|
result, output, swapped = swap_face(
|
||||||
self.source,
|
self.source,
|
||||||
image,
|
image,
|
||||||
source_faces_index=self.source_faces_index,
|
source_faces_index=self.source_faces_index,
|
||||||
faces_index=self.faces_index,
|
faces_index=self.faces_index,
|
||||||
model=self.model,
|
model=self.model,
|
||||||
upscale_options=self.upscale_options,
|
enhancement_options=self.enhancement_options,
|
||||||
gender_source=self.gender_source,
|
gender_source=self.gender_source,
|
||||||
gender_target=self.gender_target,
|
gender_target=self.gender_target,
|
||||||
|
source_hash_check=self.source_hash_check,
|
||||||
|
target_hash_check=self.target_hash_check,
|
||||||
|
device=self.device,
|
||||||
|
mask_face=self.mask_face,
|
||||||
|
select_source=self.select_source,
|
||||||
|
face_model = self.face_model,
|
||||||
|
source_folder = None,
|
||||||
|
source_imgs = None,
|
||||||
|
random_image = False,
|
||||||
|
detection_options=self.detection_options,
|
||||||
)
|
)
|
||||||
|
self.result = result
|
||||||
try:
|
try:
|
||||||
pp = scripts_postprocessing.PostprocessedImage(result)
|
pp = scripts_postprocessing.PostprocessedImage(result)
|
||||||
pp.info = {}
|
pp.info = {}
|
||||||
p.extra_generation_params.update(pp.info)
|
p.extra_generation_params.update(pp.info)
|
||||||
script_pp.image = pp.image
|
script_pp.image = pp.image
|
||||||
|
|
||||||
|
# if len(output) != 0:
|
||||||
|
# result_path = get_image_path(script_pp.image, p.outpath_samples, "", p.all_seeds[0], p.all_prompts[0], "txt", p=p, suffix="-swapped")
|
||||||
|
# if len(output) != 0:
|
||||||
|
# with open(result_path, 'w', encoding="utf8") as f:
|
||||||
|
# f.writelines(output)
|
||||||
except:
|
except:
|
||||||
logger.error("Cannot create a result image")
|
logger.error("Cannot create a result image")
|
||||||
|
|
||||||
|
|
||||||
|
class FaceSwapScriptExtras(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = 'ReActor'
|
||||||
|
order = 20000
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with (
|
||||||
|
gr.Accordion(f"{app_title}", open=False) if check_old_webui() else InputAccordion(False, label=f"{app_title}") as enable
|
||||||
|
):
|
||||||
|
# with ui_components.InputAccordion(False, label=f"{app_title}") as enable:
|
||||||
|
# with gr.Accordion(f"{app_title}", open=False):
|
||||||
|
|
||||||
|
# SD.Next or A1111 1.52:
|
||||||
|
if get_SDNEXT() or check_old_webui():
|
||||||
|
enable = gr.Checkbox(False, label="Enable")
|
||||||
|
|
||||||
|
# enable = gr.Checkbox(False, label="Enable", info=f"The Fast and Simple FaceSwap Extension - {version_flag}")
|
||||||
|
gr.Markdown(f"<span style='display:block;font-size:0.75em;margin-bottom:-24px;'>The Fast and Simple FaceSwap Extension - {version_flag}</span>")
|
||||||
|
|
||||||
|
# TAB MAIN
|
||||||
|
msgs: dict = {
|
||||||
|
"extra_multiple_source": "",
|
||||||
|
}
|
||||||
|
img, imgs, selected_tab, 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, random_image = ui_main.show(is_img2img=False, show_br=False, **msgs)
|
||||||
|
|
||||||
|
# TAB DETECTION
|
||||||
|
det_thresh, det_maxnum = ui_detection.show()
|
||||||
|
|
||||||
|
# TAB UPSCALE
|
||||||
|
restore_first, upscaler_name, upscaler_scale, upscaler_visibility, upscale_force = ui_upscale.show(show_br=False)
|
||||||
|
|
||||||
|
# TAB TOOLS
|
||||||
|
ui_tools.show()
|
||||||
|
|
||||||
|
# TAB SETTINGS
|
||||||
|
model, device, console_logging_level, source_hash_check, target_hash_check = ui_settings.show(hash_check_block=False)
|
||||||
|
|
||||||
|
gr.Markdown("<span style='display:block;text-align:right;padding-right:3px;font-size:0.666em;margin: -9px 0'>by <a style='font-weight:normal' href='https://github.com/Gourieff' target='_blank'>Eugene Gourieff</a></span>")
|
||||||
|
|
||||||
|
args = {
|
||||||
|
'img': img,
|
||||||
|
'enable': enable,
|
||||||
|
'source_faces_index': source_faces_index,
|
||||||
|
'faces_index': faces_index,
|
||||||
|
'model': model,
|
||||||
|
'face_restorer_name': face_restorer_name,
|
||||||
|
'face_restorer_visibility': face_restorer_visibility,
|
||||||
|
'restore_first': restore_first,
|
||||||
|
'upscaler_name': upscaler_name,
|
||||||
|
'upscaler_scale': upscaler_scale,
|
||||||
|
'upscaler_visibility': upscaler_visibility,
|
||||||
|
'console_logging_level': console_logging_level,
|
||||||
|
'gender_source': gender_source,
|
||||||
|
'gender_target': gender_target,
|
||||||
|
'codeformer_weight': codeformer_weight,
|
||||||
|
'device': device,
|
||||||
|
'mask_face': mask_face,
|
||||||
|
'select_source': select_source,
|
||||||
|
'face_model': face_model,
|
||||||
|
'source_folder': source_folder,
|
||||||
|
'imgs': imgs,
|
||||||
|
'random_image': random_image,
|
||||||
|
'upscale_force': upscale_force,
|
||||||
|
'det_thresh': det_thresh,
|
||||||
|
'det_maxnum': det_maxnum,
|
||||||
|
'selected_tab': selected_tab,
|
||||||
|
}
|
||||||
|
return args
|
||||||
|
|
||||||
|
@property
|
||||||
|
def upscaler(self) -> UpscalerData:
|
||||||
|
for upscaler in shared.sd_upscalers:
|
||||||
|
if upscaler.name == self.upscaler_name:
|
||||||
|
return upscaler
|
||||||
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def face_restorer(self) -> FaceRestoration:
|
||||||
|
for face_restorer in shared.face_restorers:
|
||||||
|
if face_restorer.name() == self.face_restorer_name:
|
||||||
|
return face_restorer
|
||||||
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def enhancement_options(self) -> EnhancementOptions:
|
||||||
|
return EnhancementOptions(
|
||||||
|
do_restore_first=self.restore_first,
|
||||||
|
scale=self.upscaler_scale,
|
||||||
|
upscaler=self.upscaler,
|
||||||
|
face_restorer=self.face_restorer,
|
||||||
|
upscale_visibility=self.upscaler_visibility,
|
||||||
|
restorer_visibility=self.face_restorer_visibility,
|
||||||
|
codeformer_weight=self.codeformer_weight,
|
||||||
|
upscale_force=self.upscale_force,
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def detection_options(self) -> DetectionOptions:
|
||||||
|
return DetectionOptions(
|
||||||
|
det_thresh=self.det_thresh,
|
||||||
|
det_maxnum=self.det_maxnum
|
||||||
|
)
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, **args):
|
||||||
|
if args['enable']:
|
||||||
|
reset_messaged()
|
||||||
|
if check_process_halt():
|
||||||
|
return
|
||||||
|
|
||||||
|
global SWAPPER_MODELS_PATH
|
||||||
|
if args['selected_tab'] == "tab_single":
|
||||||
|
self.source = args['img']
|
||||||
|
else:
|
||||||
|
self.source = None
|
||||||
|
self.face_restorer_name = args['face_restorer_name']
|
||||||
|
self.upscaler_scale = args['upscaler_scale']
|
||||||
|
self.upscaler_visibility = args['upscaler_visibility']
|
||||||
|
self.face_restorer_visibility = args['face_restorer_visibility']
|
||||||
|
self.restore_first = args['restore_first']
|
||||||
|
self.upscaler_name = args['upscaler_name']
|
||||||
|
self.model = os.path.join(SWAPPER_MODELS_PATH, args['model'])
|
||||||
|
self.console_logging_level = args['console_logging_level']
|
||||||
|
self.gender_source = args['gender_source']
|
||||||
|
self.gender_target = args['gender_target']
|
||||||
|
self.codeformer_weight = args['codeformer_weight']
|
||||||
|
self.device = args['device']
|
||||||
|
self.mask_face = args['mask_face']
|
||||||
|
self.select_source = args['select_source']
|
||||||
|
self.face_model = args['face_model']
|
||||||
|
self.source_folder = args['source_folder']
|
||||||
|
if args['selected_tab'] == "tab_single":
|
||||||
|
self.source_imgs = None
|
||||||
|
else:
|
||||||
|
self.source_imgs = args['imgs']
|
||||||
|
self.random_image = args['random_image']
|
||||||
|
self.upscale_force = args['upscale_force']
|
||||||
|
self.det_thresh = args['det_thresh']
|
||||||
|
self.det_maxnum = args['det_maxnum']
|
||||||
|
if self.gender_source is None or self.gender_source == "No":
|
||||||
|
self.gender_source = 0
|
||||||
|
if self.gender_target is None or self.gender_target == "No":
|
||||||
|
self.gender_target = 0
|
||||||
|
self.source_faces_index = [
|
||||||
|
int(x) for x in args['source_faces_index'].strip(",").split(",") if x.isnumeric()
|
||||||
|
]
|
||||||
|
self.faces_index = [
|
||||||
|
int(x) for x in args['faces_index'].strip(",").split(",") if x.isnumeric()
|
||||||
|
]
|
||||||
|
if len(self.source_faces_index) == 0:
|
||||||
|
self.source_faces_index = [0]
|
||||||
|
if len(self.faces_index) == 0:
|
||||||
|
self.faces_index = [0]
|
||||||
|
if self.mask_face is None:
|
||||||
|
self.mask_face = False
|
||||||
|
if self.random_image is None:
|
||||||
|
self.random_image = False
|
||||||
|
if self.upscale_force is None:
|
||||||
|
self.upscale_force = False
|
||||||
|
|
||||||
|
current_job_number = shared.state.job_no + 1
|
||||||
|
job_count = shared.state.job_count
|
||||||
|
if current_job_number == job_count:
|
||||||
|
reset_messaged()
|
||||||
|
|
||||||
|
set_Device(self.device)
|
||||||
|
|
||||||
|
logger.debug("We're here: process() 1")
|
||||||
|
|
||||||
|
if (self.source is not None and self.select_source == 0) or ((self.face_model is not None and self.face_model != "None") and self.select_source == 1) or ((self.source_folder is not None and self.source_folder != "") and self.select_source == 2) or ((self.source_imgs is not None and self.source is None) and self.select_source == 0):
|
||||||
|
|
||||||
|
logger.debug("We're here: process() 2")
|
||||||
|
|
||||||
|
if self.source is not None and self.select_source == 0:
|
||||||
|
self.source_imgs = None
|
||||||
|
|
||||||
|
apply_logging_patch(self.console_logging_level)
|
||||||
|
logger.status("Working: source face index %s, target face index %s", self.source_faces_index, self.faces_index)
|
||||||
|
# if self.select_source != 2:
|
||||||
|
image: Image.Image = pp.image
|
||||||
|
|
||||||
|
# Extract alpha channel
|
||||||
|
logger.debug(f"image = {image}")
|
||||||
|
if image.mode == 'RGBA':
|
||||||
|
_, _, _, alpha = image.split()
|
||||||
|
else:
|
||||||
|
alpha = None
|
||||||
|
logger.debug(f"alpha = {alpha}")
|
||||||
|
|
||||||
|
result, output, swapped = swap_face(
|
||||||
|
self.source,
|
||||||
|
image,
|
||||||
|
source_faces_index=self.source_faces_index,
|
||||||
|
faces_index=self.faces_index,
|
||||||
|
model=self.model,
|
||||||
|
enhancement_options=self.enhancement_options,
|
||||||
|
gender_source=self.gender_source,
|
||||||
|
gender_target=self.gender_target,
|
||||||
|
source_hash_check=True,
|
||||||
|
target_hash_check=True,
|
||||||
|
device=self.device,
|
||||||
|
mask_face=self.mask_face,
|
||||||
|
select_source=self.select_source,
|
||||||
|
face_model=self.face_model,
|
||||||
|
source_folder=self.source_folder,
|
||||||
|
source_imgs=self.source_imgs,
|
||||||
|
random_image=self.random_image,
|
||||||
|
detection_options=self.detection_options,
|
||||||
|
)
|
||||||
|
if self.select_source == 2 or (self.select_source == 0 and self.source_imgs is not None and self.source is None):
|
||||||
|
if len(result) > 0 and swapped > 0:
|
||||||
|
image = result[0]
|
||||||
|
if len(result) > 1:
|
||||||
|
if hasattr(pp, 'extra_images'):
|
||||||
|
image = result[0]
|
||||||
|
pp.extra_images.extend(result[1:])
|
||||||
|
else:
|
||||||
|
grid = make_grid(result)
|
||||||
|
result.insert(0, grid)
|
||||||
|
image = grid
|
||||||
|
pp.info["ReActor"] = True
|
||||||
|
pp.image = image
|
||||||
|
logger.status("---Done!---")
|
||||||
|
else:
|
||||||
|
logger.error("Cannot create a result image")
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
pp.info["ReActor"] = True
|
||||||
|
|
||||||
|
if alpha is not None:
|
||||||
|
logger.debug(f"result = {result}")
|
||||||
|
result = result.convert("RGBA")
|
||||||
|
result.putalpha(alpha)
|
||||||
|
logger.debug(f"result_alpha = {result}")
|
||||||
|
|
||||||
|
pp.image = result
|
||||||
|
logger.status("---Done!---")
|
||||||
|
except Exception:
|
||||||
|
logger.error("Cannot create a result image")
|
||||||
|
else:
|
||||||
|
logger.error("Please provide a source face")
|
||||||
|
|||||||
@ -1 +1,42 @@
|
|||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
try:
|
||||||
|
from modules.paths_internal import models_path
|
||||||
|
except:
|
||||||
|
try:
|
||||||
|
from modules.paths import models_path
|
||||||
|
except:
|
||||||
|
models_path = os.path.abspath("models")
|
||||||
|
|
||||||
IS_RUN: bool = False
|
IS_RUN: bool = False
|
||||||
|
BASE_PATH = os.path.join(Path(__file__).parents[1])
|
||||||
|
DEVICE_LIST: list = ["CPU", "CUDA"]
|
||||||
|
|
||||||
|
MODELS_PATH = models_path
|
||||||
|
SWAPPER_MODELS_PATH = os.path.join(MODELS_PATH, "insightface")
|
||||||
|
REACTOR_MODELS_PATH = os.path.join(MODELS_PATH, "reactor")
|
||||||
|
FACE_MODELS_PATH = os.path.join(REACTOR_MODELS_PATH, "faces")
|
||||||
|
|
||||||
|
IS_SDNEXT = False
|
||||||
|
|
||||||
|
if not os.path.exists(REACTOR_MODELS_PATH):
|
||||||
|
os.makedirs(REACTOR_MODELS_PATH)
|
||||||
|
if not os.path.exists(FACE_MODELS_PATH):
|
||||||
|
os.makedirs(FACE_MODELS_PATH)
|
||||||
|
|
||||||
|
def updateDevice():
|
||||||
|
try:
|
||||||
|
LAST_DEVICE_PATH = os.path.join(BASE_PATH, "last_device.txt")
|
||||||
|
with open(LAST_DEVICE_PATH) as f:
|
||||||
|
device = f.readline().strip()
|
||||||
|
if device not in DEVICE_LIST:
|
||||||
|
print(f"Error: Device {device} is not in DEVICE_LIST")
|
||||||
|
device = DEVICE_LIST[0]
|
||||||
|
print(f"Execution Provider has been set to {device}")
|
||||||
|
except Exception as e:
|
||||||
|
device = DEVICE_LIST[0]
|
||||||
|
print(f"Error: {e}\nExecution Provider has been set to {device}")
|
||||||
|
return device
|
||||||
|
|
||||||
|
DEVICE = updateDevice()
|
||||||
|
|||||||
@ -1,7 +1,45 @@
|
|||||||
|
import os, glob, random
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
from math import isqrt, ceil
|
from math import isqrt, ceil
|
||||||
from typing import List
|
from typing import List
|
||||||
|
import logging
|
||||||
|
import hashlib
|
||||||
|
import torch
|
||||||
|
from safetensors.torch import save_file, safe_open
|
||||||
|
from insightface.app.common import Face
|
||||||
|
|
||||||
|
from modules.images import FilenameGenerator, get_next_sequence_number
|
||||||
|
from modules import shared, script_callbacks
|
||||||
|
from scripts.reactor_globals import DEVICE, BASE_PATH, FACE_MODELS_PATH, IS_SDNEXT
|
||||||
|
|
||||||
|
try:
|
||||||
|
from modules.paths_internal import models_path
|
||||||
|
except:
|
||||||
|
try:
|
||||||
|
from modules.paths import models_path
|
||||||
|
except:
|
||||||
|
model_path = os.path.abspath("models")
|
||||||
|
|
||||||
|
MODELS_PATH = None
|
||||||
|
|
||||||
|
def set_Device(value):
|
||||||
|
global DEVICE
|
||||||
|
DEVICE = value
|
||||||
|
with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
|
||||||
|
txt.write(DEVICE)
|
||||||
|
|
||||||
|
def get_Device():
|
||||||
|
global DEVICE
|
||||||
|
return DEVICE
|
||||||
|
|
||||||
|
def set_SDNEXT():
|
||||||
|
global IS_SDNEXT
|
||||||
|
IS_SDNEXT = True
|
||||||
|
|
||||||
|
def get_SDNEXT():
|
||||||
|
global IS_SDNEXT
|
||||||
|
return IS_SDNEXT
|
||||||
|
|
||||||
def make_grid(image_list: List):
|
def make_grid(image_list: List):
|
||||||
|
|
||||||
@ -43,3 +81,158 @@ def make_grid(image_list: List):
|
|||||||
|
|
||||||
# Return None if there are no images or only one image in the image_list
|
# Return None if there are no images or only one image in the image_list
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def get_image_path(image, path, basename, seed=None, prompt=None, extension='png', p=None, suffix=""):
|
||||||
|
|
||||||
|
namegen = FilenameGenerator(p, seed, prompt, image)
|
||||||
|
|
||||||
|
save_to_dirs = shared.opts.save_to_dirs
|
||||||
|
|
||||||
|
if save_to_dirs:
|
||||||
|
dirname = namegen.apply(shared.opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
|
||||||
|
path = os.path.join(path, dirname)
|
||||||
|
|
||||||
|
os.makedirs(path, exist_ok=True)
|
||||||
|
|
||||||
|
if seed is None:
|
||||||
|
file_decoration = ""
|
||||||
|
elif shared.opts.save_to_dirs:
|
||||||
|
file_decoration = shared.opts.samples_filename_pattern or "[seed]"
|
||||||
|
else:
|
||||||
|
file_decoration = shared.opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
|
||||||
|
|
||||||
|
file_decoration = namegen.apply(file_decoration) + suffix
|
||||||
|
|
||||||
|
add_number = shared.opts.save_images_add_number or file_decoration == ''
|
||||||
|
|
||||||
|
if file_decoration != "" and add_number:
|
||||||
|
file_decoration = f"-{file_decoration}"
|
||||||
|
|
||||||
|
if add_number:
|
||||||
|
basecount = get_next_sequence_number(path, basename)
|
||||||
|
fullfn = None
|
||||||
|
for i in range(500):
|
||||||
|
fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
|
||||||
|
fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
|
||||||
|
if not os.path.exists(fullfn):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
fullfn = os.path.join(path, f"{file_decoration}.{extension}")
|
||||||
|
|
||||||
|
pnginfo = {}
|
||||||
|
|
||||||
|
params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
|
||||||
|
# script_callbacks.before_image_saved_callback(params)
|
||||||
|
|
||||||
|
fullfn = params.filename
|
||||||
|
|
||||||
|
fullfn_without_extension, extension = os.path.splitext(params.filename)
|
||||||
|
if hasattr(os, 'statvfs'):
|
||||||
|
max_name_len = os.statvfs(path).f_namemax
|
||||||
|
fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
|
||||||
|
params.filename = fullfn_without_extension + extension
|
||||||
|
fullfn = params.filename
|
||||||
|
|
||||||
|
return fullfn
|
||||||
|
|
||||||
|
def addLoggingLevel(levelName, levelNum, methodName=None):
|
||||||
|
if not methodName:
|
||||||
|
methodName = levelName.lower()
|
||||||
|
|
||||||
|
def logForLevel(self, message, *args, **kwargs):
|
||||||
|
if self.isEnabledFor(levelNum):
|
||||||
|
self._log(levelNum, message, args, **kwargs)
|
||||||
|
|
||||||
|
def logToRoot(message, *args, **kwargs):
|
||||||
|
logging.log(levelNum, message, *args, **kwargs)
|
||||||
|
|
||||||
|
logging.addLevelName(levelNum, levelName)
|
||||||
|
setattr(logging, levelName, levelNum)
|
||||||
|
setattr(logging.getLoggerClass(), methodName, logForLevel)
|
||||||
|
setattr(logging, methodName, logToRoot)
|
||||||
|
|
||||||
|
def get_image_md5hash(image: Image.Image):
|
||||||
|
md5hash = hashlib.md5(image.tobytes())
|
||||||
|
return md5hash.hexdigest()
|
||||||
|
|
||||||
|
def save_face_model(face: Face, filename: str) -> None:
|
||||||
|
try:
|
||||||
|
tensors = {
|
||||||
|
"bbox": torch.tensor(face["bbox"]),
|
||||||
|
"kps": torch.tensor(face["kps"]),
|
||||||
|
"det_score": torch.tensor(face["det_score"]),
|
||||||
|
"landmark_3d_68": torch.tensor(face["landmark_3d_68"]),
|
||||||
|
"pose": torch.tensor(face["pose"]),
|
||||||
|
"landmark_2d_106": torch.tensor(face["landmark_2d_106"]),
|
||||||
|
"embedding": torch.tensor(face["embedding"]),
|
||||||
|
"gender": torch.tensor(face["gender"]),
|
||||||
|
"age": torch.tensor(face["age"]),
|
||||||
|
}
|
||||||
|
save_file(tensors, filename)
|
||||||
|
# print(f"Face model has been saved to '{filename}'")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error: {e}")
|
||||||
|
|
||||||
|
def get_models():
|
||||||
|
global MODELS_PATH
|
||||||
|
models_path_init = os.path.join(models_path, "insightface/*")
|
||||||
|
models = glob.glob(models_path_init)
|
||||||
|
models = [x for x in models if x.endswith(".onnx") or x.endswith(".pth")]
|
||||||
|
models_names = []
|
||||||
|
for model in models:
|
||||||
|
model_path = os.path.split(model)
|
||||||
|
if MODELS_PATH is None:
|
||||||
|
MODELS_PATH = model_path[0]
|
||||||
|
model_name = model_path[1]
|
||||||
|
models_names.append(model_name)
|
||||||
|
return models_names
|
||||||
|
|
||||||
|
def load_face_model(filename: str):
|
||||||
|
face = {}
|
||||||
|
model_path = os.path.join(FACE_MODELS_PATH, filename)
|
||||||
|
with safe_open(model_path, framework="pt") as f:
|
||||||
|
for k in f.keys():
|
||||||
|
face[k] = f.get_tensor(k).numpy()
|
||||||
|
return Face(face)
|
||||||
|
|
||||||
|
def get_facemodels():
|
||||||
|
models_path = os.path.join(FACE_MODELS_PATH, "*")
|
||||||
|
models = glob.glob(models_path)
|
||||||
|
models = [x for x in models if x.endswith(".safetensors")]
|
||||||
|
return models
|
||||||
|
|
||||||
|
def get_model_names(get_models):
|
||||||
|
models = get_models()
|
||||||
|
names = []
|
||||||
|
for x in models:
|
||||||
|
names.append(os.path.basename(x))
|
||||||
|
# Sort ignoring case during sort but retain in output
|
||||||
|
names.sort(key=str.lower)
|
||||||
|
names.insert(0, "None")
|
||||||
|
return names
|
||||||
|
|
||||||
|
def get_images_from_folder(path: str):
|
||||||
|
files_path = os.path.join(path, "*")
|
||||||
|
files = glob.glob(files_path)
|
||||||
|
images = []
|
||||||
|
images_names = []
|
||||||
|
for x in files:
|
||||||
|
if x.endswith(('jpg', 'png', 'jpeg', 'webp', 'bmp')):
|
||||||
|
images.append(Image.open(x))
|
||||||
|
images_names.append(os.path.basename(x))
|
||||||
|
return images,images_names
|
||||||
|
# return [Image.open(x) for x in images if x.endswith(('jpg', 'png', 'jpeg', 'webp', 'bmp'))],[os.path.basename(x) for x in images if x.endswith(('jpg', 'png', 'jpeg', 'webp', 'bmp'))]
|
||||||
|
|
||||||
|
def get_random_image_from_folder(path: str):
|
||||||
|
images,names = get_images_from_folder(path)
|
||||||
|
random_image_index = random.randint(0, len(images) - 1)
|
||||||
|
return [images[random_image_index]],[names[random_image_index]]
|
||||||
|
|
||||||
|
def get_images_from_list(imgs: List):
|
||||||
|
images = []
|
||||||
|
images_names = []
|
||||||
|
for x in imgs:
|
||||||
|
images.append(Image.open(os.path.abspath(x.name)))
|
||||||
|
images_names.append(os.path.basename(x.name))
|
||||||
|
return images,images_names
|
||||||
|
# return [Image.open(os.path.abspath(x.name)) for x in imgs],[os.path.basename(x.name) for x in imgs]
|
||||||
|
|||||||
86
scripts/reactor_inferencers/bisenet_mask_generator.py
Normal file
86
scripts/reactor_inferencers/bisenet_mask_generator.py
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
from typing import List, Tuple
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import modules.shared as shared
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from facexlib.parsing import init_parsing_model
|
||||||
|
from facexlib.utils.misc import img2tensor
|
||||||
|
from torchvision.transforms.functional import normalize
|
||||||
|
from scripts.reactor_inferencers.mask_generator import MaskGenerator
|
||||||
|
|
||||||
|
class BiSeNetMaskGenerator(MaskGenerator):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.mask_model = init_parsing_model(device=shared.device)
|
||||||
|
|
||||||
|
def name(self):
|
||||||
|
return "BiSeNet"
|
||||||
|
|
||||||
|
def generate_mask(
|
||||||
|
self,
|
||||||
|
face_image: np.ndarray,
|
||||||
|
face_area_on_image: Tuple[int, int, int, int],
|
||||||
|
affected_areas: List[str],
|
||||||
|
mask_size: int,
|
||||||
|
use_minimal_area: bool,
|
||||||
|
fallback_ratio: float = 0.25,
|
||||||
|
**kwargs,
|
||||||
|
) -> np.ndarray:
|
||||||
|
# original_face_image = face_image
|
||||||
|
face_image = face_image.copy()
|
||||||
|
face_image = face_image[:, :, ::-1]
|
||||||
|
|
||||||
|
if use_minimal_area:
|
||||||
|
face_image = MaskGenerator.mask_non_face_areas(face_image, face_area_on_image)
|
||||||
|
|
||||||
|
h, w, _ = face_image.shape
|
||||||
|
|
||||||
|
if w != 512 or h != 512:
|
||||||
|
rw = (int(w * (512 / w)) // 8) * 8
|
||||||
|
rh = (int(h * (512 / h)) // 8) * 8
|
||||||
|
face_image = cv2.resize(face_image, dsize=(rw, rh))
|
||||||
|
|
||||||
|
face_tensor = img2tensor(face_image.astype("float32") / 255.0, float32=True)
|
||||||
|
normalize(face_tensor, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
|
||||||
|
face_tensor = torch.unsqueeze(face_tensor, 0).to(shared.device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
face = self.mask_model(face_tensor)[0]
|
||||||
|
face = face.squeeze(0).cpu().numpy().argmax(0)
|
||||||
|
face = face.copy().astype(np.uint8)
|
||||||
|
|
||||||
|
mask = self.__to_mask(face, affected_areas)
|
||||||
|
|
||||||
|
if mask_size > 0:
|
||||||
|
mask = cv2.dilate(mask, np.ones((5, 5), np.uint8), iterations=mask_size)
|
||||||
|
|
||||||
|
if w != 512 or h != 512:
|
||||||
|
mask = cv2.resize(mask, dsize=(w, h))
|
||||||
|
|
||||||
|
# """if MaskGenerator.calculate_mask_coverage(mask) < fallback_ratio:
|
||||||
|
# logger.info("Use fallback mask generator")
|
||||||
|
# mask = self.fallback_mask_generator.generate_mask(
|
||||||
|
# original_face_image, face_area_on_image, use_minimal_area=True
|
||||||
|
# )"""
|
||||||
|
|
||||||
|
return mask
|
||||||
|
|
||||||
|
def __to_mask(self, face: np.ndarray, affected_areas: List[str]) -> np.ndarray:
|
||||||
|
keep_face = "Face" in affected_areas
|
||||||
|
keep_neck = "Neck" in affected_areas
|
||||||
|
keep_hair = "Hair" in affected_areas
|
||||||
|
keep_hat = "Hat" in affected_areas
|
||||||
|
|
||||||
|
mask = np.zeros((face.shape[0], face.shape[1], 3), dtype=np.uint8)
|
||||||
|
num_of_class = np.max(face)
|
||||||
|
for i in range(1, num_of_class + 1):
|
||||||
|
index = np.where(face == i)
|
||||||
|
if i < 14 and keep_face:
|
||||||
|
mask[index[0], index[1], :] = [255, 255, 255]
|
||||||
|
elif i == 14 and keep_neck:
|
||||||
|
mask[index[0], index[1], :] = [255, 255, 255]
|
||||||
|
elif i == 17 and keep_hair:
|
||||||
|
mask[index[0], index[1], :] = [255, 255, 255]
|
||||||
|
elif i == 18 and keep_hat:
|
||||||
|
mask[index[0], index[1], :] = [255, 255, 255]
|
||||||
|
return mask
|
||||||
36
scripts/reactor_inferencers/mask_generator.py
Normal file
36
scripts/reactor_inferencers/mask_generator.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
class MaskGenerator(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
def name(self) -> str:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def generate_mask(
|
||||||
|
self,
|
||||||
|
face_image: np.ndarray,
|
||||||
|
face_area_on_image: Tuple[int, int, int, int],
|
||||||
|
**kwargs,
|
||||||
|
) -> np.ndarray:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def mask_non_face_areas(image: np.ndarray, face_area_on_image: Tuple[int, int, int, int]) -> np.ndarray:
|
||||||
|
left, top, right, bottom = face_area_on_image
|
||||||
|
image = image.copy()
|
||||||
|
image[:top, :] = 0
|
||||||
|
image[bottom:, :] = 0
|
||||||
|
image[:, :left] = 0
|
||||||
|
image[:, right:] = 0
|
||||||
|
return image
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def calculate_mask_coverage(mask: np.ndarray):
|
||||||
|
gray_mask = cv2.cvtColor(mask, cv2.COLOR_RGB2GRAY)
|
||||||
|
non_black_pixels = np.count_nonzero(gray_mask)
|
||||||
|
total_pixels = gray_mask.size
|
||||||
|
return non_black_pixels / total_pixels
|
||||||
@ -4,6 +4,7 @@ import sys
|
|||||||
|
|
||||||
from modules import shared
|
from modules import shared
|
||||||
from scripts.reactor_globals import IS_RUN
|
from scripts.reactor_globals import IS_RUN
|
||||||
|
from scripts.reactor_helpers import addLoggingLevel
|
||||||
|
|
||||||
|
|
||||||
class ColoredFormatter(logging.Formatter):
|
class ColoredFormatter(logging.Formatter):
|
||||||
@ -29,8 +30,8 @@ class ColoredFormatter(logging.Formatter):
|
|||||||
logger = logging.getLogger("ReActor")
|
logger = logging.getLogger("ReActor")
|
||||||
logger.propagate = False
|
logger.propagate = False
|
||||||
|
|
||||||
# Custom Level name
|
# Add Custom Level
|
||||||
logging.addLevelName(logging.INFO, "STATUS")
|
addLoggingLevel("STATUS", logging.INFO + 5)
|
||||||
|
|
||||||
# Add handler if we don't have one.
|
# Add handler if we don't have one.
|
||||||
if not logger.handlers:
|
if not logger.handlers:
|
||||||
|
|||||||
@ -6,51 +6,71 @@ from typing import List, Union
|
|||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
from scipy import stats
|
||||||
|
|
||||||
import insightface
|
import insightface
|
||||||
import onnxruntime
|
from insightface.app.common import Face
|
||||||
|
|
||||||
|
from scripts.reactor_globals import FACE_MODELS_PATH
|
||||||
|
from scripts.reactor_helpers import (
|
||||||
|
get_image_md5hash,
|
||||||
|
get_Device,
|
||||||
|
save_face_model,
|
||||||
|
load_face_model,
|
||||||
|
get_images_from_folder,
|
||||||
|
get_random_image_from_folder,
|
||||||
|
get_images_from_list,
|
||||||
|
set_SDNEXT
|
||||||
|
)
|
||||||
|
from scripts.console_log_patch import apply_logging_patch
|
||||||
|
|
||||||
from modules.face_restoration import FaceRestoration
|
from modules.face_restoration import FaceRestoration
|
||||||
|
try: # A1111
|
||||||
|
from modules import codeformer_model, gfpgan_model
|
||||||
|
except: # SD.Next
|
||||||
|
from modules.postprocess import codeformer_model, gfpgan_model
|
||||||
|
set_SDNEXT()
|
||||||
from modules.upscaler import UpscalerData
|
from modules.upscaler import UpscalerData
|
||||||
from modules.shared import state
|
from modules.shared import state
|
||||||
from modules.paths_internal import models_path
|
|
||||||
from scripts.reactor_logger import logger
|
from scripts.reactor_logger import logger
|
||||||
|
from reactor_modules.reactor_mask import apply_face_mask
|
||||||
|
|
||||||
|
try:
|
||||||
|
from modules.paths_internal import models_path
|
||||||
|
except:
|
||||||
|
try:
|
||||||
|
from modules.paths import models_path
|
||||||
|
except:
|
||||||
|
models_path = os.path.abspath("models")
|
||||||
|
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
np.warnings = warnings
|
np.warnings = warnings
|
||||||
np.warnings.filterwarnings('ignore')
|
np.warnings.filterwarnings('ignore')
|
||||||
|
|
||||||
providers = onnxruntime.get_available_providers()
|
|
||||||
|
DEVICE = get_Device()
|
||||||
|
if DEVICE == "CUDA":
|
||||||
|
PROVIDERS = ["CUDAExecutionProvider"]
|
||||||
|
else:
|
||||||
|
PROVIDERS = ["CPUExecutionProvider"]
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class UpscaleOptions:
|
class EnhancementOptions:
|
||||||
do_restore_first: bool = True
|
do_restore_first: bool = True
|
||||||
scale: int = 1
|
scale: int = 1
|
||||||
upscaler: UpscalerData = None
|
upscaler: UpscalerData = None
|
||||||
upscale_visibility: float = 0.5
|
upscale_visibility: float = 0.5
|
||||||
face_restorer: FaceRestoration = None
|
face_restorer: FaceRestoration = None
|
||||||
restorer_visibility: float = 0.5
|
restorer_visibility: float = 0.5
|
||||||
|
codeformer_weight: float = 0.5
|
||||||
|
upscale_force: bool = False
|
||||||
|
|
||||||
|
@dataclass
|
||||||
def cosine_distance(vector1: np.ndarray, vector2: np.ndarray) -> float:
|
class DetectionOptions:
|
||||||
vec1 = vector1.flatten()
|
det_thresh: float = 0.5
|
||||||
vec2 = vector2.flatten()
|
det_maxnum: int = 0
|
||||||
|
|
||||||
dot_product = np.dot(vec1, vec2)
|
|
||||||
norm1 = np.linalg.norm(vec1)
|
|
||||||
norm2 = np.linalg.norm(vec2)
|
|
||||||
|
|
||||||
cosine_distance = 1 - (dot_product / (norm1 * norm2))
|
|
||||||
return cosine_distance
|
|
||||||
|
|
||||||
|
|
||||||
def cosine_similarity(test_vec: np.ndarray, source_vecs: List[np.ndarray]) -> float:
|
|
||||||
cos_dist = sum(cosine_distance(test_vec, source_vec) for source_vec in source_vecs)
|
|
||||||
average_cos_dist = cos_dist / len(source_vecs)
|
|
||||||
return average_cos_dist
|
|
||||||
|
|
||||||
|
|
||||||
MESSAGED_STOPPED = False
|
MESSAGED_STOPPED = False
|
||||||
MESSAGED_SKIPPED = False
|
MESSAGED_SKIPPED = False
|
||||||
@ -66,28 +86,64 @@ def check_process_halt(msgforced: bool = False):
|
|||||||
global MESSAGED_STOPPED, MESSAGED_SKIPPED
|
global MESSAGED_STOPPED, MESSAGED_SKIPPED
|
||||||
if state.interrupted:
|
if state.interrupted:
|
||||||
if not MESSAGED_STOPPED or msgforced:
|
if not MESSAGED_STOPPED or msgforced:
|
||||||
logger.info("Stopped by User")
|
logger.status("Stopped by User")
|
||||||
MESSAGED_STOPPED = True
|
MESSAGED_STOPPED = True
|
||||||
return True
|
return True
|
||||||
if state.skipped:
|
if state.skipped:
|
||||||
if not MESSAGED_SKIPPED or msgforced:
|
if not MESSAGED_SKIPPED or msgforced:
|
||||||
logger.info("Skipped by User")
|
logger.status("Skipped by User")
|
||||||
MESSAGED_SKIPPED = True
|
MESSAGED_SKIPPED = True
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
FS_MODEL = None
|
FS_MODEL = None
|
||||||
CURRENT_FS_MODEL_PATH = None
|
|
||||||
|
|
||||||
ANALYSIS_MODEL = None
|
ANALYSIS_MODEL = None
|
||||||
|
MASK_MODEL = None
|
||||||
|
|
||||||
|
CURRENT_FS_MODEL_PATH = None
|
||||||
|
CURRENT_MASK_MODEL_PATH = None
|
||||||
|
|
||||||
|
SOURCE_FACES = None
|
||||||
|
SOURCE_IMAGE_HASH = None
|
||||||
|
TARGET_FACES = None
|
||||||
|
TARGET_IMAGE_HASH = None
|
||||||
|
SOURCE_FACES_LIST = []
|
||||||
|
SOURCE_IMAGE_LIST_HASH = []
|
||||||
|
|
||||||
|
def clear_faces():
|
||||||
|
global SOURCE_FACES, SOURCE_IMAGE_HASH
|
||||||
|
SOURCE_FACES = None
|
||||||
|
SOURCE_IMAGE_HASH = None
|
||||||
|
logger.status("Source Images Hash has been reset (for Single Source or Face Model)")
|
||||||
|
|
||||||
|
def clear_faces_list():
|
||||||
|
global SOURCE_FACES_LIST, SOURCE_IMAGE_LIST_HASH
|
||||||
|
SOURCE_FACES_LIST = []
|
||||||
|
SOURCE_IMAGE_LIST_HASH = []
|
||||||
|
logger.status("Source Images Hash has been reset (for Multiple or Folder Source)")
|
||||||
|
|
||||||
|
def clear_faces_target():
|
||||||
|
global TARGET_FACES, TARGET_IMAGE_HASH
|
||||||
|
TARGET_FACES = None
|
||||||
|
TARGET_IMAGE_HASH = None
|
||||||
|
logger.status("Target Images Hash has been reset")
|
||||||
|
|
||||||
|
def clear_faces_all():
|
||||||
|
global SOURCE_FACES, SOURCE_IMAGE_HASH, SOURCE_FACES_LIST, SOURCE_IMAGE_LIST_HASH, TARGET_FACES, TARGET_IMAGE_HASH
|
||||||
|
SOURCE_FACES = None
|
||||||
|
SOURCE_IMAGE_HASH = None
|
||||||
|
TARGET_FACES = None
|
||||||
|
TARGET_IMAGE_HASH = None
|
||||||
|
SOURCE_FACES_LIST = []
|
||||||
|
SOURCE_IMAGE_LIST_HASH = []
|
||||||
|
logger.status("All Images Hash has been reset")
|
||||||
|
|
||||||
def getAnalysisModel():
|
def getAnalysisModel():
|
||||||
global ANALYSIS_MODEL
|
global ANALYSIS_MODEL
|
||||||
if ANALYSIS_MODEL is None:
|
if ANALYSIS_MODEL is None:
|
||||||
ANALYSIS_MODEL = insightface.app.FaceAnalysis(
|
ANALYSIS_MODEL = insightface.app.FaceAnalysis(
|
||||||
name="buffalo_l", providers=providers, root=os.path.join(models_path, "insightface") # note: allowed_modules=['detection', 'genderage']
|
name="buffalo_l", providers=PROVIDERS, root=os.path.join(models_path, "insightface") # note: allowed_modules=['detection', 'genderage']
|
||||||
)
|
)
|
||||||
return ANALYSIS_MODEL
|
return ANALYSIS_MODEL
|
||||||
|
|
||||||
@ -97,124 +153,198 @@ def getFaceSwapModel(model_path: str):
|
|||||||
global CURRENT_FS_MODEL_PATH
|
global CURRENT_FS_MODEL_PATH
|
||||||
if CURRENT_FS_MODEL_PATH is None or CURRENT_FS_MODEL_PATH != model_path:
|
if CURRENT_FS_MODEL_PATH is None or CURRENT_FS_MODEL_PATH != model_path:
|
||||||
CURRENT_FS_MODEL_PATH = model_path
|
CURRENT_FS_MODEL_PATH = model_path
|
||||||
FS_MODEL = insightface.model_zoo.get_model(model_path, providers=providers)
|
FS_MODEL = insightface.model_zoo.get_model(model_path, providers=PROVIDERS)
|
||||||
|
|
||||||
return FS_MODEL
|
return FS_MODEL
|
||||||
|
|
||||||
|
|
||||||
def upscale_image(image: Image, upscale_options: UpscaleOptions):
|
def restore_face(image: Image, enhancement_options: EnhancementOptions):
|
||||||
result_image = image
|
result_image = image
|
||||||
|
|
||||||
if check_process_halt(msgforced=True):
|
if check_process_halt(msgforced=True):
|
||||||
return result_image
|
return result_image
|
||||||
|
|
||||||
if upscale_options.do_restore_first:
|
if enhancement_options.face_restorer is not None:
|
||||||
if upscale_options.face_restorer is not None:
|
|
||||||
original_image = result_image.copy()
|
original_image = result_image.copy()
|
||||||
logger.info("Restoring the face with %s", upscale_options.face_restorer.name())
|
|
||||||
numpy_image = np.array(result_image)
|
numpy_image = np.array(result_image)
|
||||||
numpy_image = upscale_options.face_restorer.restore(numpy_image)
|
if enhancement_options.face_restorer.name() == "CodeFormer":
|
||||||
|
logger.status("Restoring the face with %s (weight: %s)", enhancement_options.face_restorer.name(), enhancement_options.codeformer_weight)
|
||||||
|
numpy_image = codeformer_model.codeformer.restore(
|
||||||
|
numpy_image, w=enhancement_options.codeformer_weight
|
||||||
|
)
|
||||||
|
else: # GFPGAN:
|
||||||
|
logger.status("Restoring the face with %s", enhancement_options.face_restorer.name())
|
||||||
|
numpy_image = gfpgan_model.gfpgan_fix_faces(numpy_image)
|
||||||
|
# numpy_image = enhancement_options.face_restorer.restore(numpy_image)
|
||||||
restored_image = Image.fromarray(numpy_image)
|
restored_image = Image.fromarray(numpy_image)
|
||||||
result_image = Image.blend(
|
result_image = Image.blend(
|
||||||
original_image, restored_image, upscale_options.restorer_visibility
|
original_image, restored_image, enhancement_options.restorer_visibility
|
||||||
)
|
|
||||||
if upscale_options.upscaler is not None and upscale_options.upscaler.name != "None":
|
|
||||||
original_image = result_image.copy()
|
|
||||||
logger.info(
|
|
||||||
"Upscaling with %s scale = %s",
|
|
||||||
upscale_options.upscaler.name,
|
|
||||||
upscale_options.scale,
|
|
||||||
)
|
|
||||||
result_image = upscale_options.upscaler.scaler.upscale(
|
|
||||||
original_image, upscale_options.scale, upscale_options.upscaler.data_path
|
|
||||||
)
|
|
||||||
if upscale_options.scale == 1:
|
|
||||||
result_image = Image.blend(
|
|
||||||
original_image, result_image, upscale_options.upscale_visibility
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
if upscale_options.upscaler is not None and upscale_options.upscaler.name != "None":
|
|
||||||
original_image = result_image.copy()
|
|
||||||
logger.info(
|
|
||||||
"Upscaling with %s scale = %s",
|
|
||||||
upscale_options.upscaler.name,
|
|
||||||
upscale_options.scale,
|
|
||||||
)
|
|
||||||
result_image = upscale_options.upscaler.scaler.upscale(
|
|
||||||
image, upscale_options.scale, upscale_options.upscaler.data_path
|
|
||||||
)
|
|
||||||
if upscale_options.scale == 1:
|
|
||||||
result_image = Image.blend(
|
|
||||||
original_image, result_image, upscale_options.upscale_visibility
|
|
||||||
)
|
|
||||||
if upscale_options.face_restorer is not None:
|
|
||||||
original_image = result_image.copy()
|
|
||||||
logger.info("Restoring the face with %s", upscale_options.face_restorer.name())
|
|
||||||
numpy_image = np.array(result_image)
|
|
||||||
numpy_image = upscale_options.face_restorer.restore(numpy_image)
|
|
||||||
restored_image = Image.fromarray(numpy_image)
|
|
||||||
result_image = Image.blend(
|
|
||||||
original_image, restored_image, upscale_options.restorer_visibility
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return result_image
|
return result_image
|
||||||
|
|
||||||
|
def upscale_image(image: Image, enhancement_options: EnhancementOptions):
|
||||||
|
result_image = image
|
||||||
|
|
||||||
def get_face_gender(
|
if check_process_halt(msgforced=True):
|
||||||
face,
|
return result_image
|
||||||
face_index,
|
|
||||||
gender_condition,
|
if enhancement_options.upscaler is not None and enhancement_options.upscaler.name != "None":
|
||||||
operated: str
|
original_image = result_image.copy()
|
||||||
):
|
logger.status(
|
||||||
|
"Upscaling with %s scale = %s",
|
||||||
|
enhancement_options.upscaler.name,
|
||||||
|
enhancement_options.scale,
|
||||||
|
)
|
||||||
|
result_image = enhancement_options.upscaler.scaler.upscale(
|
||||||
|
original_image, enhancement_options.scale, enhancement_options.upscaler.data_path
|
||||||
|
)
|
||||||
|
if enhancement_options.scale == 1:
|
||||||
|
result_image = Image.blend(
|
||||||
|
original_image, result_image, enhancement_options.upscale_visibility
|
||||||
|
)
|
||||||
|
|
||||||
|
return result_image
|
||||||
|
|
||||||
|
def enhance_image(image: Image, enhancement_options: EnhancementOptions):
|
||||||
|
result_image = image
|
||||||
|
|
||||||
|
if check_process_halt(msgforced=True):
|
||||||
|
return result_image
|
||||||
|
|
||||||
|
if enhancement_options.do_restore_first:
|
||||||
|
|
||||||
|
result_image = restore_face(result_image, enhancement_options)
|
||||||
|
result_image = upscale_image(result_image, enhancement_options)
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
result_image = upscale_image(result_image, enhancement_options)
|
||||||
|
result_image = restore_face(result_image, enhancement_options)
|
||||||
|
|
||||||
|
return result_image
|
||||||
|
|
||||||
|
def enhance_image_and_mask(image: Image.Image, enhancement_options: EnhancementOptions,target_img_orig:Image.Image,entire_mask_image:Image.Image)->Image.Image:
|
||||||
|
result_image = image
|
||||||
|
|
||||||
|
if check_process_halt(msgforced=True):
|
||||||
|
return result_image
|
||||||
|
|
||||||
|
if enhancement_options.do_restore_first:
|
||||||
|
|
||||||
|
result_image = restore_face(result_image, enhancement_options)
|
||||||
|
result_image = Image.composite(result_image,target_img_orig,entire_mask_image)
|
||||||
|
result_image = upscale_image(result_image, enhancement_options)
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
result_image = upscale_image(result_image, enhancement_options)
|
||||||
|
entire_mask_image = Image.fromarray(cv2.resize(np.array(entire_mask_image),result_image.size, interpolation=cv2.INTER_AREA)).convert("L")
|
||||||
|
result_image = Image.composite(result_image,target_img_orig,entire_mask_image)
|
||||||
|
result_image = restore_face(result_image, enhancement_options)
|
||||||
|
|
||||||
|
return result_image
|
||||||
|
|
||||||
|
|
||||||
|
def get_gender(face, face_index):
|
||||||
gender = [
|
gender = [
|
||||||
x.sex
|
x.sex
|
||||||
for x in face
|
for x in face
|
||||||
]
|
]
|
||||||
gender.reverse()
|
gender.reverse()
|
||||||
|
try:
|
||||||
face_gender = gender[face_index]
|
face_gender = gender[face_index]
|
||||||
logger.info("%s Face %s: Detected Gender -%s-", operated, face_index, face_gender)
|
except:
|
||||||
|
logger.error("Gender Detection: No face with index = %s was found", face_index)
|
||||||
|
return "None"
|
||||||
|
return face_gender
|
||||||
|
|
||||||
|
def get_face_gender(
|
||||||
|
face,
|
||||||
|
face_index,
|
||||||
|
gender_condition,
|
||||||
|
operated: str,
|
||||||
|
gender_detected,
|
||||||
|
):
|
||||||
|
face_gender = gender_detected
|
||||||
|
if face_gender == "None":
|
||||||
|
return None, 0
|
||||||
|
logger.status("%s Face %s: Detected Gender -%s-", operated, face_index, face_gender)
|
||||||
if (gender_condition == 1 and face_gender == "F") or (gender_condition == 2 and face_gender == "M"):
|
if (gender_condition == 1 and face_gender == "F") or (gender_condition == 2 and face_gender == "M"):
|
||||||
logger.info("OK - Detected Gender matches Condition")
|
logger.status("OK - Detected Gender matches Condition")
|
||||||
try:
|
try:
|
||||||
return sorted(face, key=lambda x: x.bbox[0])[face_index], 0
|
return sorted(face, key=lambda x: x.bbox[0])[face_index], 0
|
||||||
except IndexError:
|
except IndexError:
|
||||||
return None, 0
|
return None, 0
|
||||||
else:
|
else:
|
||||||
logger.info("WRONG - Detected Gender doesn't match Condition")
|
logger.status("WRONG - Detected Gender doesn't match Condition")
|
||||||
return sorted(face, key=lambda x: x.bbox[0])[face_index], 1
|
return sorted(face, key=lambda x: x.bbox[0])[face_index], 1
|
||||||
|
|
||||||
|
def get_face_age(face, face_index):
|
||||||
|
age = [
|
||||||
|
x.age
|
||||||
|
for x in face
|
||||||
|
]
|
||||||
|
age.reverse()
|
||||||
|
try:
|
||||||
|
face_age = age[face_index]
|
||||||
|
except:
|
||||||
|
logger.error("Age Detection: No face with index = %s was found", face_index)
|
||||||
|
return "None"
|
||||||
|
return face_age
|
||||||
|
|
||||||
def reget_face_single(img_data, det_size, face_index):
|
def half_det_size(det_size):
|
||||||
det_size_half = (det_size[0] // 2, det_size[1] // 2)
|
logger.status("Trying to halve 'det_size' parameter")
|
||||||
return get_face_single(img_data, face_index=face_index, det_size=det_size_half)
|
return (det_size[0] // 2, det_size[1] // 2)
|
||||||
|
|
||||||
|
def analyze_faces(img_data: np.ndarray, det_size=(640, 640), det_thresh=0.5, det_maxnum=0):
|
||||||
def get_face_single(img_data: np.ndarray, face_index=0, det_size=(640, 640), gender_source=0, gender_target=0):
|
logger.info("Applied Execution Provider: %s", PROVIDERS[0])
|
||||||
face_analyser = copy.deepcopy(getAnalysisModel())
|
face_analyser = copy.deepcopy(getAnalysisModel())
|
||||||
face_analyser.prepare(ctx_id=0, det_size=det_size)
|
face_analyser.prepare(ctx_id=0, det_thresh=det_thresh, det_size=det_size)
|
||||||
face = face_analyser.get(img_data)
|
return face_analyser.get(img_data, max_num=det_maxnum)
|
||||||
|
|
||||||
|
def get_face_single(img_data: np.ndarray, face, face_index=0, det_size=(640, 640), gender_source=0, gender_target=0, det_thresh=0.5, det_maxnum=0):
|
||||||
|
|
||||||
buffalo_path = os.path.join(models_path, "insightface/models/buffalo_l.zip")
|
buffalo_path = os.path.join(models_path, "insightface/models/buffalo_l.zip")
|
||||||
if os.path.exists(buffalo_path):
|
if os.path.exists(buffalo_path):
|
||||||
os.remove(buffalo_path)
|
os.remove(buffalo_path)
|
||||||
|
|
||||||
|
face_age = "None"
|
||||||
|
try:
|
||||||
|
face_age = get_face_age(face, face_index)
|
||||||
|
except:
|
||||||
|
logger.error("Cannot detect any Age for Face index = %s", face_index)
|
||||||
|
|
||||||
|
face_gender = "None"
|
||||||
|
try:
|
||||||
|
face_gender = get_gender(face, face_index)
|
||||||
|
gender_detected = face_gender
|
||||||
|
face_gender = "Female" if face_gender == "F" else ("Male" if face_gender == "M" else "None")
|
||||||
|
except:
|
||||||
|
logger.error("Cannot detect any Gender for Face index = %s", face_index)
|
||||||
|
|
||||||
if gender_source != 0:
|
if gender_source != 0:
|
||||||
if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
|
if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
|
||||||
return reget_face_single(img_data, det_size, face_index)
|
det_size_half = half_det_size(det_size)
|
||||||
return get_face_gender(face,face_index,gender_source,"Source")
|
return get_face_single(img_data, analyze_faces(img_data, det_size_half, det_thresh, det_maxnum), face_index, det_size_half, gender_source, gender_target, det_thresh, det_maxnum)
|
||||||
|
faces, wrong_gender = get_face_gender(face,face_index,gender_source,"Source",gender_detected)
|
||||||
|
return faces, wrong_gender, face_age, face_gender
|
||||||
|
|
||||||
if gender_target != 0:
|
if gender_target != 0:
|
||||||
if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
|
if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
|
||||||
return reget_face_single(img_data, det_size, face_index)
|
det_size_half = half_det_size(det_size)
|
||||||
return get_face_gender(face,face_index,gender_target,"Target")
|
return get_face_single(img_data, analyze_faces(img_data, det_size_half, det_thresh, det_maxnum), face_index, det_size_half, gender_source, gender_target, det_thresh, det_maxnum)
|
||||||
|
faces, wrong_gender = get_face_gender(face,face_index,gender_target,"Target",gender_detected)
|
||||||
|
return faces, wrong_gender, face_age, face_gender
|
||||||
|
|
||||||
if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
|
if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
|
||||||
return reget_face_single(img_data, det_size, face_index)
|
det_size_half = half_det_size(det_size)
|
||||||
|
return get_face_single(img_data, analyze_faces(img_data, det_size_half, det_thresh, det_maxnum), face_index, det_size_half, gender_source, gender_target, det_thresh, det_maxnum)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
return sorted(face, key=lambda x: x.bbox[0])[face_index], 0
|
return sorted(face, key=lambda x: x.bbox[0])[face_index], 0, face_age, face_gender
|
||||||
except IndexError:
|
except IndexError:
|
||||||
return None, 0
|
return None, 0, face_age, face_gender
|
||||||
|
|
||||||
|
|
||||||
def swap_face(
|
def swap_face(
|
||||||
@ -223,14 +353,28 @@ def swap_face(
|
|||||||
model: Union[str, None] = None,
|
model: Union[str, None] = None,
|
||||||
source_faces_index: List[int] = [0],
|
source_faces_index: List[int] = [0],
|
||||||
faces_index: List[int] = [0],
|
faces_index: List[int] = [0],
|
||||||
upscale_options: Union[UpscaleOptions, None] = None,
|
enhancement_options: Union[EnhancementOptions, None] = None,
|
||||||
gender_source: int = 0,
|
gender_source: int = 0,
|
||||||
gender_target: int = 0,
|
gender_target: int = 0,
|
||||||
|
source_hash_check: bool = True,
|
||||||
|
target_hash_check: bool = False,
|
||||||
|
device: str = "CPU",
|
||||||
|
mask_face: bool = False,
|
||||||
|
select_source: int = 0,
|
||||||
|
face_model: str = "None",
|
||||||
|
source_folder: str = "",
|
||||||
|
source_imgs: Union[List, None] = None,
|
||||||
|
random_image: bool = False,
|
||||||
|
detection_options: Union[DetectionOptions, None] = None,
|
||||||
):
|
):
|
||||||
|
global SOURCE_FACES, SOURCE_IMAGE_HASH, TARGET_FACES, TARGET_IMAGE_HASH, PROVIDERS, SOURCE_FACES_LIST, SOURCE_IMAGE_LIST_HASH
|
||||||
|
|
||||||
result_image = target_img
|
result_image = target_img
|
||||||
|
|
||||||
|
PROVIDERS = ["CUDAExecutionProvider"] if device == "CUDA" else ["CPUExecutionProvider"]
|
||||||
|
|
||||||
if check_process_halt():
|
if check_process_halt():
|
||||||
return result_image
|
return result_image, [], 0
|
||||||
|
|
||||||
if model is not None:
|
if model is not None:
|
||||||
|
|
||||||
@ -247,55 +391,435 @@ def swap_face(
|
|||||||
|
|
||||||
source_img = Image.open(io.BytesIO(img_bytes))
|
source_img = Image.open(io.BytesIO(img_bytes))
|
||||||
|
|
||||||
source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
|
|
||||||
target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
|
target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
|
||||||
|
|
||||||
source_face, wrong_gender = get_face_single(source_img, face_index=source_faces_index[0], gender_source=gender_source)
|
target_img_orig = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
|
||||||
|
entire_mask_image = np.zeros_like(np.array(target_img))
|
||||||
|
|
||||||
|
output: List = []
|
||||||
|
output_info: str = ""
|
||||||
|
swapped = 0
|
||||||
|
|
||||||
|
# *****************
|
||||||
|
# SWAP from FOLDER or MULTIPLE images:
|
||||||
|
|
||||||
|
if (select_source == 0 and source_imgs is not None) or (select_source == 2 and (source_folder is not None and source_folder != "")):
|
||||||
|
|
||||||
|
result = []
|
||||||
|
|
||||||
|
if random_image and select_source == 2:
|
||||||
|
source_images,source_images_names = get_random_image_from_folder(source_folder)
|
||||||
|
logger.status(f"Processing with Random Image from the folder: {source_images_names[0]}")
|
||||||
|
else:
|
||||||
|
source_images,source_images_names = get_images_from_folder(source_folder) if select_source == 2 else get_images_from_list(source_imgs)
|
||||||
|
|
||||||
|
if len(source_images) > 0:
|
||||||
|
source_img_ff = []
|
||||||
|
source_faces_ff = []
|
||||||
|
for i, source_image in enumerate(source_images):
|
||||||
|
|
||||||
|
source_image = cv2.cvtColor(np.array(source_image), cv2.COLOR_RGB2BGR)
|
||||||
|
source_img_ff.append(source_image)
|
||||||
|
|
||||||
|
if source_hash_check:
|
||||||
|
|
||||||
|
source_image_md5hash = get_image_md5hash(source_image)
|
||||||
|
|
||||||
|
if len(SOURCE_IMAGE_LIST_HASH) == 0:
|
||||||
|
SOURCE_IMAGE_LIST_HASH = [source_image_md5hash]
|
||||||
|
source_image_same = False
|
||||||
|
elif len(SOURCE_IMAGE_LIST_HASH) == i:
|
||||||
|
SOURCE_IMAGE_LIST_HASH.append(source_image_md5hash)
|
||||||
|
source_image_same = False
|
||||||
|
else:
|
||||||
|
source_image_same = True if SOURCE_IMAGE_LIST_HASH[i] == source_image_md5hash else False
|
||||||
|
if not source_image_same:
|
||||||
|
SOURCE_IMAGE_LIST_HASH[i] = source_image_md5hash
|
||||||
|
|
||||||
|
logger.info("(Image %s) Source Image MD5 Hash = %s", i, SOURCE_IMAGE_LIST_HASH[i])
|
||||||
|
logger.info("(Image %s) Source Image the Same? %s", i, source_image_same)
|
||||||
|
|
||||||
|
if len(SOURCE_FACES_LIST) == 0:
|
||||||
|
logger.status(f"Analyzing Source Image {i}: {source_images_names[i]}...")
|
||||||
|
source_faces = analyze_faces(source_image, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
SOURCE_FACES_LIST = [source_faces]
|
||||||
|
elif len(SOURCE_FACES_LIST) == i and not source_image_same:
|
||||||
|
logger.status(f"Analyzing Source Image {i}: {source_images_names[i]}...")
|
||||||
|
source_faces = analyze_faces(source_image, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
SOURCE_FACES_LIST.append(source_faces)
|
||||||
|
elif len(SOURCE_FACES_LIST) != i and not source_image_same:
|
||||||
|
logger.status(f"Analyzing Source Image {i}: {source_images_names[i]}...")
|
||||||
|
source_faces = analyze_faces(source_image, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
SOURCE_FACES_LIST[i] = source_faces
|
||||||
|
elif source_image_same:
|
||||||
|
logger.status("(Image %s) Using Hashed Source Face(s) Model...", i)
|
||||||
|
source_faces = SOURCE_FACES_LIST[i]
|
||||||
|
|
||||||
|
else:
|
||||||
|
logger.status(f"Analyzing Source Image {i}...")
|
||||||
|
source_faces = analyze_faces(source_image, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
|
||||||
|
if source_faces is not None:
|
||||||
|
source_faces_ff.append(source_faces)
|
||||||
|
|
||||||
|
if len(source_faces_ff) > 0:
|
||||||
|
|
||||||
|
if target_hash_check:
|
||||||
|
|
||||||
|
target_image_md5hash = get_image_md5hash(target_img)
|
||||||
|
|
||||||
|
if TARGET_IMAGE_HASH is None:
|
||||||
|
TARGET_IMAGE_HASH = target_image_md5hash
|
||||||
|
target_image_same = False
|
||||||
|
else:
|
||||||
|
target_image_same = True if TARGET_IMAGE_HASH == target_image_md5hash else False
|
||||||
|
if not target_image_same:
|
||||||
|
TARGET_IMAGE_HASH = target_image_md5hash
|
||||||
|
|
||||||
|
logger.info("Target Image MD5 Hash = %s", TARGET_IMAGE_HASH)
|
||||||
|
logger.info("Target Image the Same? %s", target_image_same)
|
||||||
|
|
||||||
|
if TARGET_FACES is None or not target_image_same:
|
||||||
|
logger.status("Analyzing Target Image...")
|
||||||
|
target_faces = analyze_faces(target_img, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
TARGET_FACES = target_faces
|
||||||
|
elif target_image_same:
|
||||||
|
logger.status("Using Hashed Target Face(s) Model...")
|
||||||
|
target_faces = TARGET_FACES
|
||||||
|
|
||||||
|
else:
|
||||||
|
logger.status("Analyzing Target Image...")
|
||||||
|
target_faces = analyze_faces(target_img, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
|
||||||
|
for i,source_faces in enumerate(source_faces_ff):
|
||||||
|
|
||||||
|
logger.status("(Image %s) Detecting Source Face, Index = %s", i, source_faces_index[0])
|
||||||
|
source_face, wrong_gender, source_age, source_gender = get_face_single(source_img_ff[i], source_faces, face_index=source_faces_index[0], gender_source=gender_source, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
|
||||||
|
if source_age != "None" or source_gender != "None":
|
||||||
|
logger.status("(Image %s) Detected: -%s- y.o. %s", i, source_age, source_gender)
|
||||||
|
|
||||||
if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index):
|
if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index):
|
||||||
logger.info("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.")
|
logger.status("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.")
|
||||||
|
|
||||||
elif source_face is not None:
|
elif source_face is not None:
|
||||||
|
|
||||||
|
result_image, output, swapped = operate(source_img_ff[i],target_img,target_img_orig,model,source_faces_index,faces_index,source_faces,target_faces,gender_source,gender_target,source_face,wrong_gender,source_age,source_gender,output,swapped,mask_face,entire_mask_image,enhancement_options,detection_options)
|
||||||
|
|
||||||
|
result.append(result_image)
|
||||||
|
|
||||||
|
result = [result_image] if len(result) == 0 else result
|
||||||
|
|
||||||
|
return result, output, swapped
|
||||||
|
|
||||||
|
# END
|
||||||
|
# *****************
|
||||||
|
|
||||||
|
# ***********************
|
||||||
|
# SWAP from IMG or MODEL:
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
if select_source == 0 and source_img is not None:
|
||||||
|
|
||||||
|
source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
|
||||||
|
|
||||||
|
if source_hash_check:
|
||||||
|
|
||||||
|
source_image_md5hash = get_image_md5hash(source_img)
|
||||||
|
|
||||||
|
if SOURCE_IMAGE_HASH is None:
|
||||||
|
SOURCE_IMAGE_HASH = source_image_md5hash
|
||||||
|
source_image_same = False
|
||||||
|
else:
|
||||||
|
source_image_same = True if SOURCE_IMAGE_HASH == source_image_md5hash else False
|
||||||
|
if not source_image_same:
|
||||||
|
SOURCE_IMAGE_HASH = source_image_md5hash
|
||||||
|
|
||||||
|
logger.info("Source Image MD5 Hash = %s", SOURCE_IMAGE_HASH)
|
||||||
|
logger.info("Source Image the Same? %s", source_image_same)
|
||||||
|
|
||||||
|
if SOURCE_FACES is None or not source_image_same:
|
||||||
|
logger.status("Analyzing Source Image...")
|
||||||
|
source_faces = analyze_faces(source_img, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
SOURCE_FACES = source_faces
|
||||||
|
elif source_image_same:
|
||||||
|
logger.status("Using Hashed Source Face(s) Model...")
|
||||||
|
source_faces = SOURCE_FACES
|
||||||
|
|
||||||
|
else:
|
||||||
|
logger.status("Analyzing Source Image...")
|
||||||
|
source_faces = analyze_faces(source_img, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
|
||||||
|
elif select_source == 1 and (face_model is not None and face_model != "None"):
|
||||||
|
source_face_model = [load_face_model(face_model)]
|
||||||
|
if source_face_model is not None:
|
||||||
|
source_faces_index = [0]
|
||||||
|
source_faces = source_face_model
|
||||||
|
logger.status(f"Using Loaded Source Face Model: {face_model}")
|
||||||
|
else:
|
||||||
|
logger.error(f"Cannot load Face Model File: {face_model}")
|
||||||
|
|
||||||
|
else:
|
||||||
|
logger.error("Cannot detect any Source")
|
||||||
|
return result_image, [], 0
|
||||||
|
|
||||||
|
if source_faces is not None:
|
||||||
|
|
||||||
|
if target_hash_check:
|
||||||
|
|
||||||
|
target_image_md5hash = get_image_md5hash(target_img)
|
||||||
|
|
||||||
|
if TARGET_IMAGE_HASH is None:
|
||||||
|
TARGET_IMAGE_HASH = target_image_md5hash
|
||||||
|
target_image_same = False
|
||||||
|
else:
|
||||||
|
target_image_same = True if TARGET_IMAGE_HASH == target_image_md5hash else False
|
||||||
|
if not target_image_same:
|
||||||
|
TARGET_IMAGE_HASH = target_image_md5hash
|
||||||
|
|
||||||
|
logger.info("Target Image MD5 Hash = %s", TARGET_IMAGE_HASH)
|
||||||
|
logger.info("Target Image the Same? %s", target_image_same)
|
||||||
|
|
||||||
|
if TARGET_FACES is None or not target_image_same:
|
||||||
|
logger.status("Analyzing Target Image...")
|
||||||
|
target_faces = analyze_faces(target_img, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
TARGET_FACES = target_faces
|
||||||
|
elif target_image_same:
|
||||||
|
logger.status("Using Hashed Target Face(s) Model...")
|
||||||
|
target_faces = TARGET_FACES
|
||||||
|
|
||||||
|
else:
|
||||||
|
logger.status("Analyzing Target Image...")
|
||||||
|
target_faces = analyze_faces(target_img, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
|
||||||
|
logger.status("Detecting Source Face, Index = %s", source_faces_index[0])
|
||||||
|
if select_source == 0 and source_img is not None:
|
||||||
|
source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, source_faces, face_index=source_faces_index[0], gender_source=gender_source, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
else:
|
||||||
|
source_face = sorted(source_faces, key=lambda x: x.bbox[0])[source_faces_index[0]]
|
||||||
|
wrong_gender = 0
|
||||||
|
source_age = source_face["age"]
|
||||||
|
source_gender = "Female" if source_face["gender"] == 0 else "Male"
|
||||||
|
|
||||||
|
if source_age != "None" or source_gender != "None":
|
||||||
|
logger.status("Detected: -%s- y.o. %s", source_age, source_gender)
|
||||||
|
|
||||||
|
output_info = f"SourceFaceIndex={source_faces_index[0]};Age={source_age};Gender={source_gender}\n"
|
||||||
|
output.append(output_info)
|
||||||
|
|
||||||
|
if len(source_faces_index) != 0 and len(source_faces_index) != 1 and len(source_faces_index) != len(faces_index):
|
||||||
|
logger.status("Source Faces must have no entries (default=0), one entry, or same number of entries as target faces.")
|
||||||
|
|
||||||
|
elif source_face is not None:
|
||||||
|
|
||||||
|
result_image, output, swapped = operate(source_img,target_img,target_img_orig,model,source_faces_index,faces_index,source_faces,target_faces,gender_source,gender_target,source_face,wrong_gender,source_age,source_gender,output,swapped,mask_face,entire_mask_image,enhancement_options,detection_options)
|
||||||
|
|
||||||
|
else:
|
||||||
|
logger.status("No source face(s) in the provided Index")
|
||||||
|
else:
|
||||||
|
logger.status("No source face(s) found")
|
||||||
|
|
||||||
|
return result_image, output, swapped
|
||||||
|
|
||||||
|
# END
|
||||||
|
# **********************
|
||||||
|
|
||||||
|
return result_image, [], 0
|
||||||
|
|
||||||
|
def build_face_model(image: Image.Image, name: str, save_model: bool = True, det_size=(640, 640)):
|
||||||
|
if image is None:
|
||||||
|
error_msg = "Please load an Image"
|
||||||
|
logger.error(error_msg)
|
||||||
|
return error_msg
|
||||||
|
if name is None:
|
||||||
|
error_msg = "Please filled out the 'Face Model Name' field"
|
||||||
|
logger.error(error_msg)
|
||||||
|
return error_msg
|
||||||
|
apply_logging_patch(1)
|
||||||
|
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
||||||
|
if save_model:
|
||||||
|
logger.status("Building Face Model...")
|
||||||
|
face_model = analyze_faces(image, det_size)
|
||||||
|
|
||||||
|
if len(face_model) == 0:
|
||||||
|
det_size_half = half_det_size(det_size)
|
||||||
|
face_model = analyze_faces(image, det_size_half)
|
||||||
|
|
||||||
|
if face_model is not None and len(face_model) > 0:
|
||||||
|
if save_model:
|
||||||
|
face_model_path = os.path.join(FACE_MODELS_PATH, name + ".safetensors")
|
||||||
|
save_face_model(face_model[0],face_model_path)
|
||||||
|
logger.status("--Done!--")
|
||||||
|
done_msg = f"Face model has been saved to '{face_model_path}'"
|
||||||
|
logger.status(done_msg)
|
||||||
|
return done_msg
|
||||||
|
else:
|
||||||
|
return face_model[0]
|
||||||
|
else:
|
||||||
|
no_face_msg = "No face found, please try another image"
|
||||||
|
logger.error(no_face_msg)
|
||||||
|
return no_face_msg
|
||||||
|
|
||||||
|
def blend_faces(images_list: List, name: str, compute_method: int = 0, shape_check: bool = False, is_api: bool = False):
|
||||||
|
faces = []
|
||||||
|
embeddings = []
|
||||||
|
images: List[Image.Image] = []
|
||||||
|
if not is_api:
|
||||||
|
images, images_names = get_images_from_list(images_list)
|
||||||
|
else:
|
||||||
|
images = images_list
|
||||||
|
for i,image in enumerate(images):
|
||||||
|
if not is_api:
|
||||||
|
logger.status(f"Building Face Model for {images_names[i]}...")
|
||||||
|
else:
|
||||||
|
logger.status(f"Building Face Model for Image {i+1}...")
|
||||||
|
face = build_face_model(image,str(i),save_model=False)
|
||||||
|
if isinstance(face, str):
|
||||||
|
# logger.error(f"No faces found in {images_names[i]}, skipping")
|
||||||
|
continue
|
||||||
|
if shape_check:
|
||||||
|
if i == 0:
|
||||||
|
embedding_shape = face.embedding.shape
|
||||||
|
elif face.embedding.shape != embedding_shape:
|
||||||
|
if not is_api:
|
||||||
|
logger.error(f"Embedding Shape Mismatch for {images_names[i]}, skipping")
|
||||||
|
else:
|
||||||
|
logger.error(f"Embedding Shape Mismatch for Image {i+1}, skipping")
|
||||||
|
continue
|
||||||
|
faces.append(face)
|
||||||
|
embeddings.append(face.embedding)
|
||||||
|
if len(faces) > 0:
|
||||||
|
# if shape_check:
|
||||||
|
# embedding_shape = embeddings[0].shape
|
||||||
|
# for embedding in embeddings:
|
||||||
|
# if embedding.shape != embedding_shape:
|
||||||
|
# logger.error("Embedding Shape Mismatch")
|
||||||
|
# break
|
||||||
|
compute_method_name = "Mean" if compute_method == 0 else "Median" if compute_method == 1 else "Mode"
|
||||||
|
logger.status(f"Blending with Compute Method {compute_method_name}...")
|
||||||
|
blended_embedding = np.mean(embeddings, axis=0) if compute_method == 0 else np.median(embeddings, axis=0) if compute_method == 1 else stats.mode(embeddings, axis=0)[0].astype(np.float32)
|
||||||
|
blended_face = Face(
|
||||||
|
bbox=faces[0].bbox,
|
||||||
|
kps=faces[0].kps,
|
||||||
|
det_score=faces[0].det_score,
|
||||||
|
landmark_3d_68=faces[0].landmark_3d_68,
|
||||||
|
pose=faces[0].pose,
|
||||||
|
landmark_2d_106=faces[0].landmark_2d_106,
|
||||||
|
embedding=blended_embedding,
|
||||||
|
gender=faces[0].gender,
|
||||||
|
age=faces[0].age
|
||||||
|
)
|
||||||
|
if blended_face is not None:
|
||||||
|
face_model_path = os.path.join(FACE_MODELS_PATH, name + ".safetensors")
|
||||||
|
save_face_model(blended_face,face_model_path)
|
||||||
|
logger.status("--Done!--")
|
||||||
|
done_msg = f"Face model has been saved to '{face_model_path}'"
|
||||||
|
logger.status(done_msg)
|
||||||
|
return done_msg
|
||||||
|
else:
|
||||||
|
no_face_msg = "Something went wrong, please try another set of images"
|
||||||
|
logger.error(no_face_msg)
|
||||||
|
return no_face_msg
|
||||||
|
return "No faces found"
|
||||||
|
|
||||||
|
|
||||||
|
def operate(
|
||||||
|
source_img,
|
||||||
|
target_img,
|
||||||
|
target_img_orig,
|
||||||
|
model,
|
||||||
|
source_faces_index,
|
||||||
|
faces_index,
|
||||||
|
source_faces,
|
||||||
|
target_faces,
|
||||||
|
gender_source,
|
||||||
|
gender_target,
|
||||||
|
source_face,
|
||||||
|
wrong_gender,
|
||||||
|
source_age,
|
||||||
|
source_gender,
|
||||||
|
output,
|
||||||
|
swapped,
|
||||||
|
mask_face,
|
||||||
|
entire_mask_image,
|
||||||
|
enhancement_options,
|
||||||
|
detection_options,
|
||||||
|
):
|
||||||
result = target_img
|
result = target_img
|
||||||
face_swapper = getFaceSwapModel(model)
|
face_swapper = getFaceSwapModel(model)
|
||||||
|
|
||||||
source_face_idx = 0
|
source_face_idx = 0
|
||||||
|
|
||||||
swapped = 0
|
|
||||||
|
|
||||||
for face_num in faces_index:
|
for face_num in faces_index:
|
||||||
|
if check_process_halt():
|
||||||
|
return result_image, [], 0
|
||||||
if len(source_faces_index) > 1 and source_face_idx > 0:
|
if len(source_faces_index) > 1 and source_face_idx > 0:
|
||||||
source_face, wrong_gender = get_face_single(source_img, face_index=source_faces_index[source_face_idx], gender_source=gender_source)
|
logger.status("Detecting Source Face, Index = %s", source_faces_index[source_face_idx])
|
||||||
|
source_face, wrong_gender, source_age, source_gender = get_face_single(source_img, source_faces, face_index=source_faces_index[source_face_idx], gender_source=gender_source, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
if source_age != "None" or source_gender != "None":
|
||||||
|
logger.status("Detected: -%s- y.o. %s", source_age, source_gender)
|
||||||
|
|
||||||
|
output_info = f"SourceFaceIndex={source_faces_index[source_face_idx]};Age={source_age};Gender={source_gender}\n"
|
||||||
|
output.append(output_info)
|
||||||
|
|
||||||
source_face_idx += 1
|
source_face_idx += 1
|
||||||
|
|
||||||
if source_face is not None and wrong_gender == 0:
|
if source_face is not None and wrong_gender == 0:
|
||||||
target_face, wrong_gender = get_face_single(target_img, face_index=face_num, gender_target=gender_target)
|
logger.status("Detecting Target Face, Index = %s", face_num)
|
||||||
|
target_face, wrong_gender, target_age, target_gender = get_face_single(target_img, target_faces, face_index=face_num, gender_target=gender_target, det_thresh=detection_options.det_thresh, det_maxnum=detection_options.det_maxnum)
|
||||||
|
if target_age != "None" or target_gender != "None":
|
||||||
|
logger.status("Detected: -%s- y.o. %s", target_age, target_gender)
|
||||||
|
|
||||||
|
output_info = f"TargetFaceIndex={face_num};Age={target_age};Gender={target_gender}\n"
|
||||||
|
output.append(output_info)
|
||||||
|
|
||||||
if target_face is not None and wrong_gender == 0:
|
if target_face is not None and wrong_gender == 0:
|
||||||
result = face_swapper.get(result, target_face, source_face)
|
logger.status("Swapping Source into Target")
|
||||||
|
swapped_image = face_swapper.get(result, target_face, source_face)
|
||||||
|
|
||||||
|
if mask_face:
|
||||||
|
result = apply_face_mask(swapped_image=swapped_image,target_image=result,target_face=target_face,entire_mask_image=entire_mask_image)
|
||||||
|
else:
|
||||||
|
result = swapped_image
|
||||||
swapped += 1
|
swapped += 1
|
||||||
|
|
||||||
elif wrong_gender == 1:
|
elif wrong_gender == 1:
|
||||||
wrong_gender = 0
|
wrong_gender = 0
|
||||||
|
|
||||||
if source_face_idx == len(source_faces_index):
|
if source_face_idx == len(source_faces_index):
|
||||||
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
|
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
|
||||||
if upscale_options is not None:
|
|
||||||
result_image = upscale_image(result_image, upscale_options)
|
if enhancement_options is not None and len(source_faces_index) > 1:
|
||||||
return result_image
|
result_image = enhance_image(result_image, enhancement_options)
|
||||||
|
|
||||||
|
return result_image, output, swapped
|
||||||
|
|
||||||
else:
|
else:
|
||||||
logger.info(f"No target face found for {face_num}")
|
logger.status(f"No target face found for {face_num}")
|
||||||
|
|
||||||
elif wrong_gender == 1:
|
elif wrong_gender == 1:
|
||||||
wrong_gender = 0
|
wrong_gender = 0
|
||||||
|
|
||||||
if source_face_idx == len(source_faces_index):
|
if source_face_idx == len(source_faces_index):
|
||||||
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
|
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
|
||||||
if upscale_options is not None:
|
|
||||||
result_image = upscale_image(result_image, upscale_options)
|
if enhancement_options is not None and len(source_faces_index) > 1:
|
||||||
return result_image
|
result_image = enhance_image(result_image, enhancement_options)
|
||||||
|
|
||||||
|
return result_image, output, swapped
|
||||||
|
|
||||||
else:
|
else:
|
||||||
logger.info(f"No source face found for face number {source_face_idx}.")
|
logger.status(f"No source face found for face number {source_face_idx}.")
|
||||||
|
|
||||||
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
|
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
|
||||||
if upscale_options is not None and swapped > 0:
|
|
||||||
result_image = upscale_image(result_image, upscale_options)
|
|
||||||
|
|
||||||
|
if (enhancement_options is not None and swapped > 0) or enhancement_options.upscale_force:
|
||||||
|
if mask_face and entire_mask_image is not None:
|
||||||
|
result_image = enhance_image_and_mask(result_image, enhancement_options,Image.fromarray(target_img_orig),Image.fromarray(entire_mask_image).convert("L"))
|
||||||
else:
|
else:
|
||||||
logger.info("No source face(s) found")
|
result_image = enhance_image(result_image, enhancement_options)
|
||||||
return result_image
|
elif mask_face and entire_mask_image is not None and swapped > 0:
|
||||||
|
result_image = Image.composite(result_image,Image.fromarray(target_img_orig),Image.fromarray(entire_mask_image).convert("L"))
|
||||||
|
|
||||||
|
return result_image, output, swapped
|
||||||
|
|||||||
@ -1,10 +1,11 @@
|
|||||||
app_title = "ReActor"
|
app_title = "ReActor"
|
||||||
version_flag = "v0.4.1"
|
version_flag = "v0.7.1-b2"
|
||||||
|
|
||||||
from scripts.reactor_logger import logger, get_Run, set_Run
|
from scripts.reactor_logger import logger, get_Run, set_Run
|
||||||
|
from scripts.reactor_globals import DEVICE
|
||||||
|
|
||||||
is_run = get_Run()
|
is_run = get_Run()
|
||||||
|
|
||||||
if not is_run:
|
if not is_run:
|
||||||
logger.info(f"Running {version_flag}")
|
logger.status(f"Running {version_flag} on Device: {DEVICE}")
|
||||||
set_Run(True)
|
set_Run(True)
|
||||||
|
|||||||
94
scripts/reactor_xyz.py
Normal file
94
scripts/reactor_xyz.py
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
'''
|
||||||
|
Thanks @ledahu for contributing
|
||||||
|
'''
|
||||||
|
|
||||||
|
from modules import scripts
|
||||||
|
from modules.shared import opts
|
||||||
|
|
||||||
|
from scripts.reactor_helpers import (
|
||||||
|
get_model_names,
|
||||||
|
get_facemodels
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# xyz_grid = [x for x in scripts.scripts_data if x.script_class.__module__ == "xyz_grid.py"][0].module
|
||||||
|
|
||||||
|
def find_module(module_names):
|
||||||
|
if isinstance(module_names, str):
|
||||||
|
module_names = [s.strip() for s in module_names.split(",")]
|
||||||
|
for data in scripts.scripts_data:
|
||||||
|
if data.script_class.__module__ in module_names and hasattr(data, "module"):
|
||||||
|
return data.module
|
||||||
|
return None
|
||||||
|
|
||||||
|
def bool_(string):
|
||||||
|
string = str(string)
|
||||||
|
if string in ["None", ""]:
|
||||||
|
return None
|
||||||
|
elif string.lower() in ["true", "1"]:
|
||||||
|
return True
|
||||||
|
elif string.lower() in ["false", "0"]:
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Could not convert string to boolean: {string}")
|
||||||
|
|
||||||
|
def choices_bool():
|
||||||
|
return ["False", "True"]
|
||||||
|
|
||||||
|
def choices_face_models():
|
||||||
|
return get_model_names(get_facemodels)
|
||||||
|
|
||||||
|
def float_applier(value_name:str, min_range:float = 0, max_range:float = 1):
|
||||||
|
"""
|
||||||
|
Returns a function that applies the given value to the given value_name in opts.data.
|
||||||
|
"""
|
||||||
|
def validate(value_name:str, value:str):
|
||||||
|
value = float(value)
|
||||||
|
# validate value
|
||||||
|
if not min_range == 0:
|
||||||
|
assert value >= min_range, f"Value {value} for {value_name} must be greater than or equal to {min_range}"
|
||||||
|
if not max_range == 1:
|
||||||
|
assert value <= max_range, f"Value {value} for {value_name} must be less than or equal to {max_range}"
|
||||||
|
def apply_float(p, x, xs):
|
||||||
|
validate(value_name, x)
|
||||||
|
opts.data[value_name] = float(x)
|
||||||
|
return apply_float
|
||||||
|
|
||||||
|
def bool_applier(value_name:str):
|
||||||
|
def apply_bool(p, x, xs):
|
||||||
|
x_normed = bool_(x)
|
||||||
|
opts.data[value_name] = x_normed
|
||||||
|
# print(f'normed = {x_normed}')
|
||||||
|
return apply_bool
|
||||||
|
|
||||||
|
def str_applier(value_name:str):
|
||||||
|
def apply_str(p, x, xs):
|
||||||
|
opts.data[value_name] = x
|
||||||
|
return apply_str
|
||||||
|
|
||||||
|
|
||||||
|
def add_axis_options(xyz_grid):
|
||||||
|
extra_axis_options = [
|
||||||
|
xyz_grid.AxisOption("[ReActor] CodeFormer Weight", float, float_applier("codeformer_weight", 0, 1)),
|
||||||
|
xyz_grid.AxisOption("[ReActor] Restorer Visibility", float, float_applier("restorer_visibility", 0, 1)),
|
||||||
|
xyz_grid.AxisOption("[ReActor] Face Mask Correction", str, bool_applier("mask_face"), choices=choices_bool),
|
||||||
|
xyz_grid.AxisOption("[ReActor] Face Models", str, str_applier("face_model"), choices=choices_face_models),
|
||||||
|
]
|
||||||
|
set_a = {opt.label for opt in xyz_grid.axis_options}
|
||||||
|
set_b = {opt.label for opt in extra_axis_options}
|
||||||
|
if set_a.intersection(set_b):
|
||||||
|
return
|
||||||
|
|
||||||
|
xyz_grid.axis_options.extend(extra_axis_options)
|
||||||
|
|
||||||
|
def run():
|
||||||
|
xyz_grid = find_module("xyz_grid.py, xy_grid.py")
|
||||||
|
if xyz_grid:
|
||||||
|
add_axis_options(xyz_grid)
|
||||||
|
|
||||||
|
# XYZ init:
|
||||||
|
try:
|
||||||
|
import modules.script_callbacks as script_callbacks
|
||||||
|
script_callbacks.on_before_ui(run)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
Loading…
x
Reference in New Issue
Block a user