dikdimon commited on
Commit
7bed60d
·
verified ·
1 Parent(s): 1e6ab29

Upload extensionsa using SD-Hub extension

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +101 -0
  2. extensionsa/1-sd-dynamic-thresholding/.github/FUNDING.yml +1 -0
  3. extensionsa/1-sd-dynamic-thresholding/.github/workflows/publish.yml +21 -0
  4. extensionsa/1-sd-dynamic-thresholding/.gitignore +1 -0
  5. extensionsa/1-sd-dynamic-thresholding/LICENSE.txt +21 -0
  6. extensionsa/1-sd-dynamic-thresholding/README.md +120 -0
  7. extensionsa/1-sd-dynamic-thresholding/__init__.py +6 -0
  8. extensionsa/1-sd-dynamic-thresholding/__pycache__/dynthres_core.cpython-310.pyc +0 -0
  9. extensionsa/1-sd-dynamic-thresholding/__pycache__/dynthres_unipc.cpython-310.pyc +0 -0
  10. extensionsa/1-sd-dynamic-thresholding/dynthres_comfyui.py +86 -0
  11. extensionsa/1-sd-dynamic-thresholding/dynthres_core.py +167 -0
  12. extensionsa/1-sd-dynamic-thresholding/dynthres_unipc.py +111 -0
  13. extensionsa/1-sd-dynamic-thresholding/github/cat_demo_1.jpg +0 -0
  14. extensionsa/1-sd-dynamic-thresholding/github/comfy_node.png +0 -0
  15. extensionsa/1-sd-dynamic-thresholding/github/grid_preview.png +0 -0
  16. extensionsa/1-sd-dynamic-thresholding/github/ui.png +0 -0
  17. extensionsa/1-sd-dynamic-thresholding/javascript/active.js +68 -0
  18. extensionsa/1-sd-dynamic-thresholding/pyproject.toml +13 -0
  19. extensionsa/1-sd-dynamic-thresholding/scripts/__pycache__/dynamic_thresholding.cpython-310.pyc +0 -0
  20. extensionsa/1-sd-dynamic-thresholding/scripts/dynamic_thresholding.py +270 -0
  21. extensionsa/2-sd-webui-reactor/.github/ISSUE_TEMPLATE/bug_report.yml +58 -0
  22. extensionsa/2-sd-webui-reactor/.github/ISSUE_TEMPLATE/config.yml +5 -0
  23. extensionsa/2-sd-webui-reactor/.github/ISSUE_TEMPLATE/feature_request.yml +16 -0
  24. extensionsa/2-sd-webui-reactor/.gitignore +10 -0
  25. extensionsa/2-sd-webui-reactor/API.md +85 -0
  26. extensionsa/2-sd-webui-reactor/LICENSE +661 -0
  27. extensionsa/2-sd-webui-reactor/README.md +413 -0
  28. extensionsa/2-sd-webui-reactor/README_RU.md +420 -0
  29. extensionsa/2-sd-webui-reactor/example/IamSFW.jpg +0 -0
  30. extensionsa/2-sd-webui-reactor/example/api_example.py +108 -0
  31. extensionsa/2-sd-webui-reactor/example/api_external.curl +0 -0
  32. extensionsa/2-sd-webui-reactor/example/api_external.json +0 -0
  33. extensionsa/2-sd-webui-reactor/install.py +155 -0
  34. extensionsa/2-sd-webui-reactor/last_device.txt +1 -0
  35. extensionsa/2-sd-webui-reactor/reactor_modules/__pycache__/reactor_mask.cpython-310.pyc +0 -0
  36. extensionsa/2-sd-webui-reactor/reactor_modules/reactor_mask.py +176 -0
  37. extensionsa/2-sd-webui-reactor/reactor_ui/__init__.py +5 -0
  38. extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/__init__.cpython-310.pyc +0 -0
  39. extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_detection_ui.cpython-310.pyc +0 -0
  40. extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_main_ui.cpython-310.pyc +0 -0
  41. extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_settings_ui.cpython-310.pyc +0 -0
  42. extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_tools_ui.cpython-310.pyc +0 -0
  43. extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_upscale_ui.cpython-310.pyc +0 -0
  44. extensionsa/2-sd-webui-reactor/reactor_ui/reactor_detection_ui.py +54 -0
  45. extensionsa/2-sd-webui-reactor/reactor_ui/reactor_main_ui.py +229 -0
  46. extensionsa/2-sd-webui-reactor/reactor_ui/reactor_settings_ui.py +77 -0
  47. extensionsa/2-sd-webui-reactor/reactor_ui/reactor_tools_ui.py +61 -0
  48. extensionsa/2-sd-webui-reactor/reactor_ui/reactor_upscale_ui.py +47 -0
  49. extensionsa/2-sd-webui-reactor/requirements.txt +4 -0
  50. extensionsa/2-sd-webui-reactor/scripts/__pycache__/console_log_patch.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -33,3 +33,104 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/anime_3.png filter=lfs diff=lfs merge=lfs -text
37
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/anime_4.png filter=lfs diff=lfs merge=lfs -text
38
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/canny_1.png filter=lfs diff=lfs merge=lfs -text
39
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/inpaint_before_fix.png filter=lfs diff=lfs merge=lfs -text
40
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/ip2p_1.png filter=lfs diff=lfs merge=lfs -text
41
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/ip2p_2.png filter=lfs diff=lfs merge=lfs -text
42
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/ip2p_3.png filter=lfs diff=lfs merge=lfs -text
43
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/lineart_1.png filter=lfs diff=lfs merge=lfs -text
44
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/lineart_2.png filter=lfs diff=lfs merge=lfs -text
45
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/lineart_3.png filter=lfs diff=lfs merge=lfs -text
46
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/mlsd_1.png filter=lfs diff=lfs merge=lfs -text
47
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/normal_1.png filter=lfs diff=lfs merge=lfs -text
48
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/normal_2.png filter=lfs diff=lfs merge=lfs -text
49
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/scribble_2.png filter=lfs diff=lfs merge=lfs -text
50
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/seg_2.png filter=lfs diff=lfs merge=lfs -text
51
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/shuffle_1.png filter=lfs diff=lfs merge=lfs -text
52
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/shuffle_2.png filter=lfs diff=lfs merge=lfs -text
53
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/softedge_1.png filter=lfs diff=lfs merge=lfs -text
54
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/tile_new_1.png filter=lfs diff=lfs merge=lfs -text
55
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/tile_new_2.png filter=lfs diff=lfs merge=lfs -text
56
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/tile_new_3.png filter=lfs diff=lfs merge=lfs -text
57
+ extensionsa/DWPose/ControlNet-v1-1-nightly/github_docs/imgs/tile_new_4.png filter=lfs diff=lfs merge=lfs -text
58
+ extensionsa/DWPose/ControlNet-v1-1-nightly/test_imgs/bird.png filter=lfs diff=lfs merge=lfs -text
59
+ extensionsa/DWPose/ControlNet-v1-1-nightly/test_imgs/building.png filter=lfs diff=lfs merge=lfs -text
60
+ extensionsa/DWPose/ControlNet-v1-1-nightly/test_imgs/building2.png filter=lfs diff=lfs merge=lfs -text
61
+ extensionsa/DWPose/ControlNet-v1-1-nightly/test_imgs/girls.jpg filter=lfs diff=lfs merge=lfs -text
62
+ extensionsa/DWPose/ControlNet-v1-1-nightly/test_imgs/person-leaves.png filter=lfs diff=lfs merge=lfs -text
63
+ extensionsa/DWPose/ControlNet-v1-1-nightly/test_imgs/sn.jpg filter=lfs diff=lfs merge=lfs -text
64
+ extensionsa/DWPose/mmpose/demo/resources/demo_coco.gif filter=lfs diff=lfs merge=lfs -text
65
+ extensionsa/DWPose/mmpose/tests/data/humanart/2D_virtual_human/digital_art/000000001648.jpg filter=lfs diff=lfs merge=lfs -text
66
+ extensionsa/DWPose/resources/architecture.jpg filter=lfs diff=lfs merge=lfs -text
67
+ extensionsa/DWPose/resources/generation.jpg filter=lfs diff=lfs merge=lfs -text
68
+ extensionsa/DWPose/resources/iron.gif filter=lfs diff=lfs merge=lfs -text
69
+ extensionsa/DWPose/resources/jay_pose.jpg filter=lfs diff=lfs merge=lfs -text
70
+ extensionsa/DWPose/resources/lalaland.gif filter=lfs diff=lfs merge=lfs -text
71
+ extensionsa/a1111-sd-webui-tagcomplete/tags/danbooru2023.csv filter=lfs diff=lfs merge=lfs -text
72
+ extensionsa/advanced_euler_sampler_extension/img/xyz_grid-0000-114514.jpg filter=lfs diff=lfs merge=lfs -text
73
+ extensionsa/diffusion-noise-alternatives-webui/images/ColorGrade.png filter=lfs diff=lfs merge=lfs -text
74
+ extensionsa/diffusion-noise-alternatives-webui/images/GrainCompare.png filter=lfs diff=lfs merge=lfs -text
75
+ extensionsa/extra-network-browser/screenshot.png filter=lfs diff=lfs merge=lfs -text
76
+ extensionsa/sd-civitai-browser-plus_fix/aria2/lin/aria2 filter=lfs diff=lfs merge=lfs -text
77
+ extensionsa/sd-civitai-browser-plus_fix/aria2/win/aria2.exe filter=lfs diff=lfs merge=lfs -text
78
+ extensionsa/sd-webui-agentattention/samples/xyz_grid-2415-1-desk.png filter=lfs diff=lfs merge=lfs -text
79
+ extensionsa/sd-webui-agentattention/samples/xyz_grid-2417-1-goldfinch,[[:space:]]Carduelis[[:space:]]carduelis.png filter=lfs diff=lfs merge=lfs -text
80
+ extensionsa/sd-webui-agentattention/samples/xyz_grid-2418-1-bell[[:space:]]pepper.png filter=lfs diff=lfs merge=lfs -text
81
+ extensionsa/sd-webui-agentattention/samples/xyz_grid-2419-1-bicycle.png filter=lfs diff=lfs merge=lfs -text
82
+ extensionsa/sd-webui-agentattention/samples/xyz_grid-2428-1-desk.jpg filter=lfs diff=lfs merge=lfs -text
83
+ extensionsa/sd-webui-birefnet/sd-webui-birefnet.png filter=lfs diff=lfs merge=lfs -text
84
+ extensionsa/sd-webui-cads/samples/comparison.png filter=lfs diff=lfs merge=lfs -text
85
+ extensionsa/sd-webui-cads/samples/grid-7069.png filter=lfs diff=lfs merge=lfs -text
86
+ extensionsa/sd-webui-cads/samples/grid-7070.png filter=lfs diff=lfs merge=lfs -text
87
+ extensionsa/sd-webui-cardmaster/docked-detail-view.png filter=lfs diff=lfs merge=lfs -text
88
+ extensionsa/sd-webui-cardmaster/preview.gif filter=lfs diff=lfs merge=lfs -text
89
+ extensionsa/sd-webui-cardmaster/toma-chan[[:space:]]alt.png filter=lfs diff=lfs merge=lfs -text
90
+ extensionsa/sd-webui-cardmaster/toma-chan.png filter=lfs diff=lfs merge=lfs -text
91
+ extensionsa/sd-webui-cutoff/images/cover.jpg filter=lfs diff=lfs merge=lfs -text
92
+ extensionsa/sd-webui-cutoff/images/sample-1.png filter=lfs diff=lfs merge=lfs -text
93
+ extensionsa/sd-webui-cutoff/images/sample-2.png filter=lfs diff=lfs merge=lfs -text
94
+ extensionsa/sd-webui-cutoff/images/sample-3.png filter=lfs diff=lfs merge=lfs -text
95
+ extensionsa/sd-webui-cutoff/images/sample-4.png filter=lfs diff=lfs merge=lfs -text
96
+ extensionsa/sd-webui-cutoff/images/sample-4_small.png filter=lfs diff=lfs merge=lfs -text
97
+ extensionsa/sd-webui-cutoff/images/sample-5.png filter=lfs diff=lfs merge=lfs -text
98
+ extensionsa/sd-webui-cutoff/images/sample-5_small.png filter=lfs diff=lfs merge=lfs -text
99
+ extensionsa/sd-webui-fabric/static/example_2_default.png filter=lfs diff=lfs merge=lfs -text
100
+ extensionsa/sd-webui-fabric/static/example_2_feedback.png filter=lfs diff=lfs merge=lfs -text
101
+ extensionsa/sd-webui-fabric/static/example_3_10.png filter=lfs diff=lfs merge=lfs -text
102
+ extensionsa/sd-webui-fabric/static/example_3_feedback.png filter=lfs diff=lfs merge=lfs -text
103
+ extensionsa/sd-webui-fabric/static/fabric_demo.gif filter=lfs diff=lfs merge=lfs -text
104
+ extensionsa/sd-webui-image-comparison/tab.gif filter=lfs diff=lfs merge=lfs -text
105
+ extensionsa/sd-webui-incantations/images/xyz_grid-0463-3.jpg filter=lfs diff=lfs merge=lfs -text
106
+ extensionsa/sd-webui-incantations/images/xyz_grid-0469-4.jpg filter=lfs diff=lfs merge=lfs -text
107
+ extensionsa/sd-webui-incantations/images/xyz_grid-2652-1419902843-cinematic[[:space:]]4K[[:space:]]photo[[:space:]]of[[:space:]]a[[:space:]]dog[[:space:]]riding[[:space:]]a[[:space:]]bus[[:space:]]and[[:space:]]eating[[:space:]]cake[[:space:]]and[[:space:]]wearing[[:space:]]headphones.png filter=lfs diff=lfs merge=lfs -text
108
+ extensionsa/sd-webui-incantations/images/xyz_grid-2660-1590472902-A[[:space:]]photo[[:space:]]of[[:space:]]a[[:space:]]lion[[:space:]]and[[:space:]]a[[:space:]]grizzly[[:space:]]bear[[:space:]]and[[:space:]]a[[:space:]]tiger[[:space:]]in[[:space:]]the[[:space:]]woods.jpg filter=lfs diff=lfs merge=lfs -text
109
+ extensionsa/sd-webui-incantations/images/xyz_grid-3040-1-a[[:space:]]puppy[[:space:]]and[[:space:]]a[[:space:]]kitten[[:space:]]on[[:space:]]the[[:space:]]moon.png filter=lfs diff=lfs merge=lfs -text
110
+ extensionsa/sd-webui-incantations/images/xyz_grid-3348-1590472902-A[[:space:]]photo[[:space:]]of[[:space:]]a[[:space:]]lion[[:space:]]and[[:space:]]a[[:space:]]grizzly[[:space:]]bear[[:space:]]and[[:space:]]a[[:space:]]tiger[[:space:]]in[[:space:]]the[[:space:]]woods.jpg filter=lfs diff=lfs merge=lfs -text
111
+ extensionsa/sd-webui-llul/images/llul_yuv420p.mp4 filter=lfs diff=lfs merge=lfs -text
112
+ extensionsa/sd-webui-llul/images/mask_effect.jpg filter=lfs diff=lfs merge=lfs -text
113
+ extensionsa/sd-webui-matview/images/sample1.jpg filter=lfs diff=lfs merge=lfs -text
114
+ extensionsa/sd-webui-pag/images/xyz_grid-3040-1-a[[:space:]]puppy[[:space:]]and[[:space:]]a[[:space:]]kitten[[:space:]]on[[:space:]]the[[:space:]]moon.png filter=lfs diff=lfs merge=lfs -text
115
+ extensionsa/sd-webui-samplers-scheduler/images/example2.png filter=lfs diff=lfs merge=lfs -text
116
+ extensionsa/sd-webui-samplers-scheduler/images/example3.png filter=lfs diff=lfs merge=lfs -text
117
+ extensionsa/sd-webui-semantic-guidance/samples/comparison.png filter=lfs diff=lfs merge=lfs -text
118
+ extensionsa/sd-webui-semantic-guidance/samples/enhance.jpg filter=lfs diff=lfs merge=lfs -text
119
+ extensionsa/sd-webui-smea/sample.jpg filter=lfs diff=lfs merge=lfs -text
120
+ extensionsa/sd-webui-smea/sample2.jpg filter=lfs diff=lfs merge=lfs -text
121
+ extensionsa/sd-webui-vectorscope-cc/samples/XYZ.jpg filter=lfs diff=lfs merge=lfs -text
122
+ extensionsa/sd-webui-xl_vec/images/crop_top.png filter=lfs diff=lfs merge=lfs -text
123
+ extensionsa/sd-webui-xl_vec/images/mult.png filter=lfs diff=lfs merge=lfs -text
124
+ extensionsa/sd-webui-xl_vec/images/original_size.png filter=lfs diff=lfs merge=lfs -text
125
+ extensionsa/sd_extension-prompt_formatter/Twemoji.Mozilla.ttf filter=lfs diff=lfs merge=lfs -text
126
+ extensionsa/ssasd/images/sample.png filter=lfs diff=lfs merge=lfs -text
127
+ extensionsa/ssasd/images/sample2.png filter=lfs diff=lfs merge=lfs -text
128
+ extensionsa/ssasd/images/sample3.png filter=lfs diff=lfs merge=lfs -text
129
+ extensionsa/stable-diffusion-webui-composable-lora/readme/changelog_2023-04-08.png filter=lfs diff=lfs merge=lfs -text
130
+ extensionsa/stable-diffusion-webui-composable-lora/readme/fig11.png filter=lfs diff=lfs merge=lfs -text
131
+ extensionsa/stable-diffusion-webui-composable-lora/readme/fig12.png filter=lfs diff=lfs merge=lfs -text
132
+ extensionsa/stable-diffusion-webui-composable-lora/readme/fig13.png filter=lfs diff=lfs merge=lfs -text
133
+ extensionsa/stable-diffusion-webui-composable-lora/readme/fig8.png filter=lfs diff=lfs merge=lfs -text
134
+ extensionsa/stable-diffusion-webui-composable-lora/readme/fig9.png filter=lfs diff=lfs merge=lfs -text
135
+ extensionsa/stable-diffusion-webui-rembg/preview.png filter=lfs diff=lfs merge=lfs -text
136
+ extensionsa/stable-diffusion-webui-tripclipskip/images/xy_plot.jpg filter=lfs diff=lfs merge=lfs -text
extensionsa/1-sd-dynamic-thresholding/.github/FUNDING.yml ADDED
@@ -0,0 +1 @@
 
 
1
+ github: mcmonkey4eva
extensionsa/1-sd-dynamic-thresholding/.github/workflows/publish.yml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - master
7
+ paths:
8
+ - "pyproject.toml"
9
+
10
+ jobs:
11
+ publish-node:
12
+ name: Publish Custom Node to registry
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Check out code
16
+ uses: actions/checkout@v4
17
+ - name: Publish Custom Node
18
+ uses: Comfy-Org/publish-node-action@main
19
+ with:
20
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
21
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
extensionsa/1-sd-dynamic-thresholding/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__/
extensionsa/1-sd-dynamic-thresholding/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Alex "mcmonkey" Goodwin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
extensionsa/1-sd-dynamic-thresholding/README.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion Dynamic Thresholding (CFG Scale Fix)
2
+
3
+ ### Concept
4
+
5
+ Extension for [SwarmUI](https://github.com/mcmonkeyprojects/SwarmUI), [ComfyUI](https://github.com/comfyanonymous/ComfyUI), and [AUTOMATIC1111 Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) that enables a way to use higher CFG Scales without color issues.
6
+
7
+ This works by clamping latents between steps. You can read more [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/3962) or [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/3268) or [this tweet](https://twitter.com/Birchlabs/status/1582165379832348672).
8
+
9
+ --------------
10
+
11
+ ### Credit
12
+
13
+ The core functionality of this PR was originally developed by [Birch-san](https://github.com/Birch-san) and ported to the WebUI by [dtan3847](https://github.com/dtan3847), then converted to an Auto WebUI extension and given a UI by [mcmonkey4eva](https://github.com/mcmonkey4eva), further development and research done by [mcmonkey4eva](https://github.com/mcmonkey4eva) and JDMLeverton. Ported by ComfyUI by [TwoDukes](https://github.com/TwoDukes) and [mcmonkey4eva](https://github.com/mcmonkey4eva). Ported to SwarmUI by [mcmonkey4eva](https://github.com/mcmonkey4eva).
14
+
15
+ --------------
16
+
17
+ ### Examples
18
+
19
+ ![img](github/cat_demo_1.jpg)
20
+
21
+ ![img](github/ui.png)
22
+
23
+
24
+ --------------
25
+
26
+ ### Demo Grid
27
+
28
+ View at <https://sd.mcmonkey.org/dynthresh/>.
29
+
30
+ ![img](github/grid_preview.png)
31
+
32
+ (Was generated via [this YAML config](https://gist.github.com/mcmonkey4eva/fccd29172f44424dfc0217a482c824f6) for the [Infinite Grid Generator](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script))
33
+
34
+ --------------
35
+
36
+ ### Installation and Usage
37
+
38
+ #### SwarmUI
39
+
40
+ - Supported out-of-the-box on default installations.
41
+ - If using a custom installation, just make sure the backend you use has this repo installed per the instructions specific to the backend as written below.
42
+ - It's under the "Display Advanced Options" parameter checkbox.
43
+
44
+ #### Auto WebUI
45
+
46
+ - You must have the [AUTOMATIC1111 Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) already installed and working. Refer to that project's readme for help with that.
47
+ - Open the WebUI, go to the `Extensions` tab
48
+ - -EITHER- Option **A**:
49
+ - go to the `Available` tab with
50
+ - click `Load from` (with the default list)
51
+ - Scroll down to find `Dynamic Thresholding (CFG Scale Fix)`, or use `CTRL+F` to find it
52
+ - -OR- Option **B**:
53
+ - Click on `Install from URL`
54
+ - Copy/paste this project's URL into the `URL for extension's git repository` textbox: `https://github.com/mcmonkeyprojects/sd-dynamic-thresholding`
55
+ - Click `Install`
56
+ - Restart or reload the WebUI
57
+ - Go to txt2img or img2img
58
+ - Check the `Enable Dynamic Thresholding (CFG Scale Fix)` box
59
+ - Read the info on-page and set the sliders where you want em.
60
+ - Click generate.
61
+
62
+
63
+ #### ComfyUI
64
+
65
+ - Must have [ComfyUI](https://github.com/comfyanonymous/ComfyUI) already installed and working. Refer to that project's readme for help with that.
66
+ - -EITHER- Option **A**: (TODO: Manager install)
67
+ - -OR- Option **B**:
68
+ - `cd ComfyUI/custom_nodes`
69
+ - `git clone https://github.com/mcmonkeyprojects/sd-dynamic-thresholding`
70
+ - restart ComfyUI
71
+ - Add node `advanced/mcmonkey/DynamicThresholdingSimple` (or `Full`)
72
+ - Link your model to the input, and then link the output model to your KSampler's input
73
+
74
+ ![img](github/comfy_node.png)
75
+
76
+ --------------
77
+
78
+ ### Supported Auto WebUI Extensions
79
+
80
+ - This can be configured within the [Infinity Grid Generator](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script#supported-extensions) extension, see the readme of that project for details.
81
+
82
+ ### ComfyUI Compatibility
83
+
84
+ - This would work with any variant of the `KSampler` node, including custom ones, so long as they do not totally override the internal sampling function (most don't).
85
+
86
+ ----------------------
87
+
88
+ ### Licensing pre-note:
89
+
90
+ This is an open source project, provided entirely freely, for everyone to use and contribute to.
91
+
92
+ If you make any changes that could benefit the community as a whole, please contribute upstream.
93
+
94
+ ### The short of the license is:
95
+
96
+ You can do basically whatever you want, except you may not hold any developer liable for what you do with the software.
97
+
98
+ ### The long version of the license follows:
99
+
100
+ The MIT License (MIT)
101
+
102
+ Copyright (c) 2023 Alex "mcmonkey" Goodwin
103
+
104
+ Permission is hereby granted, free of charge, to any person obtaining a copy
105
+ of this software and associated documentation files (the "Software"), to deal
106
+ in the Software without restriction, including without limitation the rights
107
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
108
+ copies of the Software, and to permit persons to whom the Software is
109
+ furnished to do so, subject to the following conditions:
110
+
111
+ The above copyright notice and this permission notice shall be included in all
112
+ copies or substantial portions of the Software.
113
+
114
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
115
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
116
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
117
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
118
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
119
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
120
+ SOFTWARE.
extensionsa/1-sd-dynamic-thresholding/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from . import dynthres_comfyui
2
+
3
+ NODE_CLASS_MAPPINGS = {
4
+ "DynamicThresholdingSimple": dynthres_comfyui.DynamicThresholdingSimpleComfyNode,
5
+ "DynamicThresholdingFull": dynthres_comfyui.DynamicThresholdingComfyNode,
6
+ }
extensionsa/1-sd-dynamic-thresholding/__pycache__/dynthres_core.cpython-310.pyc ADDED
Binary file (4.49 kB). View file
 
extensionsa/1-sd-dynamic-thresholding/__pycache__/dynthres_unipc.cpython-310.pyc ADDED
Binary file (4.92 kB). View file
 
extensionsa/1-sd-dynamic-thresholding/dynthres_comfyui.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .dynthres_core import DynThresh
2
+
3
+ class DynamicThresholdingComfyNode:
4
+
5
+ @classmethod
6
+ def INPUT_TYPES(s):
7
+ return {
8
+ "required": {
9
+ "model": ("MODEL",),
10
+ "mimic_scale": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0, "step": 0.5}),
11
+ "threshold_percentile": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
12
+ "mimic_mode": (DynThresh.Modes, ),
13
+ "mimic_scale_min": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.5}),
14
+ "cfg_mode": (DynThresh.Modes, ),
15
+ "cfg_scale_min": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.5}),
16
+ "sched_val": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.01}),
17
+ "separate_feature_channels": (["enable", "disable"], ),
18
+ "scaling_startpoint": (DynThresh.Startpoints, ),
19
+ "variability_measure": (DynThresh.Variabilities, ),
20
+ "interpolate_phi": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
21
+ }
22
+ }
23
+
24
+ RETURN_TYPES = ("MODEL",)
25
+ FUNCTION = "patch"
26
+ CATEGORY = "advanced/mcmonkey"
27
+
28
+ def patch(self, model, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, separate_feature_channels, scaling_startpoint, variability_measure, interpolate_phi):
29
+
30
+ dynamic_thresh = DynThresh(mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, 0, 999, separate_feature_channels == "enable", scaling_startpoint, variability_measure, interpolate_phi)
31
+
32
+ def sampler_dyn_thresh(args):
33
+ input = args["input"]
34
+ cond = input - args["cond"]
35
+ uncond = input - args["uncond"]
36
+ cond_scale = args["cond_scale"]
37
+ time_step = model.model.model_sampling.timestep(args["sigma"])
38
+ time_step = time_step[0].item()
39
+ dynamic_thresh.step = 999 - time_step
40
+
41
+ if cond_scale == mimic_scale:
42
+ return input - (uncond + (cond - uncond) * cond_scale)
43
+ else:
44
+ return input - dynamic_thresh.dynthresh(cond, uncond, cond_scale, None)
45
+
46
+ m = model.clone()
47
+ m.set_model_sampler_cfg_function(sampler_dyn_thresh)
48
+ return (m, )
49
+
50
+ class DynamicThresholdingSimpleComfyNode:
51
+
52
+ @classmethod
53
+ def INPUT_TYPES(s):
54
+ return {
55
+ "required": {
56
+ "model": ("MODEL",),
57
+ "mimic_scale": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0, "step": 0.5}),
58
+ "threshold_percentile": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
59
+ }
60
+ }
61
+
62
+ RETURN_TYPES = ("MODEL",)
63
+ FUNCTION = "patch"
64
+ CATEGORY = "advanced/mcmonkey"
65
+
66
+ def patch(self, model, mimic_scale, threshold_percentile):
67
+
68
+ dynamic_thresh = DynThresh(mimic_scale, threshold_percentile, "CONSTANT", 0, "CONSTANT", 0, 0, 0, 999, False, "MEAN", "AD", 1)
69
+
70
+ def sampler_dyn_thresh(args):
71
+ input = args["input"]
72
+ cond = input - args["cond"]
73
+ uncond = input - args["uncond"]
74
+ cond_scale = args["cond_scale"]
75
+ time_step = model.model.model_sampling.timestep(args["sigma"])
76
+ time_step = time_step[0].item()
77
+ dynamic_thresh.step = 999 - time_step
78
+
79
+ if cond_scale == mimic_scale:
80
+ return input - (uncond + (cond - uncond) * cond_scale)
81
+ else:
82
+ return input - dynamic_thresh.dynthresh(cond, uncond, cond_scale, None)
83
+
84
+ m = model.clone()
85
+ m.set_model_sampler_cfg_function(sampler_dyn_thresh)
86
+ return (m, )
extensionsa/1-sd-dynamic-thresholding/dynthres_core.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, math
2
+
3
+ ######################### DynThresh Core #########################
4
+
5
+ class DynThresh:
6
+
7
+ Modes = ["Constant", "Linear Down", "Cosine Down", "Half Cosine Down", "Linear Up", "Cosine Up", "Half Cosine Up", "Power Up", "Power Down", "Linear Repeating", "Cosine Repeating", "Sawtooth"]
8
+ Startpoints = ["MEAN", "ZERO"]
9
+ Variabilities = ["AD", "STD"]
10
+
11
+ def __init__(self, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, experiment_mode, max_steps, separate_feature_channels, scaling_startpoint, variability_measure, interpolate_phi):
12
+ self.mimic_scale = mimic_scale
13
+ self.threshold_percentile = threshold_percentile
14
+ self.mimic_mode = mimic_mode
15
+ self.cfg_mode = cfg_mode
16
+ self.max_steps = max_steps
17
+ self.cfg_scale_min = cfg_scale_min
18
+ self.mimic_scale_min = mimic_scale_min
19
+ self.experiment_mode = experiment_mode
20
+ self.sched_val = sched_val
21
+ self.sep_feat_channels = separate_feature_channels
22
+ self.scaling_startpoint = scaling_startpoint
23
+ self.variability_measure = variability_measure
24
+ self.interpolate_phi = interpolate_phi
25
+
26
+ def interpret_scale(self, scale, mode, min):
27
+ scale -= min
28
+ max = self.max_steps - 1
29
+ frac = self.step / max
30
+ if mode == "Constant":
31
+ pass
32
+ elif mode == "Linear Down":
33
+ scale *= 1.0 - frac
34
+ elif mode == "Half Cosine Down":
35
+ scale *= math.cos(frac)
36
+ elif mode == "Cosine Down":
37
+ scale *= math.cos(frac * 1.5707)
38
+ elif mode == "Linear Up":
39
+ scale *= frac
40
+ elif mode == "Half Cosine Up":
41
+ scale *= 1.0 - math.cos(frac)
42
+ elif mode == "Cosine Up":
43
+ scale *= 1.0 - math.cos(frac * 1.5707)
44
+ elif mode == "Power Up":
45
+ scale *= math.pow(frac, self.sched_val)
46
+ elif mode == "Power Down":
47
+ scale *= 1.0 - math.pow(frac, self.sched_val)
48
+ elif mode == "Linear Repeating":
49
+ portion = (frac * self.sched_val) % 1.0
50
+ scale *= (0.5 - portion) * 2 if portion < 0.5 else (portion - 0.5) * 2
51
+ elif mode == "Cosine Repeating":
52
+ scale *= math.cos(frac * 6.28318 * self.sched_val) * 0.5 + 0.5
53
+ elif mode == "Sawtooth":
54
+ scale *= (frac * self.sched_val) % 1.0
55
+ scale += min
56
+ return scale
57
+
58
+ def dynthresh(self, cond, uncond, cfg_scale, weights):
59
+ mimic_scale = self.interpret_scale(self.mimic_scale, self.mimic_mode, self.mimic_scale_min)
60
+ cfg_scale = self.interpret_scale(cfg_scale, self.cfg_mode, self.cfg_scale_min)
61
+ # uncond shape is (batch, 4, height, width)
62
+ conds_per_batch = cond.shape[0] / uncond.shape[0]
63
+ assert conds_per_batch == int(conds_per_batch), "Expected # of conds per batch to be constant across batches"
64
+ cond_stacked = cond.reshape((-1, int(conds_per_batch)) + uncond.shape[1:])
65
+
66
+ ### Normal first part of the CFG Scale logic, basically
67
+ diff = cond_stacked - uncond.unsqueeze(1)
68
+ if weights is not None:
69
+ diff = diff * weights
70
+ relative = diff.sum(1)
71
+
72
+ ### Get the normal result for both mimic and normal scale
73
+ mim_target = uncond + relative * mimic_scale
74
+ cfg_target = uncond + relative * cfg_scale
75
+ ### If we weren't doing mimic scale, we'd just return cfg_target here
76
+
77
+ ### Now recenter the values relative to their average rather than absolute, to allow scaling from average
78
+ mim_flattened = mim_target.flatten(2)
79
+ cfg_flattened = cfg_target.flatten(2)
80
+ mim_means = mim_flattened.mean(dim=2).unsqueeze(2)
81
+ cfg_means = cfg_flattened.mean(dim=2).unsqueeze(2)
82
+ mim_centered = mim_flattened - mim_means
83
+ cfg_centered = cfg_flattened - cfg_means
84
+
85
+ if self.sep_feat_channels:
86
+ if self.variability_measure == 'STD':
87
+ mim_scaleref = mim_centered.std(dim=2).unsqueeze(2)
88
+ cfg_scaleref = cfg_centered.std(dim=2).unsqueeze(2)
89
+ else: # 'AD'
90
+ mim_scaleref = mim_centered.abs().max(dim=2).values.unsqueeze(2)
91
+ cfg_scaleref = torch.quantile(cfg_centered.abs(), self.threshold_percentile, dim=2).unsqueeze(2)
92
+
93
+ else:
94
+ if self.variability_measure == 'STD':
95
+ mim_scaleref = mim_centered.std()
96
+ cfg_scaleref = cfg_centered.std()
97
+ else: # 'AD'
98
+ mim_scaleref = mim_centered.abs().max()
99
+ cfg_scaleref = torch.quantile(cfg_centered.abs(), self.threshold_percentile)
100
+
101
+ if self.scaling_startpoint == 'ZERO':
102
+ scaling_factor = mim_scaleref / cfg_scaleref
103
+ result = cfg_flattened * scaling_factor
104
+
105
+ else: # 'MEAN'
106
+ if self.variability_measure == 'STD':
107
+ cfg_renormalized = (cfg_centered / cfg_scaleref) * mim_scaleref
108
+ else: # 'AD'
109
+ ### Get the maximum value of all datapoints (with an optional threshold percentile on the uncond)
110
+ max_scaleref = torch.maximum(mim_scaleref, cfg_scaleref)
111
+ ### Clamp to the max
112
+ cfg_clamped = cfg_centered.clamp(-max_scaleref, max_scaleref)
113
+ ### Now shrink from the max to normalize and grow to the mimic scale (instead of the CFG scale)
114
+ cfg_renormalized = (cfg_clamped / max_scaleref) * mim_scaleref
115
+
116
+ ### Now add it back onto the averages to get into real scale again and return
117
+ result = cfg_renormalized + cfg_means
118
+
119
+ actual_res = result.unflatten(2, mim_target.shape[2:])
120
+
121
+ if self.interpolate_phi != 1.0:
122
+ actual_res = actual_res * self.interpolate_phi + cfg_target * (1.0 - self.interpolate_phi)
123
+
124
+ if self.experiment_mode == 1:
125
+ num = actual_res.cpu().numpy()
126
+ for y in range(0, 64):
127
+ for x in range (0, 64):
128
+ if num[0][0][y][x] > 1.0:
129
+ num[0][1][y][x] *= 0.5
130
+ if num[0][1][y][x] > 1.0:
131
+ num[0][1][y][x] *= 0.5
132
+ if num[0][2][y][x] > 1.5:
133
+ num[0][2][y][x] *= 0.5
134
+ actual_res = torch.from_numpy(num).to(device=uncond.device)
135
+ elif self.experiment_mode == 2:
136
+ num = actual_res.cpu().numpy()
137
+ for y in range(0, 64):
138
+ for x in range (0, 64):
139
+ over_scale = False
140
+ for z in range(0, 4):
141
+ if abs(num[0][z][y][x]) > 1.5:
142
+ over_scale = True
143
+ if over_scale:
144
+ for z in range(0, 4):
145
+ num[0][z][y][x] *= 0.7
146
+ actual_res = torch.from_numpy(num).to(device=uncond.device)
147
+ elif self.experiment_mode == 3:
148
+ coefs = torch.tensor([
149
+ # R G B W
150
+ [0.298, 0.207, 0.208, 0.0], # L1
151
+ [0.187, 0.286, 0.173, 0.0], # L2
152
+ [-0.158, 0.189, 0.264, 0.0], # L3
153
+ [-0.184, -0.271, -0.473, 1.0], # L4
154
+ ], device=uncond.device)
155
+ res_rgb = torch.einsum("laxy,ab -> lbxy", actual_res, coefs)
156
+ max_r, max_g, max_b, max_w = res_rgb[0][0].max(), res_rgb[0][1].max(), res_rgb[0][2].max(), res_rgb[0][3].max()
157
+ max_rgb = max(max_r, max_g, max_b)
158
+ print(f"test max = r={max_r}, g={max_g}, b={max_b}, w={max_w}, rgb={max_rgb}")
159
+ if self.step / (self.max_steps - 1) > 0.2:
160
+ if max_rgb < 2.0 and max_w < 3.0:
161
+ res_rgb /= max_rgb / 2.4
162
+ else:
163
+ if max_rgb > 2.4 and max_w > 3.0:
164
+ res_rgb /= max_rgb / 2.4
165
+ actual_res = torch.einsum("laxy,ab -> lbxy", res_rgb, coefs.inverse())
166
+
167
+ return actual_res
extensionsa/1-sd-dynamic-thresholding/dynthres_unipc.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import math
4
+ import traceback
5
+ from modules import shared
6
+ try:
7
+ from modules.models.diffusion import uni_pc
8
+ except Exception as e:
9
+ from modules import unipc as uni_pc
10
+
11
+ ######################### UniPC Implementation logic #########################
12
+
13
+ # The majority of this is straight from modules.models/diffusion/uni_pc/sampler.py
14
+ # Unfortunately that's not an easy middle-injection point, so, just copypasta'd it all
15
+ # It's like they designed it to intentionally be as difficult to inject into as possible :(
16
+ # (It has hooks but not in useful locations)
17
+ # I stripped the original comments for brevity.
18
+ # Some never-used code (scheduler modes, noise modes, guidance modes) have been removed as well for brevity.
19
+ # The actual impl comes down to just the last line in particular, and the `before_sample` insert to track step count.
20
+
21
+ class CustomUniPCSampler(uni_pc.sampler.UniPCSampler):
22
+ def __init__(self, model, **kwargs):
23
+ super().__init__(model, *kwargs)
24
+ @torch.no_grad()
25
+ def sample(self, S, batch_size, shape, conditioning=None, callback=None, normals_sequence=None, img_callback=None,
26
+ quantize_x0=False, eta=0., mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None,
27
+ corrector_kwargs=None, verbose=True, x_T=None, log_every_t=100, unconditional_guidance_scale=1.,
28
+ unconditional_conditioning=None, **kwargs):
29
+ if conditioning is not None:
30
+ if isinstance(conditioning, dict):
31
+ ctmp = conditioning[list(conditioning.keys())[0]]
32
+ while isinstance(ctmp, list): ctmp = ctmp[0]
33
+ cbs = ctmp.shape[0]
34
+ if cbs != batch_size:
35
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
36
+
37
+ elif isinstance(conditioning, list):
38
+ for ctmp in conditioning:
39
+ if ctmp.shape[0] != batch_size:
40
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
41
+ else:
42
+ if conditioning.shape[0] != batch_size:
43
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
44
+ C, H, W = shape
45
+ size = (batch_size, C, H, W)
46
+ device = self.model.betas.device
47
+ if x_T is None:
48
+ img = torch.randn(size, device=device)
49
+ else:
50
+ img = x_T
51
+ ns = uni_pc.uni_pc.NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)
52
+ model_type = "v" if self.model.parameterization == "v" else "noise"
53
+ model_fn = CustomUniPC_model_wrapper(lambda x, t, c: self.model.apply_model(x, t, c), ns, model_type=model_type, guidance_scale=unconditional_guidance_scale, dt_data=self.main_class)
54
+ self.main_class.step = 0
55
+ def before_sample(x, t, cond, uncond):
56
+ self.main_class.step += 1
57
+ return self.before_sample(x, t, cond, uncond)
58
+ uni_pc_inst = uni_pc.uni_pc.UniPC(model_fn, ns, predict_x0=True, thresholding=False, variant=shared.opts.uni_pc_variant, condition=conditioning, unconditional_condition=unconditional_conditioning, before_sample=before_sample, after_sample=self.after_sample, after_update=self.after_update)
59
+ x = uni_pc_inst.sample(img, steps=S, skip_type=shared.opts.uni_pc_skip_type, method="multistep", order=shared.opts.uni_pc_order, lower_order_final=shared.opts.uni_pc_lower_order_final)
60
+ return x.to(device), None
61
+
62
+ def CustomUniPC_model_wrapper(model, noise_schedule, model_type="noise", model_kwargs={}, guidance_scale=1.0, dt_data=None):
63
+ def expand_dims(v, dims):
64
+ return v[(...,) + (None,)*(dims - 1)]
65
+ def get_model_input_time(t_continuous):
66
+ return (t_continuous - 1. / noise_schedule.total_N) * 1000.
67
+ def noise_pred_fn(x, t_continuous, cond=None):
68
+ if t_continuous.reshape((-1,)).shape[0] == 1:
69
+ t_continuous = t_continuous.expand((x.shape[0]))
70
+ t_input = get_model_input_time(t_continuous)
71
+ if cond is None:
72
+ output = model(x, t_input, None, **model_kwargs)
73
+ else:
74
+ output = model(x, t_input, cond, **model_kwargs)
75
+ if model_type == "noise":
76
+ return output
77
+ elif model_type == "v":
78
+ alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
79
+ dims = x.dim()
80
+ return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
81
+ def model_fn(x, t_continuous, condition, unconditional_condition):
82
+ if t_continuous.reshape((-1,)).shape[0] == 1:
83
+ t_continuous = t_continuous.expand((x.shape[0]))
84
+ if guidance_scale == 1. or unconditional_condition is None:
85
+ return noise_pred_fn(x, t_continuous, cond=condition)
86
+ else:
87
+ x_in = torch.cat([x] * 2)
88
+ t_in = torch.cat([t_continuous] * 2)
89
+ if isinstance(condition, dict):
90
+ assert isinstance(unconditional_condition, dict)
91
+ c_in = dict()
92
+ for k in condition:
93
+ if isinstance(condition[k], list):
94
+ c_in[k] = [torch.cat([
95
+ unconditional_condition[k][i],
96
+ condition[k][i]]) for i in range(len(condition[k]))]
97
+ else:
98
+ c_in[k] = torch.cat([
99
+ unconditional_condition[k],
100
+ condition[k]])
101
+ elif isinstance(condition, list):
102
+ c_in = list()
103
+ assert isinstance(unconditional_condition, list)
104
+ for i in range(len(condition)):
105
+ c_in.append(torch.cat([unconditional_condition[i], condition[i]]))
106
+ else:
107
+ c_in = torch.cat([unconditional_condition, condition])
108
+ noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
109
+ #return noise_uncond + guidance_scale * (noise - noise_uncond)
110
+ return dt_data.dynthresh(noise, noise_uncond, guidance_scale, None)
111
+ return model_fn
extensionsa/1-sd-dynamic-thresholding/github/cat_demo_1.jpg ADDED
extensionsa/1-sd-dynamic-thresholding/github/comfy_node.png ADDED
extensionsa/1-sd-dynamic-thresholding/github/grid_preview.png ADDED
extensionsa/1-sd-dynamic-thresholding/github/ui.png ADDED
extensionsa/1-sd-dynamic-thresholding/javascript/active.js ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ let dynthres_update_enabled = function() {
2
+ return Array.from(arguments);
3
+ };
4
+
5
+ (function(){
6
+ let accordions = {};
7
+ let enabled = {};
8
+ onUiUpdate(() => {
9
+ let accordion_id_prefix = "#dynthres_";
10
+ let extension_checkbox_class = ".dynthres-enabled";
11
+
12
+ dynthres_update_enabled = function() {
13
+ let res = Array.from(arguments);
14
+ let tabname = res[1] ? "img2img" : "txt2img";
15
+
16
+ let checkbox = accordions[tabname]?.querySelector(extension_checkbox_class + ' input');
17
+ checkbox?.dispatchEvent(new Event('change'));
18
+
19
+ return res;
20
+ };
21
+
22
+ function attachEnabledButtonListener(checkbox, accordion) {
23
+ let span = accordion.querySelector('.label-wrap span');
24
+ let badge = document.createElement('input');
25
+ badge.type = "checkbox";
26
+ badge.checked = checkbox.checked;
27
+ badge.addEventListener('click', (e) => {
28
+ checkbox.checked = !checkbox.checked;
29
+ badge.checked = checkbox.checked;
30
+ checkbox.dispatchEvent(new Event('change'));
31
+ e.stopPropagation();
32
+ });
33
+
34
+ badge.className = checkbox.className;
35
+ badge.classList.add('primary');
36
+ span.insertBefore(badge, span.firstChild);
37
+ let space = document.createElement('span');
38
+ space.innerHTML = "&nbsp;";
39
+ span.insertBefore(space, badge.nextSibling);
40
+
41
+ checkbox.addEventListener('change', () => {
42
+ let badge = accordion.querySelector('.label-wrap span input');
43
+ badge.checked = checkbox.checked;
44
+ });
45
+ checkbox.parentNode.style.display = "none";
46
+ }
47
+
48
+ if (Object.keys(accordions).length < 2) {
49
+ let accordion = gradioApp().querySelector(accordion_id_prefix + 'txt2img');
50
+ if (accordion) {
51
+ accordions.txt2img = accordion;
52
+ }
53
+ accordion = gradioApp().querySelector(accordion_id_prefix + 'img2img');
54
+ if (accordion) {
55
+ accordions.img2img = accordion;
56
+ }
57
+ }
58
+
59
+ if (Object.keys(accordions).length > 0 && accordions.txt2img && !enabled.txt2img) {
60
+ enabled.txt2img = accordions.txt2img.querySelector(extension_checkbox_class + ' input');
61
+ attachEnabledButtonListener(enabled.txt2img, accordions.txt2img);
62
+ }
63
+ if (Object.keys(accordions).length > 0 && accordions.img2img && !enabled.img2img) {
64
+ enabled.img2img = accordions.img2img.querySelector(extension_checkbox_class + ' input');
65
+ attachEnabledButtonListener(enabled.img2img, accordions.img2img);
66
+ }
67
+ });
68
+ })();
extensionsa/1-sd-dynamic-thresholding/pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "sd-dynamic-thresholding"
3
+ description = "Adds nodes for Dynamic Thresholding, CFG scheduling, and related techniques"
4
+ version = "1.0.1"
5
+ license = { file = "LICENSE.txt" }
6
+
7
+ [project.urls]
8
+ Repository = "https://github.com/mcmonkeyprojects/sd-dynamic-thresholding"
9
+
10
+ [tool.comfy]
11
+ PublisherId = "mcmonkey"
12
+ DisplayName = "Dynamic Thresholding"
13
+ Icon = ""
extensionsa/1-sd-dynamic-thresholding/scripts/__pycache__/dynamic_thresholding.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
extensionsa/1-sd-dynamic-thresholding/scripts/dynamic_thresholding.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##################
2
+ # Stable Diffusion Dynamic Thresholding (CFG Scale Fix)
3
+ #
4
+ # Author: Alex 'mcmonkey' Goodwin
5
+ # GitHub URL: https://github.com/mcmonkeyprojects/sd-dynamic-thresholding
6
+ # Created: 2022/01/26
7
+ # Last updated: 2023/01/30
8
+ #
9
+ # For usage help, view the README.md file in the extension root, or via the GitHub page.
10
+ #
11
+ ##################
12
+
13
+ import gradio as gr
14
+ import torch, traceback
15
+ import dynthres_core
16
+ from modules import scripts, script_callbacks, sd_samplers, sd_samplers_compvis, sd_samplers_common
17
+ try:
18
+ import dynthres_unipc
19
+ except Exception as e:
20
+ print(f"\n\n======\nError! UniPC sampler support failed to load! Is your WebUI up to date?\n(Error: {e})\n======")
21
+ try:
22
+ from modules.sd_samplers_kdiffusion import CFGDenoiserKDiffusion as cfgdenoisekdiff
23
+ IS_AUTO_16 = True
24
+ except Exception as e:
25
+ print(f"\n\n======\nWarning! Using legacy KDiff version! Is your WebUI up to date?\n======")
26
+ from modules.sd_samplers_kdiffusion import CFGDenoiser as cfgdenoisekdiff
27
+ IS_AUTO_16 = False
28
+
29
+ DISABLE_VISIBILITY = True
30
+
31
+ ######################### Data values #########################
32
+ MODES_WITH_VALUE = ["Power Up", "Power Down", "Linear Repeating", "Cosine Repeating", "Sawtooth"]
33
+
34
+ ######################### Script class entrypoint #########################
35
+ class Script(scripts.Script):
36
+
37
+ def title(self):
38
+ return "Dynamic Thresholding (CFG Scale Fix)"
39
+
40
+ def show(self, is_img2img):
41
+ return scripts.AlwaysVisible
42
+
43
+ def ui(self, is_img2img):
44
+ def vis_change(is_vis):
45
+ return {"visible": is_vis, "__type__": "update"}
46
+ # "Dynamic Thresholding (CFG Scale Fix)"
47
+ dtrue = gr.Checkbox(value=True, visible=False)
48
+ dfalse = gr.Checkbox(value=False, visible=False)
49
+ with gr.Accordion("Dynamic Thresholding (CFG Scale Fix)", open=False, elem_id="dynthres_" + ("img2img" if is_img2img else "txt2img")):
50
+ with gr.Row():
51
+ enabled = gr.Checkbox(value=False, label="Enable Dynamic Thresholding (CFG Scale Fix)", elem_classes=["dynthres-enabled"], elem_id='dynthres_enabled')
52
+ with gr.Group():
53
+ gr.HTML(value=f"View <a style=\"border-bottom: 1px #00ffff dotted;\" href=\"https://github.com/mcmonkeyprojects/sd-dynamic-thresholding/wiki/Usage-Tips\">the wiki for usage tips.</a><br><br>", elem_id='dynthres_wiki_link')
54
+ mimic_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='Mimic CFG Scale', value=7.0, elem_id='dynthres_mimic_scale')
55
+ with gr.Accordion("Advanced Options", open=False, elem_id='dynthres_advanced_opts'):
56
+ with gr.Row():
57
+ threshold_percentile = gr.Slider(minimum=90.0, value=100.0, maximum=100.0, step=0.05, label='Top percentile of latents to clamp', elem_id='dynthres_threshold_percentile')
58
+ interpolate_phi = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Interpolate Phi", value=1.0, elem_id='dynthres_interpolate_phi')
59
+ with gr.Row():
60
+ mimic_mode = gr.Dropdown(dynthres_core.DynThresh.Modes, value="Constant", label="Mimic Scale Scheduler", elem_id='dynthres_mimic_mode')
61
+ cfg_mode = gr.Dropdown(dynthres_core.DynThresh.Modes, value="Constant", label="CFG Scale Scheduler", elem_id='dynthres_cfg_mode')
62
+ mimic_scale_min = gr.Slider(minimum=0.0, maximum=30.0, step=0.5, visible=DISABLE_VISIBILITY, label="Minimum value of the Mimic Scale Scheduler", elem_id='dynthres_mimic_scale_min')
63
+ cfg_scale_min = gr.Slider(minimum=0.0, maximum=30.0, step=0.5, visible=DISABLE_VISIBILITY, label="Minimum value of the CFG Scale Scheduler", elem_id='dynthres_cfg_scale_min')
64
+ sched_val = gr.Slider(minimum=0.0, maximum=40.0, step=0.5, value=4.0, visible=DISABLE_VISIBILITY, label="Scheduler Value", info="Value unique to the scheduler mode - for Power Up/Down, this is the power. For Linear/Cosine Repeating, this is the number of repeats per image.", elem_id='dynthres_sched_val')
65
+ with gr.Row():
66
+ separate_feature_channels = gr.Checkbox(value=True, label="Separate Feature Channels", elem_id='dynthres_separate_feature_channels')
67
+ scaling_startpoint = gr.Radio(["ZERO", "MEAN"], value="MEAN", label="Scaling Startpoint")
68
+ variability_measure = gr.Radio(["STD", "AD"], value="AD", label="Variability Measure")
69
+ def should_show_scheduler_value(cfg_mode, mimic_mode):
70
+ sched_vis = cfg_mode in MODES_WITH_VALUE or mimic_mode in MODES_WITH_VALUE or DISABLE_VISIBILITY
71
+ return vis_change(sched_vis), vis_change(mimic_mode != "Constant" or DISABLE_VISIBILITY), vis_change(cfg_mode != "Constant" or DISABLE_VISIBILITY)
72
+ cfg_mode.change(should_show_scheduler_value, inputs=[cfg_mode, mimic_mode], outputs=[sched_val, mimic_scale_min, cfg_scale_min])
73
+ mimic_mode.change(should_show_scheduler_value, inputs=[cfg_mode, mimic_mode], outputs=[sched_val, mimic_scale_min, cfg_scale_min])
74
+ enabled.change(
75
+ _js="dynthres_update_enabled",
76
+ fn=None,
77
+ inputs=[enabled, dtrue if is_img2img else dfalse],
78
+ show_progress = False)
79
+ self.infotext_fields = (
80
+ (enabled, lambda d: gr.Checkbox.update(value="Dynamic thresholding enabled" in d)),
81
+ (mimic_scale, "Mimic scale"),
82
+ (separate_feature_channels, "Separate Feature Channels"),
83
+ (scaling_startpoint, lambda d: gr.Radio.update(value=d.get("Scaling Startpoint", "MEAN"))),
84
+ (variability_measure, lambda d: gr.Radio.update(value=d.get("Variability Measure", "AD"))),
85
+ (interpolate_phi, "Interpolate Phi"),
86
+ (threshold_percentile, "Threshold percentile"),
87
+ (mimic_scale_min, "Mimic scale minimum"),
88
+ (mimic_mode, lambda d: gr.Dropdown.update(value=d.get("Mimic mode", "Constant"))),
89
+ (cfg_mode, lambda d: gr.Dropdown.update(value=d.get("CFG mode", "Constant"))),
90
+ (cfg_scale_min, "CFG scale minimum"),
91
+ (sched_val, "Scheduler value"))
92
+ return [enabled, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, separate_feature_channels, scaling_startpoint, variability_measure, interpolate_phi]
93
+
94
+ last_id = 0
95
+
96
+ def process_batch(self, p, enabled, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, separate_feature_channels, scaling_startpoint, variability_measure, interpolate_phi, batch_number, prompts, seeds, subseeds):
97
+ enabled = getattr(p, 'dynthres_enabled', enabled)
98
+ if not enabled:
99
+ return
100
+ orig_sampler_name = p.sampler_name
101
+ orig_latent_sampler_name = getattr(p, 'latent_sampler', None)
102
+ if orig_sampler_name in ["DDIM", "PLMS"]:
103
+ raise RuntimeError(f"Cannot use sampler {orig_sampler_name} with Dynamic Thresholding")
104
+ if orig_latent_sampler_name in ["DDIM", "PLMS"]:
105
+ raise RuntimeError(f"Cannot use secondary sampler {orig_latent_sampler_name} with Dynamic Thresholding")
106
+ if 'UniPC' in (orig_sampler_name, orig_latent_sampler_name) and p.enable_hr:
107
+ raise RuntimeError(f"UniPC does not support Hires Fix. Auto WebUI silently swaps to DDIM for this, which DynThresh does not support. Please swap to a sampler capable of img2img processing for HR Fix to work.")
108
+ mimic_scale = getattr(p, 'dynthres_mimic_scale', mimic_scale)
109
+ separate_feature_channels = getattr(p, 'dynthres_separate_feature_channels', separate_feature_channels)
110
+ scaling_startpoint = getattr(p, 'dynthres_scaling_startpoint', scaling_startpoint)
111
+ variability_measure = getattr(p, 'dynthres_variability_measure', variability_measure)
112
+ interpolate_phi = getattr(p, 'dynthres_interpolate_phi', interpolate_phi)
113
+ threshold_percentile = getattr(p, 'dynthres_threshold_percentile', threshold_percentile)
114
+ mimic_mode = getattr(p, 'dynthres_mimic_mode', mimic_mode)
115
+ mimic_scale_min = getattr(p, 'dynthres_mimic_scale_min', mimic_scale_min)
116
+ cfg_mode = getattr(p, 'dynthres_cfg_mode', cfg_mode)
117
+ cfg_scale_min = getattr(p, 'dynthres_cfg_scale_min', cfg_scale_min)
118
+ experiment_mode = getattr(p, 'dynthres_experiment_mode', 0)
119
+ sched_val = getattr(p, 'dynthres_scheduler_val', sched_val)
120
+ p.extra_generation_params["Dynamic thresholding enabled"] = True
121
+ p.extra_generation_params["Mimic scale"] = mimic_scale
122
+ p.extra_generation_params["Separate Feature Channels"] = separate_feature_channels
123
+ p.extra_generation_params["Scaling Startpoint"] = scaling_startpoint
124
+ p.extra_generation_params["Variability Measure"] = variability_measure
125
+ p.extra_generation_params["Interpolate Phi"] = interpolate_phi
126
+ p.extra_generation_params["Threshold percentile"] = threshold_percentile
127
+ p.extra_generation_params["Sampler"] = orig_sampler_name
128
+ if mimic_mode != "Constant":
129
+ p.extra_generation_params["Mimic mode"] = mimic_mode
130
+ p.extra_generation_params["Mimic scale minimum"] = mimic_scale_min
131
+ if cfg_mode != "Constant":
132
+ p.extra_generation_params["CFG mode"] = cfg_mode
133
+ p.extra_generation_params["CFG scale minimum"] = cfg_scale_min
134
+ if cfg_mode in MODES_WITH_VALUE or mimic_mode in MODES_WITH_VALUE:
135
+ p.extra_generation_params["Scheduler value"] = sched_val
136
+ # Note: the ID number is to protect the edge case of multiple simultaneous runs with different settings
137
+ Script.last_id += 1
138
+ # Percentage to portion
139
+ threshold_percentile *= 0.01
140
+
141
+ def make_sampler(orig_sampler_name):
142
+ fixed_sampler_name = f"{orig_sampler_name}_dynthres{Script.last_id}"
143
+
144
+ # Make a placeholder sampler
145
+ sampler = sd_samplers.all_samplers_map[orig_sampler_name]
146
+ dt_data = dynthres_core.DynThresh(mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, experiment_mode, p.steps, separate_feature_channels, scaling_startpoint, variability_measure, interpolate_phi)
147
+ if orig_sampler_name == "UniPC":
148
+ def unipc_constructor(model):
149
+ return CustomVanillaSDSampler(dynthres_unipc.CustomUniPCSampler, model, dt_data)
150
+ new_sampler = sd_samplers_common.SamplerData(fixed_sampler_name, unipc_constructor, sampler.aliases, sampler.options)
151
+ else:
152
+ def new_constructor(model):
153
+ result = sampler.constructor(model)
154
+ cfg = CustomCFGDenoiser(result if IS_AUTO_16 else result.model_wrap_cfg.inner_model, dt_data)
155
+ result.model_wrap_cfg = cfg
156
+ return result
157
+ new_sampler = sd_samplers_common.SamplerData(fixed_sampler_name, new_constructor, sampler.aliases, sampler.options)
158
+ return fixed_sampler_name, new_sampler
159
+
160
+ # Apply for usage
161
+ p.orig_sampler_name = orig_sampler_name
162
+ p.orig_latent_sampler_name = orig_latent_sampler_name
163
+ p.fixed_samplers = []
164
+
165
+ if orig_latent_sampler_name:
166
+ latent_sampler_name, latent_sampler = make_sampler(orig_latent_sampler_name)
167
+ sd_samplers.all_samplers_map[latent_sampler_name] = latent_sampler
168
+ p.fixed_samplers.append(latent_sampler_name)
169
+ p.latent_sampler = latent_sampler_name
170
+
171
+ if orig_sampler_name != orig_latent_sampler_name:
172
+ p.sampler_name, new_sampler = make_sampler(orig_sampler_name)
173
+ sd_samplers.all_samplers_map[p.sampler_name] = new_sampler
174
+ p.fixed_samplers.append(p.sampler_name)
175
+ else:
176
+ p.sampler_name = p.latent_sampler
177
+
178
+ if p.sampler is not None:
179
+ p.sampler = sd_samplers.create_sampler(p.sampler_name, p.sd_model)
180
+
181
+ def postprocess_batch(self, p, enabled, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, separate_feature_channels, scaling_startpoint, variability_measure, interpolate_phi, batch_number, images):
182
+ if not enabled or not hasattr(p, 'orig_sampler_name'):
183
+ return
184
+ p.sampler_name = p.orig_sampler_name
185
+ if p.orig_latent_sampler_name:
186
+ p.latent_sampler = p.orig_latent_sampler_name
187
+ for added_sampler in p.fixed_samplers:
188
+ del sd_samplers.all_samplers_map[added_sampler]
189
+ del p.fixed_samplers
190
+ del p.orig_sampler_name
191
+ del p.orig_latent_sampler_name
192
+
193
+ ######################### CompVis Implementation logic #########################
194
+
195
+ class CustomVanillaSDSampler(sd_samplers_compvis.VanillaStableDiffusionSampler):
196
+ def __init__(self, constructor, sd_model, dt_data):
197
+ super().__init__(constructor, sd_model)
198
+ self.sampler.main_class = dt_data
199
+
200
+ ######################### K-Diffusion Implementation logic #########################
201
+
202
+ class CustomCFGDenoiser(cfgdenoisekdiff):
203
+ def __init__(self, model, dt_data):
204
+ super().__init__(model)
205
+ self.main_class = dt_data
206
+
207
+ def combine_denoised(self, x_out, conds_list, uncond, cond_scale):
208
+ if isinstance(uncond, dict) and 'crossattn' in uncond:
209
+ uncond = uncond['crossattn']
210
+ denoised_uncond = x_out[-uncond.shape[0]:]
211
+ # conds_list shape is (batch, cond, 2)
212
+ weights = torch.tensor(conds_list, device=uncond.device).select(2, 1)
213
+ weights = weights.reshape(*weights.shape, 1, 1, 1)
214
+ self.main_class.step = self.step
215
+ if hasattr(self, 'total_steps'):
216
+ self.main_class.max_steps = self.total_steps
217
+
218
+ if self.main_class.experiment_mode >= 4 and self.main_class.experiment_mode <= 5:
219
+ # https://arxiv.org/pdf/2305.08891.pdf "Rescale CFG". It's not good, but if you want to test it, just set experiment_mode = 4 + phi.
220
+ denoised = torch.clone(denoised_uncond)
221
+ fi = self.main_class.experiment_mode - 4.0
222
+ for i, conds in enumerate(conds_list):
223
+ for cond_index, weight in conds:
224
+ xcfg = (denoised_uncond[i] + (x_out[cond_index] - denoised_uncond[i]) * (cond_scale * weight))
225
+ xrescaled = xcfg * (torch.std(x_out[cond_index]) / torch.std(xcfg))
226
+ xfinal = fi * xrescaled + (1.0 - fi) * xcfg
227
+ denoised[i] = xfinal
228
+ return denoised
229
+
230
+ return self.main_class.dynthresh(x_out[:-uncond.shape[0]], denoised_uncond, cond_scale, weights)
231
+
232
+ ######################### XYZ Plot Script Support logic #########################
233
+
234
+ def make_axis_options():
235
+ xyz_grid = [x for x in scripts.scripts_data if x.script_class.__module__ in ("xyz_grid.py", "scripts.xyz_grid")][0].module
236
+ def apply_mimic_scale(p, x, xs):
237
+ if x != 0:
238
+ setattr(p, "dynthres_enabled", True)
239
+ setattr(p, "dynthres_mimic_scale", x)
240
+ else:
241
+ setattr(p, "dynthres_enabled", False)
242
+ def confirm_scheduler(p, xs):
243
+ for x in xs:
244
+ if x not in dynthres_core.DynThresh.Modes:
245
+ raise RuntimeError(f"Unknown Scheduler: {x}")
246
+ extra_axis_options = [
247
+ xyz_grid.AxisOption("[DynThres] Mimic Scale", float, apply_mimic_scale),
248
+ xyz_grid.AxisOption("[DynThres] Separate Feature Channels", int,
249
+ xyz_grid.apply_field("dynthres_separate_feature_channels")),
250
+ xyz_grid.AxisOption("[DynThres] Scaling Startpoint", str, xyz_grid.apply_field("dynthres_scaling_startpoint"), choices=lambda:['ZERO', 'MEAN']),
251
+ xyz_grid.AxisOption("[DynThres] Variability Measure", str, xyz_grid.apply_field("dynthres_variability_measure"), choices=lambda:['STD', 'AD']),
252
+ xyz_grid.AxisOption("[DynThres] Interpolate Phi", float, xyz_grid.apply_field("dynthres_interpolate_phi")),
253
+ xyz_grid.AxisOption("[DynThres] Threshold Percentile", float, xyz_grid.apply_field("dynthres_threshold_percentile")),
254
+ xyz_grid.AxisOption("[DynThres] Mimic Scheduler", str, xyz_grid.apply_field("dynthres_mimic_mode"), confirm=confirm_scheduler, choices=lambda: dynthres_core.DynThresh.Modes),
255
+ xyz_grid.AxisOption("[DynThres] Mimic minimum", float, xyz_grid.apply_field("dynthres_mimic_scale_min")),
256
+ xyz_grid.AxisOption("[DynThres] CFG Scheduler", str, xyz_grid.apply_field("dynthres_cfg_mode"), confirm=confirm_scheduler, choices=lambda: dynthres_core.DynThresh.Modes),
257
+ xyz_grid.AxisOption("[DynThres] CFG minimum", float, xyz_grid.apply_field("dynthres_cfg_scale_min")),
258
+ xyz_grid.AxisOption("[DynThres] Scheduler value", float, xyz_grid.apply_field("dynthres_scheduler_val"))
259
+ ]
260
+ if not any("[DynThres]" in x.label for x in xyz_grid.axis_options):
261
+ xyz_grid.axis_options.extend(extra_axis_options)
262
+
263
+ def callback_before_ui():
264
+ try:
265
+ make_axis_options()
266
+ except Exception as e:
267
+ traceback.print_exc()
268
+ print(f"Failed to add support for X/Y/Z Plot Script because: {e}")
269
+
270
+ script_callbacks.on_before_ui(callback_before_ui)
extensionsa/2-sd-webui-reactor/.github/ISSUE_TEMPLATE/bug_report.yml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Bug Report
2
+ description: You think somethings is broken
3
+ labels: ["bug", "new"]
4
+
5
+ body:
6
+ - type: checkboxes
7
+ attributes:
8
+ label: First, confirm
9
+ description: Make sure you use the latest version of the ReActor extension and you have already searched to see if an issue already exists for the bug you encountered before you create a new Issue.
10
+ options:
11
+ - label: I have read the [instruction](https://github.com/Gourieff/sd-webui-reactor/blob/main/README.md) carefully
12
+ required: true
13
+ - label: I have searched the existing issues
14
+ required: true
15
+ - label: I have updated the extension to the latest version
16
+ required: true
17
+ - type: markdown
18
+ attributes:
19
+ value: |
20
+ *Please fill this form with as much information as possible and *provide screenshots if possible**
21
+ - type: textarea
22
+ id: what-did
23
+ attributes:
24
+ label: What happened?
25
+ description: Tell what happened in a very clear and simple way
26
+ validations:
27
+ required: true
28
+ - type: textarea
29
+ id: steps
30
+ attributes:
31
+ label: Steps to reproduce the problem
32
+ description: Please provide with precise step by step instructions on how to reproduce the bug
33
+ value: |
34
+ 1. Go to ....
35
+ 2. Press ....
36
+ 3. ...
37
+ validations:
38
+ required: true
39
+ - type: textarea
40
+ id: sysinfo
41
+ attributes:
42
+ label: Sysinfo
43
+ description: Describe your platform. OS, browser, GPU, what SD WebUI you use, what version and what extensions are also enabled. If you use A1111 you can generate "System info file" (Settings -> Sysinfo) and put it here.
44
+ validations:
45
+ required: true
46
+ - type: textarea
47
+ id: logs
48
+ attributes:
49
+ label: Relevant console log
50
+ description: Please provide cmd/terminal logs from the moment you started UI to the momemt you got an error. This will be automatically formatted into code, so no need for backticks.
51
+ render: Shell
52
+ validations:
53
+ required: true
54
+ - type: textarea
55
+ id: misc
56
+ attributes:
57
+ label: Additional information
58
+ description: Please provide with any relevant additional info or context.
extensionsa/2-sd-webui-reactor/.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ blank_issues_enabled: false
2
+ contact_links:
3
+ - name: ReActor Extension Community Support
4
+ url: https://github.com/Gourieff/sd-webui-reactor/discussions
5
+ about: Please ask and answer questions here.
extensionsa/2-sd-webui-reactor/.github/ISSUE_TEMPLATE/feature_request.yml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Feature request
2
+ description: Suggest an idea for this project
3
+ title: "[Feature]: "
4
+ labels: ["enhancement", "new"]
5
+
6
+ body:
7
+ - type: textarea
8
+ id: description
9
+ attributes:
10
+ label: Feature description
11
+ description: Describe the feature in a clear and simple way
12
+ value:
13
+ - type: markdown
14
+ attributes:
15
+ value: |
16
+ The best way to propose an idea is to start a new discussion via the [Discussions](https://github.com/Gourieff/sd-webui-reactor/discussions) section (choose the "Idea" category)
extensionsa/2-sd-webui-reactor/.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.pyc
5
+
6
+ .vscode/
7
+
8
+ example
9
+ *.txt
10
+ !requirements.txt
extensionsa/2-sd-webui-reactor/API.md ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # <div align="center">ReActor Extension API</div>
2
+
3
+ <div align="center">
4
+
5
+ [Built-in SD WebUI API](#built-in-sd-webui-api) | [External ReActor API](#external-reactor-api)
6
+
7
+ ---
8
+ </div>
9
+
10
+ Gourieff's **ReActor** SD WebUI Extension allows to operate via API: both built-in and external (POST and GET requests).
11
+
12
+
13
+ ## Built-in SD WebUI API
14
+
15
+ This API is actual if you use Automatic1111 stable-diffusion-webui.
16
+
17
+ First of all - check the [SD Web API Wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/API) for how to use the API.
18
+
19
+ * Call `requests.get(url=f'{address}/sdapi/v1/script-info')` to find the args that ReActor needs;
20
+ * Define ReActor script args and add like this `"alwayson_scripts": {"reactor":{"args":args}}` in the payload;
21
+ * Call the API.
22
+
23
+ You can find the [full usage example](./example/api_example.py) with all the available parameters and discriptions in the "example" folder.
24
+
25
+ ## External ReActor API
26
+
27
+ ReActor extension supports for external calls via POST or GET requests while your SD WebUI server is working.
28
+
29
+ > :warning: Source and Target images must be "base64".
30
+
31
+ Example:
32
+
33
+ ```
34
+ curl -X POST \
35
+ 'http://127.0.0.1:7860/reactor/image' \
36
+ -H 'accept: application/json' \
37
+ -H 'Content-Type: application/json' \
38
+ -d '{
39
+ "source_image": "data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABQAAD/7g...",
40
+ "target_image": "data:image/png;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABCAAD/7g...",
41
+ "source_faces_index": [0],
42
+ "face_index": [0],
43
+ "upscaler": "4x_NMKD-Siax_200k",
44
+ "scale": 2,
45
+ "upscale_visibility": 1,
46
+ "face_restorer": "CodeFormer",
47
+ "restorer_visibility": 1,
48
+ "restore_first": 1,
49
+ "model": "inswapper_128.onnx",
50
+ "gender_source": 0,
51
+ "gender_target": 0,
52
+ "save_to_file": 0,
53
+ "result_file_path": "",
54
+ "device": "CUDA",
55
+ "mask_face": 1,
56
+ "select_source": 1,
57
+ "face_model": "elena.safetensors",
58
+ "source_folder": "C:/faces",
59
+ "random_image": 1,
60
+ "upscale_force": 1
61
+ }'
62
+ ```
63
+
64
+ * Set `"upscaler"` to `"None"` and `"scale"` to `1` if you don't need to upscale;
65
+ * Set `"save_to_file"` to `1` if you need to save result to a file;
66
+ * `"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"`;
67
+ * 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;
68
+ * Set `"select_source"` to: 0 - Image, 1 - Face Model, 2 - Source Folder;
69
+ * Set `"face_model"` to the face model file you want to choose if you set `"select_source": 1`;
70
+ * Set `"source_folder"` to the path with source images (with faces you need as the results) if you set `"select_source": 2`;
71
+ * Set `"random_image"` to `1` if want ReActor to choose a random image from the path of `"source_folder"`;
72
+ * Set `"upscale_force"` to `1` if you want ReActor to upscale the image even if no face found.
73
+
74
+ 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).
75
+
76
+ As a result you recieve a "base64" image:
77
+
78
+ ```
79
+ {"image":"iVBORw0KGgoAAAANSUhEUgAABlAAAARQCAIAAAAdiYuqAAEAAElEQVR4nOz9+ZMlSXImBn6qau4vIjKzzr5wzwBCDrm/7f+/K7IHV3ZkhUIuyZHlkBhiMGig0Y0..."}
80
+ ```
81
+
82
+ A list of available models can be seen by GET:
83
+ * http://127.0.0.1:7860/reactor/models
84
+ * http://127.0.0.1:7860/reactor/upscalers
85
+ * http://127.0.0.1:7860/reactor/facemodels
extensionsa/2-sd-webui-reactor/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
extensionsa/2-sd-webui-reactor/README.md ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_EN.png?raw=true" alt="logo" width="180px"/>
4
+
5
+ ![Version](https://img.shields.io/badge/version-0.7.1_alpha2-lightgreen?style=for-the-badge&labelColor=darkgreen)
6
+
7
+ <a href="https://boosty.to/artgourieff" target="_blank">
8
+ <img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Support Me on Boosty"/>
9
+ <br>
10
+ <sup>
11
+ Support This Project
12
+ </sup>
13
+ </a>
14
+
15
+ <hr>
16
+
17
+ [![Commit activity](https://img.shields.io/github/commit-activity/t/Gourieff/sd-webui-reactor/main?cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/commits/main)
18
+ ![Last commit](https://img.shields.io/github/last-commit/Gourieff/sd-webui-reactor/main?cacheSeconds=0)
19
+ [![Opened issues](https://img.shields.io/github/issues/Gourieff/sd-webui-reactor?color=red)](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
20
+ [![Closed issues](https://img.shields.io/github/issues-closed/Gourieff/sd-webui-reactor?color=green&cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/issues?q=is%3Aissue+is%3Aclosed)
21
+ ![License](https://img.shields.io/github/license/Gourieff/sd-webui-reactor)
22
+
23
+ English | [Русский](/README_RU.md)
24
+
25
+ # ReActor for Stable Diffusion
26
+
27
+ ### The Fast and Simple FaceSwap Extension with a lot of improvements and without NSFW filter (uncensored, use it on your own [responsibility](#disclaimer))
28
+
29
+ ---
30
+ <b>
31
+ <a href="#latestupdate">What's new</a> | <a href="#installation">Installation</a> | <a href="#features">Features</a> | <a href="#usage">Usage</a> | <a href="#api">API</a> | <a href="#troubleshooting">Troubleshooting</a> | <a href="#updating">Updating</a> | <a href="#comfyui">ComfyUI</a> | <a href="#disclaimer">Disclaimer</a>
32
+ </b>
33
+ </div>
34
+
35
+ ---
36
+
37
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
38
+
39
+ <a name="latestupdate">
40
+
41
+ ## What's new in the latest updates
42
+
43
+ <details>
44
+ <summary><a>Click to expand</a></summary>
45
+
46
+ ### 0.7.0 <sub><sup>BETA2
47
+
48
+ - 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!
49
+
50
+ <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%"/>
51
+
52
+ To use "Face Model" axis - you should enable ReActor and choose any face model as the Source:<br>
53
+ <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%"/>
54
+
55
+ Full size demo image: [xyz_demo_2.png](https://raw.githubusercontent.com/Gourieff/Assets/main/sd-webui-reactor/xyz_demo_2.png)
56
+
57
+ ### 0.7.0 <sub><sup>BETA1
58
+
59
+ - X/Y/Z Script support (up to 3 axes: CodeFormer Weight, Restorer Visibility, Face Mask Correction)
60
+
61
+ <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%"/>
62
+
63
+ <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%"/>
64
+
65
+ Full size demo image: [xyz_demo.png](https://raw.githubusercontent.com/Gourieff/Assets/main/sd-webui-reactor/xyz_demo.png)
66
+
67
+ __Don't forget to enable ReActor and set any source (to prevent "no source" error)__
68
+
69
+ ### 0.7.0 <sub><sup>ALPHA1
70
+
71
+ - You can now blend faces to build blended face models ("Tools->Face Models->Blend") - due to popular demand
72
+
73
+ <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%"/>
74
+
75
+ - CUDA 12 Support in the Installer script for 1.17.0 ORT-GPU library
76
+ - New tab "Detection" with "Threshold" and "Max Faces" parameters
77
+
78
+ ### 0.6.1 <sub><sup>BETA3
79
+
80
+ - '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)
81
+ - ReActor shows filenames of source images in-process when the multiple images mode or the folder mode (random as well) is selected
82
+
83
+ ### 0.6.1 <sub><sup>BETA2
84
+
85
+ - 'Save original' option works fine now when you select 'Multiple Images' or 'Source Folder'
86
+ - Random Mode for 'Source Folder'
87
+
88
+ <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%"/>
89
+
90
+ ### 0.6.0
91
+
92
+ - New Logo
93
+ - Adaptation to A1111 1.7.0 (appropriate GFPGAN loader)
94
+ - New URL for the main model file
95
+ - UI reworked
96
+ - You can now load several source images (with reference faces) or set the path to the folder containing faces images
97
+
98
+ <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%"/>
99
+
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%"/>
101
+
102
+ ### 0.5.1
103
+
104
+ - 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;
105
+ - "Face Mask Correction" option - if you encounter some pixelation around face contours, this option will be useful;
106
+
107
+ <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%"/>
108
+
109
+ </details>
110
+
111
+ ## Installation
112
+
113
+ [A1111 WebUI / WebUI-Forge](#a1111) | [SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
114
+
115
+ <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):
116
+
117
+ 1. (For Windows Users):
118
+ - Install **Visual Studio 2022** (Community version, for example - you need this step to build some of dependencies):
119
+ https://visualstudio.microsoft.com/downloads/
120
+ - 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":
121
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/
122
+ - OR if you don't want to install VS or VS C++ BT - follow [this steps (sec. VIII)](#insightfacebuild)
123
+ 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"
124
+ 3. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
125
+ 4. Check the last message in your SD-WebUI Console:
126
+ * 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"
127
+ * If you see the message "Done!", just reload the UI
128
+ 5. Enjoy!
129
+
130
+ <a name="sdnext">If you use [SD.Next](https://github.com/vladmandic/automatic):
131
+
132
+ 1. Close (stop) your SD WebUI Server if it's running
133
+ 2. (For Windows Users) See the [1st step](#a1111) for Automatic1111 (if you followed [this steps (sec. VIII)](#insightfacebuild) instead - go to the Step 5)
134
+ 3. Go to (Windows)`automatic\venv\Scripts` or (MacOS/Linux)`automatic/venv/bin`, run Terminal or Console (cmd) for that folder and type `activate`
135
+ 4. Run `pip install insightface==0.7.3`
136
+ 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"
137
+ 6. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
138
+ 7. Check the last message in your SD.Next Console:
139
+ * If you see the message "--- PLEASE, RESTART the Server! ---" - stop the Server (CTRL+C or CMD+C) or just close your console
140
+ 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
141
+ 9. Run your SD.Next WebUI and enjoy!
142
+
143
+ <a name="colab">If you use [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
144
+
145
+ 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"
146
+ 2. Please, wait for several minutes until the installation process will be finished (be patient, don't interrupt the process)
147
+ 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"
148
+ 4. Enjoy!
149
+
150
+ ## Features
151
+
152
+ - Very fast and accurate **face replacement (face swap)** in images
153
+ - **Multiple faces support**
154
+ - **Gender detection**
155
+ - Ability to **save original images** (made before swapping)
156
+ - **Face restoration** of a swapped face
157
+ - **Upscaling** of a resulting image
158
+ - Saving ans loading **Safetensors Face Models**
159
+ - **Facial Mask Correction** to avoid any pixelation around face contours
160
+ - Ability to set the **Postprocessing order**
161
+ - **100% compatibility** with different **SD WebUIs**: Automatic1111, SD.Next, Cagliostro Colab UI
162
+ - **Fast performance** even with CPU, ReActor for SD WebUI is absolutely not picky about how powerful your GPU is
163
+ - **CUDA** acceleration support since version 0.5.0
164
+ - **[API](/API.md) support**: both SD WebUI built-in and external (via POST/GET requests)
165
+ - **ComfyUI [support](https://github.com/Gourieff/comfyui-reactor-node)**
166
+ - **Mac M1/M2 [support](https://github.com/Gourieff/sd-webui-reactor/issues/42)**
167
+ - Console **log level control**
168
+ - **NSFW filter free** (this extension is aimed at highly developed intellectual people, not at perverts; our society must be oriented on its way towards the highest standards, not the lowest - this is the essence of development and evolution; so, my position is - that mature-minded people are clever enough to understand for themselves what is good and what is bad and take full responsibility for personal actions; for others - no "filters" will help until they do understand how Universe works)
169
+
170
+ ## Usage
171
+
172
+ > Using this software you are agree with [disclaimer](#disclaimer)
173
+
174
+ 1. Under "ReActor" drop-down menu, import an image containing a face;
175
+ 2. Turn on the "Enable" checkbox;
176
+ 3. That's it, now the generated result will have the face you selected.
177
+
178
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
179
+
180
+ ### Face Indexes
181
+
182
+ ReActor detects faces in images in the following order:<br>
183
+ left->right, top->bottom
184
+
185
+ And if you need to specify faces, you can set indexes for source and input images.
186
+
187
+ Index of the first detected face is 0.
188
+
189
+ You can set indexes in the order you need.<br>
190
+ E.g.: 0,1,2 (for Source); 1,0,2 (for Input).<br>
191
+ This means: the second Input face (index = 1) will be swapped by the first Source face (index = 0) and so on.
192
+
193
+ ### Genders
194
+
195
+ You can specify the gender to detect in images.<br>
196
+ ReActor will swap a face only if it meets the given condition.
197
+
198
+ ### The result face is blurry
199
+ Use the "Restore Face" option. You can also try the "Upscaler" option or for more finer control, use an upscaler from the "Extras" tab.
200
+ You can also set the postproduction order (from 0.1.0 version):
201
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
202
+
203
+ *The old logic was the opposite (Upscale -> then Restore), resulting in worse face quality (and big texture differences) after upscaling.*
204
+
205
+ ### There are multiple faces in result
206
+ 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.
207
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
208
+
209
+ ### ~~The result is totally black~~
210
+ ~~This means NSFW filter detected that your image is NSFW.~~
211
+
212
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
213
+
214
+ ### Img2Img
215
+
216
+ You can choose to activate the swap on the source image or on the generated image, or on both using the checkboxes. Activating on source image allows you to start from a given base and apply the diffusion process to it.
217
+
218
+ 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".
219
+
220
+ ### Extras Tab
221
+
222
+ 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
223
+
224
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
225
+
226
+ ## API
227
+
228
+ You can use ReActor with the built-in Webui API or via an external API.
229
+
230
+ Please follow **[this](/API.md)** page for the detailed instruction.
231
+
232
+ ## Troubleshooting
233
+
234
+ ### **I. "You should at least have one model in models directory"**
235
+
236
+ Please, check the path where "inswapper_128.onnx" model is stored. It must be inside the folder `stable-diffusion-webui\models\insightface`. Move the model there if it's stored in a different directory.
237
+
238
+ ### **II. Any problems with installing Insightface or other dependencies**
239
+
240
+ (for Mac M1/M2 users) If you get errors when trying to install Insightface - please read https://github.com/Gourieff/sd-webui-reactor/issues/42
241
+
242
+ (for Windows Users) If you have VS C++ Build Tools or MS VS 2022 installed but still have a problem, then try the next step:
243
+ 1. Close (stop) your SD WebUI Server and start it again
244
+
245
+ (for Any OS Users) If the problem still there, then do the following:
246
+ 1. Close (stop) your SD WebUI Server if it's running
247
+ 2. Go to (Windows)`venv\Lib\site-packages` folder or (MacOS/Linux)`venv/lib/python3.10/site-packages`
248
+ 3. If you see any folders with names start from `~` (e.g. "~rotobuf") - delete them
249
+ 4. Go to (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin`
250
+ 5. Run Terminal or Console (cmd) for that folder and type `activate`
251
+ 6. Update your pip at first: `pip install -U pip`
252
+ 7. Then one-by-one:
253
+ - `pip install insightface==0.7.3`
254
+ - `pip install onnx`
255
+ - `pip install "onnxruntime-gpu>=1.16.1"`
256
+ - `pip install opencv-python`
257
+ - `pip install tqdm`
258
+ 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.
259
+
260
+ ### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
261
+
262
+ First of all - you need to disable any other Roop-based extensions:
263
+ - Go to 'Extensions -> Installed' tab and uncheck any Roop-based extensions except this one
264
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>
265
+ - Click 'Apply and restart UI'
266
+
267
+ Alternative solutions:
268
+ - https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243
269
+ - https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (can be actual, if you use Vladmandic SD.Next)
270
+
271
+ ### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
272
+
273
+ Probably, you need to disable the "SD-CN-Animation" extension (or perhaps some another that causes the conflict)
274
+
275
+ ### **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'"**
276
+
277
+ This error may occur if there's smth wrong with the model file `inswapper_128.onnx`
278
+
279
+ Try to download it manually from [here](https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx)
280
+ and put it to the `stable-diffusion-webui\models\insightface` replacing existing one
281
+
282
+ ### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" OR "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
283
+
284
+ 1. Close (stop) your SD WebUI Server if it's running
285
+ 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
286
+ 3. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
287
+ 4. Then:
288
+ - `python -m pip install -U pip`
289
+ - `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`
290
+ - `pip install "onnxruntime-gpu>=1.16.1"`
291
+
292
+ 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!
293
+
294
+ ### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
295
+
296
+ 1. Close (stop) your SD WebUI Server if it's running
297
+ 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
298
+ 3. Go to the "google" folder (inside the "site-packages") and delete any folders there with names start from "~"
299
+ 4. Go to the (Windows)`venv\Scripts` or (MacOS/Linux)`venv/bin` run Terminal or Console (cmd) there and type `activate`
300
+ 5. Then:
301
+ - `python -m pip install -U pip`
302
+ - `pip uninstall protobuf`
303
+ - `pip install "protobuf>=3.20.3"`
304
+
305
+ 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
306
+
307
+ <a name="insightfacebuild">
308
+
309
+ ### **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:**
310
+
311
+ 1. Close (stop) your SD WebUI Server if it's running
312
+ 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"
313
+ 3. From stable-diffusion-webui (or SD.Next) root folder run CMD and `.\venv\Scripts\activate`<br>OR<br>(A1111 Portable) Run CMD
314
+ 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`
315
+ 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`
316
+ 6. Enjoy!
317
+
318
+ ### **IX. 07-August-23 Update problem**
319
+
320
+ If after `git pull` you see the message: `Merge made by the 'recursive' strategy` and then when you check `git status` you see `Your branch is ahead of 'origin/main' by`
321
+
322
+ Please do the next:
323
+
324
+ Inside the folder `extensions\sd-webui-reactor` run Terminal or Console (cmd) and then:
325
+ - `git reset f48bdf1 --hard`
326
+ - `git pull`
327
+
328
+ OR
329
+
330
+ 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`
331
+
332
+ ### **X. StabilityMatrix Issues**
333
+
334
+ 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
335
+
336
+ ## Updating
337
+
338
+ A good and quick way to check for Extensions updates: https://github.com/Gourieff/sd-webui-extensions-updater
339
+
340
+ ## ComfyUI
341
+
342
+ You can use ReActor with ComfyUI.<br>
343
+ For the installation instruction follow the [ReActor Node repo](https://github.com/Gourieff/comfyui-reactor-node)
344
+
345
+ ## Disclaimer
346
+
347
+ 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.
348
+
349
+ 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.
350
+
351
+ 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.**
352
+
353
+ By using this extension you are agree not to create any content that:
354
+ - violates any laws;
355
+ - causes any harm to a person or persons;
356
+ - propogates (spreads) any information (both public or personal) or images (both public or personal) which could be meant for harm;
357
+ - spreads misinformation;
358
+ - targets vulnerable groups of people.
359
+
360
+ 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:
361
+
362
+ [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.
363
+
364
+ 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.
365
+
366
+ 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.
367
+
368
+ ### Models Hashsum
369
+
370
+ #### Safe-to-use models have the folowing hash:
371
+
372
+ inswapper_128.onnx
373
+ ```
374
+ MD5:a3a155b90354160350efd66fed6b3d80
375
+ SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
376
+ ```
377
+
378
+ 1k3d68.onnx
379
+
380
+ ```
381
+ MD5:6fb94fcdb0055e3638bf9158e6a108f4
382
+ SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
383
+ ```
384
+
385
+ 2d106det.onnx
386
+
387
+ ```
388
+ MD5:a3613ef9eb3662b4ef88eb90db1fcf26
389
+ SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
390
+ ```
391
+
392
+ det_10g.onnx
393
+
394
+ ```
395
+ MD5:4c10eef5c9e168357a16fdd580fa8371
396
+ SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
397
+ ```
398
+
399
+ genderage.onnx
400
+
401
+ ```
402
+ MD5:81c77ba87ab38163b0dec6b26f8e2af2
403
+ SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
404
+ ```
405
+
406
+ w600k_r50.onnx
407
+
408
+ ```
409
+ MD5:80248d427976241cbd1343889ed132b3
410
+ SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
411
+ ```
412
+
413
+ **Please check hashsums if you download these models from unverified (or untrusted) sources**
extensionsa/2-sd-webui-reactor/README_RU.md ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/ReActor_logo_NEW_RU.png?raw=true" alt="logo" width="180px"/>
4
+
5
+ ![Version](https://img.shields.io/badge/версия-0.7.1_alpha2-lightgreen?style=for-the-badge&labelColor=darkgreen)
6
+
7
+ <a href="https://boosty.to/artgourieff" target="_blank">
8
+ <img src="https://lovemet.ru/www/boosty.jpg" width="108" alt="Поддержать проект на Boosty"/>
9
+ <br>
10
+ <sup>
11
+ Поддержать проект
12
+ </sup>
13
+ </a>
14
+
15
+ <hr>
16
+
17
+ [![Commit activity](https://img.shields.io/github/commit-activity/t/Gourieff/sd-webui-reactor/main?cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/commits/main)
18
+ ![Last commit](https://img.shields.io/github/last-commit/Gourieff/sd-webui-reactor/main?cacheSeconds=0)
19
+ [![Opened issues](https://img.shields.io/github/issues/Gourieff/sd-webui-reactor?color=red)](https://github.com/Gourieff/sd-webui-reactor/issues?cacheSeconds=0)
20
+ [![Closed issues](https://img.shields.io/github/issues-closed/Gourieff/sd-webui-reactor?color=green&cacheSeconds=0)](https://github.com/Gourieff/sd-webui-reactor/issues?q=is%3Aissue+is%3Aclosed)
21
+ ![License](https://img.shields.io/github/license/Gourieff/sd-webui-reactor)
22
+
23
+ [English](/README.md) | Русский
24
+
25
+ # ReActor для Stable Diffusion
26
+ ### Расширение для быстрой и простой замены лиц на любых изображениях. Без фильтра цензуры, 18+, используйте под вашу собственную [ответственность](#disclaimer)
27
+
28
+ ---
29
+ <b>
30
+ <a href="#latestupdate">Что нового</a> | <a href="#installation">Установка</a> | <a href="#features">Возможности</a> | <a href="#usage">Использование</a> | <a href="#api">API</a> | <a href="#troubleshooting">Устранение проблем</a> | <a href="#updating">Обновление</a> | <a href="#comfyui">ComfyUI</a> | <a href="#disclaimer">Ответственность</a>
31
+ </b>
32
+ </div>
33
+
34
+ ---
35
+
36
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/demo_crop.jpg?raw=true" alt="example"/>
37
+
38
+ <a name="latestupdate">
39
+
40
+ ## Что нового в последних обновлениях
41
+
42
+ <details>
43
+ <summary><a>Нажмите, чтобы посмотреть</a></summary>
44
+
45
+ ### 0.7.0 <sub><sup>BETA2
46
+
47
+ - X/Y/Z опция улучшена! Добавлен ещё один параметр: теперь вы можете выбрать несколько моделей лиц для создания вариации замененных лиц, чтобы выбрать наилучшие!
48
+
49
+ <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%"/>
50
+
51
+ Чтобы использовать ось "Face Model" - активируйте РеАктор и выбирите любую модель лица в качестве источника:<br>
52
+ <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%"/>
53
+
54
+ Полноразмерное демо-изображение: [xyz_demo_2.png](https://raw.githubusercontent.com/Gourieff/Assets/main/sd-webui-reactor/xyz_demo_2.png)
55
+
56
+ ### 0.7.0 <sub><sup>BETA1
57
+
58
+ - Поддержка X/Y/Z скрипта (до 3-х параметров: CodeFormer Weight, Restorer Visibility, Face Mask Correction)
59
+
60
+ <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%"/>
61
+
62
+ Полноразмерное демо-изображение: [xyz_demo.png](https://raw.githubusercontent.com/Gourieff/Assets/main/sd-webui-reactor/xyz_demo.png)
63
+
64
+ ### 0.7.0 <sub><sup>ALPHA1
65
+
66
+ - По многочисленным просьбам появилась возможность строить смешанные модели лиц ("Tools->Face Models->Blend")
67
+
68
+ <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%"/>
69
+
70
+ - Поддержка CUDA 12 в скрипте установщика для библиотеки ORT-GPU версии 1.17.0
71
+ - Новая вкладка "Detection" с параметрами "Threshold" и "Max Faces"
72
+
73
+ ### 0.6.1 <sub><sup>BETA3
74
+
75
+ - Опция 'Force Upscale' внутри вкладки 'Upscale': апскейл выполнится, даже если не было обнаружено ни одного лица (FR https://github.com/Gourieff/sd-webui-reactor/issues/116)
76
+ - Отображение имён файлов используемых из��бражений, когда выбрано несколько изображений или папка (а также режим случайного изображения)
77
+
78
+ ### 0.6.1 <sub><sup>BETA2
79
+
80
+ - Опция 'Save original' теперь работает правильно, когда вы выбираете 'Multiple Images' или 'Source Folder'
81
+ - Добавлен режим выбора случайного изображения для 'Source Folder'
82
+
83
+ <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%"/>
84
+
85
+ ### 0.6.0
86
+
87
+ - Новый логотип
88
+ - Адаптация к версии A1111 1.7.0 (правильная загрузка GFPGAN)
89
+ - Новая ссылка для файла основной модели
90
+ - UI переработан
91
+ - Появилась возможность загружать несколько исходных изображений с лицами или задавать путь к папке, содержащей такие изображения
92
+
93
+ <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%"/>
94
+
95
+ <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%"/>
96
+
97
+ ### 0.5.1
98
+
99
+ - Теперь можно сохранять модели лиц в качестве файлов "safetensors" (находятся в `<sd-web-ui-folder>\models\reactor\faces`) и загружать их с ReActor, храня супер легкие модели лиц, которые вы чаще всего используете;
100
+ - Новые опция "Face Mask Correction" - если вы сталкиваетесь с пикселизацией вокруг контуров лица, эта опция будет полезной;
101
+
102
+ <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%"/>
103
+
104
+ </details>
105
+
106
+ <a name="installation">
107
+
108
+ ## Установка
109
+
110
+ [A1111 WebUI / WebUI-Forge](#a1111) | [SD.Next](#sdnext) | [Google Colab SD WebUI](#colab)
111
+
112
+ <a name="a1111">Если вы используете [AUTOMATIC1111 SD WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui/) или [SD WebUI Forge](https://github.com/lllyasviel/stable-diffusion-webui-forge):
113
+
114
+ 1. (Для пользователей Windows):
115
+ - Установите **Visual Studio 2022** (Например, версию Community - этот шаг нужен для правильной компиляции библиотеки Insightface):
116
+ https://visualstudio.microsoft.com/downloads/
117
+ - ИЛИ только **VS C++ Build Tools** (если вам не нужен весь пакет Visual Studio), выберите "Desktop Development with C++" в разделе "Workloads -> Desktop & Mobile":
118
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/
119
+ - ИЛИ если же вы не хотите устанавливать что-либо из вышеуказанного - выполните [следующие шаги (пункт VIII)](#insightfacebuild)
120
+ 2. Внутри SD Web-UI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"
121
+ 3. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
122
+ 4. Проверьте последнее сообщение в консоли SD-WebUI:
123
+ * Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) и запустите его заново - ИЛИ же перейдите во вкладку "Installed", нажмите "Apply and restart UI"
124
+ * Если вы видите "Done!", просто перезагрузите UI, нажав на "Reload UI"
125
+ 5. Готово!
126
+
127
+ <a name="sdnext">Если вы используете [SD.Next](https://github.com/vladmandic/automatic):
128
+
129
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
130
+ 2. (Для пользователей Windows) Смотрите [Шаг 1](#a1111) для Automatic1111 (если же вы следовали [данным шагам (пункт VIII)](#insightfacebuild) вместо этого - переходите к Шагу 5)
131
+ 3. Перейдите в (Windows)`automatic\venv\Scripts` или (MacOS/Linux)`automatic/venv/bin`, запустите Терминал или Консоль (cmd) для данной папки и выполните `activate`
132
+ 4. Выполните `pip install insightface==0.7.3`
133
+ 5. Запустите SD.Next, перейдите во вкладку "Extensions", вставьте эту ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" и нажмите "Install"
134
+ 6. Пожалуйста, подождите несколько минут, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
135
+ 7. Проверьте последнее сообщение в консоли SD.Next:
136
+ * Если вы видите "--- PLEASE, RESTART the Server! ---" - остановите Сервер (CTRL+C или CMD+C) или просто закройте консоль
137
+ 8. Перейдите в директорию `automatic\extensions\sd-webui-reactor` - если вы видите там папку `models\insightface` с файлом `inswapper_128.onnx` внутри, переместите его в папку `automatic\models\insightface`
138
+ 9. Готово, можете запустить SD.Next WebUI!
139
+
140
+ <a name="colab">Если вы используете [Cagliostro Colab UI](https://github.com/Linaqruf/sd-notebook-collection):
141
+
142
+ 1. В активном WebUI перейдите во вкладку "Extensions", загрузите список доступных расширений (вкладка "Available") и введите "ReActor" в строке поиска или же вставьте ссылку `https://github.com/Gourieff/sd-webui-reactor` в "Install from URL" - и нажмите "Install"
143
+ 2. Пожалуйста, подождите некоторое время, пока процесс установки полностью не завершится (наберитесь терпения, не прерывайте процесс)
144
+ 3. Когда вы увидите сообщение "--- PLEASE, RESTART the Server! ---" (в секции "Start UI" вашего ноутбука "Start Cagliostro Colab UI") - перейдите во вкладку "Installed" и нажмите "Apply and restart UI"
145
+ 4. Готово!
146
+
147
+ <a name="features">
148
+
149
+ ## Возможности
150
+
151
+ - Быстрая и точна **замена лиц (faceswap)** на изображении
152
+ - **Поддержка нескольких лиц**
153
+ - **Определение пола**
154
+ - Функция **сохранения оригинального изображения** (сгенерированного до замены лица)
155
+ - **Восстановление лица** после замены
156
+ - **Увеличение размера** полученного изображения
157
+ - Сохранение и загрузка **Моделей Лиц типа Safetensors**
158
+ - **Коррекция Маски Лица** для предотвращения какой-либо пикселизации вокруг контуров лиц
159
+ - Возможность задать **порядок постобработки**
160
+ - **100% совместимость** с разными **SD WebUI**: Automatic1111, SD.Next, Cagliostro Colab UI
161
+ - **Отличная производительность** даже с использованием ЦПУ, ReActor для SD WebUI абсолютно не требователен к мощности вашей видеокарты
162
+ - **Поддержка CUDA**, начиная с версии 0.5.0
163
+ - **Поддержка [API](/API.md)**: как встроенного в SD WebUI, так и внешнего (через POST/GET запросы)
164
+ - **[Поддержка](https://github.com/Gourieff/comfyui-reactor-node) ComfyUI**
165
+ - **[Поддержка](https://github.com/Gourieff/sd-webui-reactor/issues/42) компьютеров Mac M1/M2**
166
+ - **Регулировка уровня логов** консоли
167
+ - **Без NSFW фильтров** (данное расширение адресовано высокоразвитым интеллектуальным людям, а не извращенцам; наше общество должно быть ориентировано на своём пути на высшие стандарты, а не на низшие - в этом состоит суть развития и эволюции человеческого общества; поэтому, моя позиция такова - что зрелые умом люди достаточно разумны, чтобы понимать, что есть хорошо, а что плохо и нести полную ответственность за собственные действия; для прочих - никакие "фильтры" не помогут, пока эти люди сами не поймут, как работает Вселенная)
168
+
169
+ <a name="usage">
170
+
171
+ ## Использование
172
+
173
+ > Используя данное программное обеспечение, вы соглашаетесь с [ответственностью](#disclaimer)
174
+
175
+ 1. В раскрывающимся меню "ReActor" импортируйте изображение, содержащее лицо;
176
+ 2. Установите флажок "Enable";
177
+ 3. Готово, теперь результат будет иметь то лицо, которое вы выбрали.
178
+
179
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/example.jpg?raw=true" alt="example" width="808"/>
180
+
181
+ ### Индексы Лиц (Face Indexes)
182
+
183
+ ReActor определяет лица на изображении в следующей последовательности:<br>
184
+ слева-направо, сверху-вниз.
185
+
186
+ Если вам нужно заменить определенное лицо, вы можете указать индекс для исходного (source, с лицом) и входного (input, где будет замена лица) изображений.
187
+
188
+ Индекс первого обнаруженного лица - 0.
189
+
190
+ Вы можете задать индексы в том порядке, который вам нужен.<br>
191
+ Например: 0,1,2 (для Source); 1,0,2 (для Input).<br>
192
+ Это означает, что: второе лицо из Input (индекс = 1) будет заменено первым лицом из Source (индекс = 0) и так далее.
193
+
194
+ ### Определение Пола
195
+
196
+ Вы можете обозначить, какой пол нужно определять на изображении.<br>
197
+ ReActor заменит только то лицо, которое удовлетворяет заданному условию.
198
+
199
+ ### Если лицо получилось нечётким
200
+ Используйте опцию "Restore Face". Также можете попробовать опцию "Upscaler". Для более точного контроля параметров используйте Upscaler во вкладке "Extras".
201
+ Также вы можете установить порядок постобработки (начиная с версии 0.1.0):
202
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/pp-order.png?raw=true" alt="example"/>
203
+
204
+ *Прежняя логика была противоположенной (Upscale -> затем Restore), что приводило к более худшему качеству изображения лица (а также к значительной разнице текстур) после увеличения.*
205
+
206
+ ### Результат имеет несколько лиц
207
+ Выберите номера лиц, которые нужно поменять, используя поля "Comma separated face number(s)" для исходного изображения лица и для результата. Можно устанавливать любой, необходимый вам, порядок лиц.
208
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/multiple-faces.png?raw=true" alt="example"/>
209
+
210
+ ### ~~Результат получился чёрным~~
211
+ ~~Это значит, что сработал NSFW фильтр.~~
212
+
213
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/IamSFW.jpg?raw=true" alt="IamSFW" width="50%"/>
214
+
215
+ ### Img2Img
216
+
217
+ Используйте эту вкладку, чтобы заменить лицо на уже готовом изображении (флажок "Swap in source image") или на сгенерированном на основе готового (флажок "Swap in generated image").
218
+
219
+ Inpainting также работает, но замена лица происходит только в области маски.<br>Пожалуйста, используйте с опцией "Only masked" для "Inpaint area", если вы применяете "Upscaler". Иначе, используйте функцию увеличения (апскейла) через вкладку "Extras" или через опциональный загрузчик "Script" (внизу экрана), применив "SD upscale" или "Ultimate SD upscale".
220
+
221
+ ### Extras
222
+
223
+ Начиная с версии 0.5.0, вы можете использовать ReActor через вкладку Extras, что даёт очень быструю производительность и возможность замены лиц в обход пайплайна SD, что иногда вызывает размытие или искажение деталей оригинального изображения
224
+
225
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/extras_tab.jpg?raw=true" alt="IamSFW"/>
226
+
227
+ ## API
228
+
229
+ Вы можете использовать ReActor как со встроенным SD Webui API так и через внешнее API.
230
+
231
+ Подробная инструкция **[здесь](/API.md)**.
232
+
233
+ <a name="troubleshooting">
234
+
235
+ ## Устранение проблем
236
+
237
+ ### **I. "You should at least have one model in models directory"**
238
+
239
+ Проверьте путь, где хранится модель "inswapper_128.onnx". Файл должен находиться в папке `stable-diffusion-webui\models\insightface`. Переместите модель туда, если она находится в какой-то иной директории.
240
+
241
+ ### **II. Какие-либо проблемы с установкой Insightface или прочих пакетов**
242
+
243
+ (Для пользователей Mac M1/M2) Если вы получаете ошибки в ходе установки Insightface - читайте https://github.com/Gourieff/sd-webui-reactor/issues/42
244
+
245
+ (Для пользователей Windows) Если VS C++ Build Tools или MS VS 2022 установлены но вы видите ошибки, связанные с отсутствием Insightface, попробуйте следующее:
246
+ 1. Закройте (остановите) SD WebUI Сервер и запустите его снова (возможно, не прошла инициализация пакета после его установки)
247
+
248
+ (Для пользователей любых ОС) Попробуйте следующее:
249
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
250
+ 2. Перейдите в папку (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages`
251
+ 3. Если вы видите к-л папки с именами, начинающимися с `~` (например, "~rotobuf") - удалите их
252
+ 4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`
253
+ 5. Откройте Терминал или Консоль (cmd) для этой папки и выполните `activate`
254
+ 6. Для начала обновите pip: `pip install -U pip`
255
+ 7. Далее:
256
+ - `pip install insightface==0.7.3`
257
+ - `pip install onnx`
258
+ - `pip install "onnxruntime-gpu>=1.16.1"`
259
+ - `pip install opencv-python`
260
+ - `pip install tqdm`
261
+ 8. Выполните `deactivate`, закройте Терминал или Консоль и запустите SD WebUI, ReActor должен запуститься без к-л проблем - если же нет, добро пожаловать в раздел "Issues".
262
+
263
+ ### **III. "TypeError: UpscaleOptions.init() got an unexpected keyword argument 'do_restore_first'"**
264
+
265
+ Для начала отключите любые другие Roop-подобные расширения:
266
+ - Перейдите в 'Extensions -> Installed' и снимите флажок с ненужных:
267
+ <img src="https://github.com/Gourieff/Assets/raw/main/sd-webui-reactor/roop-off.png?raw=true" alt="uncompatible-with-other-roop"/>
268
+ - Нажмите 'Apply and restart UI'
269
+
270
+ Альтернативные решения:
271
+ - https://github.com/Gourieff/sd-webui-reactor/issues/3#issuecomment-1615919243
272
+ - https://github.com/Gourieff/sd-webui-reactor/issues/39#issuecomment-1666559134 (актуально для Vladmandic SD.Next)
273
+
274
+ ### **IV. "AttributeError: 'FaceSwapScript' object has no attribute 'enable'"**
275
+
276
+ Отключите расширение "SD-CN-Animation" (или какое-либо другое, вызывающее конфликт)
277
+
278
+ ### **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'"**
279
+
280
+ Эта ошибка появляется, если что-то не так с файлом модели `inswapper_128.onnx`.
281
+
282
+ Скачайте вручную по ссылке [here](https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx)
283
+ и сохраните в директорию `stable-diffusion-webui\models\insightface`, заменив имеющийся файл.
284
+
285
+ ### **VI. "ValueError: This ORT build has ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] enabled" ИЛИ "ValueError: This ORT build has ['AzureExecutionProvider', 'CPUExecutionProvider'] enabled"**
286
+
287
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
288
+ 2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
289
+ 3. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
290
+ 4. Затем:
291
+ - `python -m pip install -U pip`
292
+ - `pip uninstall -y onnxruntime onnxruntime-gpu onnxruntime-silicon onnxruntime-extensions`
293
+ - `pip install "onnxruntime-gpu>=1.16.1"`
294
+
295
+ Если это не помогло - значит какое-то другое расширение переустанавлив��ет `onnxruntime` всякий раз, когда SD WebUI проверяет требования пакетов. Внимательно посмотрите список активных расширений. Некоторые расширения могут вызывать переустановку `onnxruntime-gpu` на версию `onnxruntime<1.16.1` при каждом запуске SD WebUI.<br>ORT 1.16.0 выкатили с ошибкой https://github.com/microsoft/onnxruntime/issues/17631 - не устанавливайте её!
296
+
297
+ ### **VII. "ImportError: cannot import name 'builder' from 'google.protobuf.internal'"**
298
+
299
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
300
+ 2. Перейдите в (Windows)`venv\Lib\site-packages` или (MacOS/Linux)`venv/lib/python3.10/site-packages` и посмотрите, если там папки с именам, начинающимися на "~" (например, "~rotobuf"), удалите их
301
+ 3. Перейдите в папку "google" (внутри "site-packages") и удалите любые папки с именам, начинающимися на "~"
302
+ 4. Перейдите в (Windows)`venv\Scripts` или (MacOS/Linux)`venv/bin`, откройте Терминал или Консоль (cmd) и выполните `activate`
303
+ 5. Затем:
304
+ - `python -m pip install -U pip`
305
+ - `pip uninstall protobuf`
306
+ - `pip install "protobuf>=3.20.3"`
307
+
308
+ Если это не помгло - значит, есть к-л другое расширение, которое использует неподходящую версию пакета protobuf, и SD WebUI устанавливает эту версию при каждом запуске.
309
+
310
+ <a name="insightfacebuild">
311
+
312
+ ### **VIII. (Для пользователей Windows) Если вы до сих пор не можете установить пакет Insightface по каким-то причинам или же просто не желаете устанавливать Visual Studio или VS C++ Build Tools - сделайте следующее:**
313
+
314
+ 1. Закройте (остановите) SD WebUI Сервер, если он запущен
315
+ 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"
316
+ 3. Из корневой директории откройте Консоль (CMD) и выполните `.\venv\Scripts\activate`<br>ИЛИ<br>(A1111 Portable) Откройте Консоль (CMD)
317
+ 4. Обновите PIP: `python -m pip install -U pip`<br>ИЛИ<br>(A1111 Portable)`system\python\python.exe -m pip install -U pip`
318
+ 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`
319
+ 6. Готово!
320
+
321
+ ### **IX. Ошибка обновления 07-Август-23**
322
+
323
+ Если после очередного `git pull` вы получили сообщение: `Merge made by the 'recursive' strategy` и затем, когда проверяете статус репозитория через `git status`, вы видите `Your branch is ahead of 'origin/main' by`
324
+
325
+ Выполните следующее:
326
+
327
+ Внутри папки `extensions\sd-webui-reactor` запустите Терминал или Консоль (cmd) и затем:
328
+ - `git reset f48bdf1 --hard`
329
+ - `git pull`
330
+
331
+ ИЛИ:
332
+
333
+ Полностью удалите папку `sd-webui-reactor` внутри директории `extensions`, запустите Терминал или Консоль (cmd) и выполните `git clone https://github.com/Gourieff/sd-webui-reactor`
334
+
335
+ ### **X. Ошибки установки в StabilityMatrix**
336
+
337
+ Если вы столкнулись с ошибками при установки данного расширения в пакетном менеджере StabilityMatrix - изучите информацию по ссылке: https://github.com/Gourieff/sd-webui-reactor/issues/129#issuecomment-1768210875
338
+
339
+ <a name="updating">
340
+
341
+ ## Обновление
342
+
343
+ Самый простой и удобный способ обновления SD WebUI и расширений: https://github.com/Gourieff/sd-webui-extensions-updater
344
+
345
+ ## ComfyUI
346
+
347
+ Вы можете использовать ReActor с ComfyUI<br>
348
+ Инструкция здесь: [ReActor Node](https://github.com/Gourieff/comfyui-reactor-node)
349
+
350
+ <a name="disclaimer">
351
+
352
+ ## Ответственность
353
+
354
+ Это программное обеспечение призвано стать продуктивным вкладом в быстрорастущую медиаиндустрию на основе генеративн��х сетей и искусственного интеллекта. Данное ПО поможет художникам в решении таких задач, как анимация собственного персонажа или использование персонажа в качестве модели для одежды и т.д.
355
+
356
+ Разработчики этого программного обеспечения осведомлены о возможных неэтичных применениях и обязуются принять против этого превентивные меры. Мы продолжим развивать этот проект в позитивном направлении, придерживаясь закона и этики.
357
+
358
+ Подразумевается, что пользователи этого программного обеспечения будут использовать его ответственно, соблюдая локальное законодательство. Если используется лицо реального человека, пользователь обязан получить согласие заинтересованного лица и четко указать, что это дипфейк при размещении контента в Интернете. **Разработчики и Со-авторы данного программного обеспечения не несут ответственности за действия конечных пользователей.**
359
+
360
+ Используя данное расширение, вы соглашаетесь не создавать материалы, которые:
361
+ - нарушают какие-либо действующие законы тех или иных государств или международных организаций;
362
+ - причиняют какой-либо вред человеку или лицам;
363
+ - пропагандируют любую информацию (как общедоступную, так и личную) или изображения (как общедоступные, так и личные), которые могут быть направлены на причинение вреда;
364
+ - используются для распространения дезинформации;
365
+ - нацелены на уязвимые группы людей.
366
+
367
+ Данное программное обеспечение использует предварительно обученные модели `buffalo_l` и `inswapper_128.onnx`, представленные разработчиками [InsightFace](https://github.com/deepinsight/insightface/). Эти модели распространяются при следующих условиях:
368
+
369
+ [Перевод из текста лицензии insighface](https://github.com/deepinsight/insightface/tree/master/python-package): Предварительно обученные модели InsightFace доступны только для некоммерческих исследовательских целей. Сюда входят как модели с автоматической загрузкой, так и модели, загруженные вручную.
370
+
371
+ Пользователи данного программного обеспечения должны строго соблюдать данные условия использования. Разработчики и Со-авторы данного программного продукта не несут ответственности за неправильное использование предварительно обученных моделей InsightFace.
372
+
373
+ Обратите внимание: если вы собираетесь использовать это программное обеспечение в каких-либо коммерческих целях, вам необходимо будет обучить свои собственные модели или найти модели, которые можно использовать в коммерческих целях.
374
+
375
+ ### Хэш файлов моделей
376
+
377
+ #### Безопасные для использования модели имеют следующий хэш:
378
+
379
+ inswapper_128.onnx
380
+ ```
381
+ MD5:a3a155b90354160350efd66fed6b3d80
382
+ SHA256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
383
+ ```
384
+
385
+ 1k3d68.onnx
386
+
387
+ ```
388
+ MD5:6fb94fcdb0055e3638bf9158e6a108f4
389
+ SHA256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
390
+ ```
391
+
392
+ 2d106det.onnx
393
+
394
+ ```
395
+ MD5:a3613ef9eb3662b4ef88eb90db1fcf26
396
+ SHA256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
397
+ ```
398
+
399
+ det_10g.onnx
400
+
401
+ ```
402
+ MD5:4c10eef5c9e168357a16fdd580fa8371
403
+ SHA256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
404
+ ```
405
+
406
+ genderage.onnx
407
+
408
+ ```
409
+ MD5:81c77ba87ab38163b0dec6b26f8e2af2
410
+ SHA256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
411
+ ```
412
+
413
+ w600k_r50.onnx
414
+
415
+ ```
416
+ MD5:80248d427976241cbd1343889ed132b3
417
+ SHA256:4c06341c33c2ca1f86781dab0e829f88ad5b64be9fba56e56bc9ebdefc619e43
418
+ ```
419
+
420
+ **Пожалуйста, сравните хэш, если вы скачиваете данные модели из непроверенных источников**
extensionsa/2-sd-webui-reactor/example/IamSFW.jpg ADDED
extensionsa/2-sd-webui-reactor/example/api_example.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64, io, requests, json
2
+ from PIL import Image, PngImagePlugin
3
+ from datetime import datetime, date
4
+
5
+ address = 'http://127.0.0.1:7860'
6
+ input_file = "extensions\sd-webui-reactor\example\IamSFW.jpg" # Input file path
7
+ time = datetime.now()
8
+ today = date.today()
9
+ current_date = today.strftime('%Y-%m-%d')
10
+ current_time = time.strftime('%H-%M-%S')
11
+ output = 'outputs/api/output_'+current_date+'_'+current_time # Output file path + name index
12
+ try:
13
+ im = Image.open(input_file)
14
+ except Exception as e:
15
+ print(e)
16
+ finally:
17
+ print(im)
18
+
19
+ img_bytes = io.BytesIO()
20
+ im.save(img_bytes, format='PNG')
21
+ img_base64 = base64.b64encode(img_bytes.getvalue()).decode('utf-8')
22
+
23
+ # ReActor arguments:
24
+ args=[
25
+ img_base64, #0
26
+ True, #1 Enable ReActor
27
+ '0', #2 Comma separated face number(s) from swap-source image
28
+ '0', #3 Comma separated face number(s) for target image (result)
29
+ 'C:\stable-diffusion-webui\models\insightface\inswapper_128.onnx', #4 model path
30
+ 'CodeFormer', #4 Restore Face: None; CodeFormer; GFPGAN
31
+ 1, #5 Restore visibility value
32
+ True, #7 Restore face -> Upscale
33
+ '4x_NMKD-Superscale-SP_178000_G', #8 Upscaler (type 'None' if doesn't need), see full list here: http://127.0.0.1:7860/sdapi/v1/script-info -> reactor -> sec.8
34
+ 1.5, #9 Upscaler scale value
35
+ 1, #10 Upscaler visibility (if scale = 1)
36
+ False, #11 Swap in source image
37
+ True, #12 Swap in generated image
38
+ 1, #13 Console Log Level (0 - min, 1 - med or 2 - max)
39
+ 0, #14 Gender Detection (Source) (0 - No, 1 - Female Only, 2 - Male Only)
40
+ 0, #15 Gender Detection (Target) (0 - No, 1 - Female Only, 2 - Male Only)
41
+ False, #16 Save the original image(s) made before swapping
42
+ 0.8, #17 CodeFormer Weight (0 = maximum effect, 1 = minimum effect), 0.5 - by default
43
+ False, #18 Source Image Hash Check, True - by default
44
+ False, #19 Target Image Hash Check, False - by default
45
+ "CUDA", #20 CPU or CUDA (if you have it), CPU - by default
46
+ True, #21 Face Mask Correction
47
+ 1, #22 Select Source, 0 - Image, 1 - Face Model, 2 - Source Folder
48
+ "elena.safetensors", #23 Filename of the face model (from "models/reactor/faces"), e.g. elena.safetensors, don't forger to set #22 to 1
49
+ "C:\PATH_TO_FACES_IMAGES", #24 The path to the folder containing source faces images, don't forger to set #22 to 2
50
+ None, #25 skip it for API
51
+ True, #26 Randomly select an image from the path
52
+ True, #27 Force Upscale even if no face found
53
+ 0.6, #28 Face Detection Threshold
54
+ 2, #29 Maximum number of faces to detect (0 is unlimited)
55
+ ]
56
+
57
+ # The args for ReActor can be found by
58
+ # requests.get(url=f'{address}/sdapi/v1/script-info')
59
+
60
+ prompt = "(8k, best quality, masterpiece, highly detailed:1.1),realistic photo of fantastic happy woman,hairstyle of blonde and red short bob hair,modern clothing,cinematic lightning,film grain,dynamic pose,bokeh,dof"
61
+
62
+ neg = "ng_deepnegative_v1_75t,(badhandv4:1.2),(worst quality:2),(low quality:2),(normal quality:2),lowres,(bad anatomy),(bad hands),((monochrome)),((grayscale)),(verybadimagenegative_v1.3:0.8),negative_hand-neg,badhandv4,nude,naked,(strabismus),cross-eye,heterochromia,((blurred))"
63
+
64
+ payload = {
65
+ "prompt": prompt,
66
+ "negative_prompt": neg,
67
+ "seed": -1,
68
+ "sampler_name": "DPM++ 2M Karras",
69
+ "steps": 15,
70
+ "cfg_scale": 7,
71
+ "width": 512,
72
+ "height": 768,
73
+ "restore_faces": False,
74
+ "alwayson_scripts": {"reactor":{"args":args}}
75
+ }
76
+
77
+ try:
78
+ print('Working... Please wait...')
79
+ result = requests.post(url=f'{address}/sdapi/v1/txt2img', json=payload)
80
+ except Exception as e:
81
+ print(e)
82
+ finally:
83
+ print('Done! Saving file...')
84
+
85
+ if result is not None:
86
+ r = result.json()
87
+ n = 0
88
+
89
+ for i in r['images']:
90
+ image = Image.open(io.BytesIO(base64.b64decode(i.split(",",1)[0])))
91
+
92
+ png_payload = {
93
+ "image": "data:image/png;base64," + i
94
+ }
95
+ response2 = requests.post(url=f'{address}/sdapi/v1/png-info', json=png_payload)
96
+
97
+ pnginfo = PngImagePlugin.PngInfo()
98
+ pnginfo.add_text("parameters", response2.json().get("info"))
99
+ output_file = output+'_'+str(n)+'_.png'
100
+ try:
101
+ image.save(output_file, pnginfo=pnginfo)
102
+ except Exception as e:
103
+ print(e)
104
+ finally:
105
+ print(f'{output_file} is saved\nAll is done!')
106
+ n += 1
107
+ else:
108
+ print('Something went wrong...')
extensionsa/2-sd-webui-reactor/example/api_external.curl ADDED
The diff for this file is too large to render. See raw diff
 
extensionsa/2-sd-webui-reactor/example/api_external.json ADDED
The diff for this file is too large to render. See raw diff
 
extensionsa/2-sd-webui-reactor/install.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import os, sys
3
+ from typing import Any
4
+ import pkg_resources
5
+ from tqdm import tqdm
6
+ import urllib.request
7
+ from packaging import version as pv
8
+
9
+ try:
10
+ from modules.paths_internal import models_path
11
+ except:
12
+ try:
13
+ from modules.paths import models_path
14
+ except:
15
+ models_path = os.path.abspath("models")
16
+
17
+
18
+ BASE_PATH = os.path.dirname(os.path.realpath(__file__))
19
+
20
+ req_file = os.path.join(BASE_PATH, "requirements.txt")
21
+
22
+ models_dir = os.path.join(models_path, "insightface")
23
+
24
+ # DEPRECATED:
25
+ # models_dir_old = os.path.join(models_path, "roop")
26
+ # if os.path.exists(models_dir_old):
27
+ # if not os.listdir(models_dir_old) and (not os.listdir(models_dir) or not os.path.exists(models_dir)):
28
+ # os.rename(models_dir_old, models_dir)
29
+ # else:
30
+ # import shutil
31
+ # for file in os.listdir(models_dir_old):
32
+ # shutil.move(os.path.join(models_dir_old, file), os.path.join(models_dir, file))
33
+ # try:
34
+ # os.rmdir(models_dir_old)
35
+ # except Exception as e:
36
+ # print(f"OSError: {e}")
37
+
38
+ model_url = "https://huggingface.co/datasets/Gourieff/ReActor/resolve/main/models/inswapper_128.onnx"
39
+ model_name = os.path.basename(model_url)
40
+ model_path = os.path.join(models_dir, model_name)
41
+
42
+ def pip_install(*args):
43
+ subprocess.run([sys.executable, "-m", "pip", "install", *args])
44
+
45
+ def pip_uninstall(*args):
46
+ subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", *args])
47
+
48
+ def is_installed (
49
+ package: str, version: str | None = None, strict: bool = True
50
+ ):
51
+ has_package = None
52
+ try:
53
+ has_package = pkg_resources.get_distribution(package)
54
+ if has_package is not None:
55
+ installed_version = has_package.version
56
+ if (installed_version != version and strict == True) or (pv.parse(installed_version) < pv.parse(version) and strict == False):
57
+ return False
58
+ else:
59
+ return True
60
+ else:
61
+ return False
62
+ except Exception as e:
63
+ print(f"Error: {e}")
64
+ return False
65
+
66
+ def download(url, path):
67
+ request = urllib.request.urlopen(url)
68
+ total = int(request.headers.get('Content-Length', 0))
69
+ with tqdm(total=total, desc='Downloading...', unit='B', unit_scale=True, unit_divisor=1024) as progress:
70
+ urllib.request.urlretrieve(url, path, reporthook=lambda count, block_size, total_size: progress.update(block_size))
71
+
72
+ if not os.path.exists(models_dir):
73
+ os.makedirs(models_dir)
74
+
75
+ if not os.path.exists(model_path):
76
+ download(model_url, model_path)
77
+
78
+ # print("ReActor preheating...", end=' ')
79
+
80
+ last_device = None
81
+ first_run = False
82
+ available_devices = ["CPU", "CUDA"]
83
+
84
+ try:
85
+ last_device_log = os.path.join(BASE_PATH, "last_device.txt")
86
+ with open(last_device_log) as f:
87
+ last_device = f.readline().strip()
88
+ if last_device not in available_devices:
89
+ last_device = None
90
+ except:
91
+ last_device = "CPU"
92
+ first_run = True
93
+ with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
94
+ txt.write(last_device)
95
+
96
+ with open(req_file) as file:
97
+ install_count = 0
98
+ ort = "onnxruntime-gpu"
99
+ import torch
100
+ cuda_version = None
101
+ try:
102
+ if torch.cuda.is_available():
103
+ cuda_version = torch.version.cuda
104
+ print(f"CUDA {cuda_version}")
105
+ if first_run or last_device is None:
106
+ last_device = "CUDA"
107
+ elif torch.backends.mps.is_available() or hasattr(torch,'dml') or hasattr(torch,'privateuseone'):
108
+ ort = "onnxruntime"
109
+ # to prevent errors when ORT-GPU is installed but we want ORT instead:
110
+ if first_run:
111
+ pip_uninstall("onnxruntime", "onnxruntime-gpu")
112
+ # just in case:
113
+ if last_device == "CUDA" or last_device is None:
114
+ last_device = "CPU"
115
+ else:
116
+ if last_device == "CUDA" or last_device is None:
117
+ last_device = "CPU"
118
+ with open(os.path.join(BASE_PATH, "last_device.txt"), "w") as txt:
119
+ txt.write(last_device)
120
+ if cuda_version is not None and float(cuda_version)>=12: # CU12
121
+ if not is_installed(ort,"1.17.1",False):
122
+ install_count += 1
123
+ pip_uninstall("onnxruntime", "onnxruntime-gpu")
124
+ pip_install(ort,"--extra-index-url","https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/")
125
+ elif not is_installed(ort,"1.16.1",False):
126
+ install_count += 1
127
+ pip_install(ort, "-U")
128
+ except Exception as e:
129
+ print(e)
130
+ print(f"\nERROR: Failed to install {ort} - ReActor won't start")
131
+ raise e
132
+ # print(f"Device: {last_device}")
133
+ strict = True
134
+ for package in file:
135
+ package_version = None
136
+ try:
137
+ package = package.strip()
138
+ if "==" in package:
139
+ package_version = package.split('==')[1]
140
+ elif ">=" in package:
141
+ package_version = package.split('>=')[1]
142
+ strict = False
143
+ if not is_installed(package,package_version,strict):
144
+ install_count += 1
145
+ pip_install(package)
146
+ except Exception as e:
147
+ print(e)
148
+ print(f"\nERROR: Failed to install {package} - ReActor won't start")
149
+ raise e
150
+ if install_count > 0:
151
+ print(f"""
152
+ +---------------------------------+
153
+ --- PLEASE, RESTART the Server! ---
154
+ +---------------------------------+
155
+ """)
extensionsa/2-sd-webui-reactor/last_device.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ CUDA
extensionsa/2-sd-webui-reactor/reactor_modules/__pycache__/reactor_mask.cpython-310.pyc ADDED
Binary file (5.48 kB). View file
 
extensionsa/2-sd-webui-reactor/reactor_modules/reactor_mask.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from PIL import Image, ImageDraw
4
+
5
+ from torchvision.transforms.functional import to_pil_image
6
+
7
+ from scripts.reactor_logger import logger
8
+ from scripts.reactor_inferencers.bisenet_mask_generator import BiSeNetMaskGenerator
9
+ from scripts.reactor_entities.face import FaceArea
10
+ from scripts.reactor_entities.rect import Rect
11
+
12
+
13
+ colors = [
14
+ (255, 0, 0),
15
+ (0, 255, 0),
16
+ (0, 0, 255),
17
+ (255, 255, 0),
18
+ (255, 0, 255),
19
+ (0, 255, 255),
20
+ (255, 255, 255),
21
+ (128, 0, 0),
22
+ (0, 128, 0),
23
+ (128, 128, 0),
24
+ (0, 0, 128),
25
+ (0, 128, 128),
26
+ ]
27
+
28
+ def color_generator(colors):
29
+ while True:
30
+ for color in colors:
31
+ yield color
32
+
33
+
34
+ def process_face_image(
35
+ face: FaceArea,
36
+ **kwargs,
37
+ ) -> Image:
38
+ image = np.array(face.image)
39
+ overlay = image.copy()
40
+ color_iter = color_generator(colors)
41
+ cv2.rectangle(overlay, (0, 0), (image.shape[1], image.shape[0]), next(color_iter), -1)
42
+ l, t, r, b = face.face_area_on_image
43
+ cv2.rectangle(overlay, (l, t), (r, b), (0, 0, 0), 10)
44
+ if face.landmarks_on_image is not None:
45
+ for landmark in face.landmarks_on_image:
46
+ cv2.circle(overlay, (int(landmark.x), int(landmark.y)), 6, (0, 0, 0), 10)
47
+ alpha = 0.3
48
+ output = cv2.addWeighted(image, 1 - alpha, overlay, alpha, 0)
49
+
50
+ return Image.fromarray(output)
51
+
52
+
53
+ def apply_face_mask(swapped_image:np.ndarray,target_image:np.ndarray,target_face,entire_mask_image:np.array)->np.ndarray:
54
+ logger.status("Correcting Face Mask")
55
+ mask_generator = BiSeNetMaskGenerator()
56
+ face = FaceArea(target_image,Rect.from_ndarray(np.array(target_face.bbox)),1.6,512,"")
57
+ face_image = np.array(face.image)
58
+ process_face_image(face)
59
+ face_area_on_image = face.face_area_on_image
60
+ mask = mask_generator.generate_mask(
61
+ face_image,
62
+ face_area_on_image=face_area_on_image,
63
+ affected_areas=["Face"],
64
+ mask_size=0,
65
+ use_minimal_area=True
66
+ )
67
+ mask = cv2.blur(mask, (12, 12))
68
+ # """entire_mask_image = np.zeros_like(target_image)"""
69
+ larger_mask = cv2.resize(mask, dsize=(face.width, face.height))
70
+ entire_mask_image[
71
+ face.top : face.bottom,
72
+ face.left : face.right,
73
+ ] = larger_mask
74
+
75
+ result = Image.composite(Image.fromarray(swapped_image),Image.fromarray(target_image), Image.fromarray(entire_mask_image).convert("L"))
76
+ return np.array(result)
77
+
78
+
79
+ def rotate_array(image: np.ndarray, angle: float) -> np.ndarray:
80
+ if angle == 0:
81
+ return image
82
+
83
+ h, w = image.shape[:2]
84
+ center = (w // 2, h // 2)
85
+
86
+ M = cv2.getRotationMatrix2D(center, angle, 1.0)
87
+ return cv2.warpAffine(image, M, (w, h))
88
+
89
+
90
+ def rotate_image(image: Image, angle: float) -> Image:
91
+ if angle == 0:
92
+ return image
93
+ return Image.fromarray(rotate_array(np.array(image), angle))
94
+
95
+
96
+ def correct_face_tilt(angle: float) -> bool:
97
+ angle = abs(angle)
98
+ if angle > 180:
99
+ angle = 360 - angle
100
+ return angle > 40
101
+
102
+
103
+ def _dilate(arr: np.ndarray, value: int) -> np.ndarray:
104
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value))
105
+ return cv2.dilate(arr, kernel, iterations=1)
106
+
107
+
108
+ def _erode(arr: np.ndarray, value: int) -> np.ndarray:
109
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (value, value))
110
+ return cv2.erode(arr, kernel, iterations=1)
111
+
112
+
113
+ def dilate_erode(img: Image.Image, value: int) -> Image.Image:
114
+ """
115
+ The dilate_erode function takes an image and a value.
116
+ If the value is positive, it dilates the image by that amount.
117
+ If the value is negative, it erodes the image by that amount.
118
+
119
+ Parameters
120
+ ----------
121
+ img: PIL.Image.Image
122
+ the image to be processed
123
+ value: int
124
+ kernel size of dilation or erosion
125
+
126
+ Returns
127
+ -------
128
+ PIL.Image.Image
129
+ The image that has been dilated or eroded
130
+ """
131
+ if value == 0:
132
+ return img
133
+
134
+ arr = np.array(img)
135
+ arr = _dilate(arr, value) if value > 0 else _erode(arr, -value)
136
+
137
+ return Image.fromarray(arr)
138
+
139
+ def mask_to_pil(masks, shape: tuple[int, int]) -> list[Image.Image]:
140
+ """
141
+ Parameters
142
+ ----------
143
+ masks: torch.Tensor, dtype=torch.float32, shape=(N, H, W).
144
+ The device can be CUDA, but `to_pil_image` takes care of that.
145
+
146
+ shape: tuple[int, int]
147
+ (width, height) of the original image
148
+ """
149
+ n = masks.shape[0]
150
+ return [to_pil_image(masks[i], mode="L").resize(shape) for i in range(n)]
151
+
152
+ def create_mask_from_bbox(
153
+ bboxes: list[list[float]], shape: tuple[int, int]
154
+ ) -> list[Image.Image]:
155
+ """
156
+ Parameters
157
+ ----------
158
+ bboxes: list[list[float]]
159
+ list of [x1, y1, x2, y2]
160
+ bounding boxes
161
+ shape: tuple[int, int]
162
+ shape of the image (width, height)
163
+
164
+ Returns
165
+ -------
166
+ masks: list[Image.Image]
167
+ A list of masks
168
+
169
+ """
170
+ masks = []
171
+ for bbox in bboxes:
172
+ mask = Image.new("L", shape, 0)
173
+ mask_draw = ImageDraw.Draw(mask)
174
+ mask_draw.rectangle(bbox, fill=255)
175
+ masks.append(mask)
176
+ return masks
extensionsa/2-sd-webui-reactor/reactor_ui/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import reactor_ui.reactor_upscale_ui as ui_upscale
2
+ import reactor_ui.reactor_tools_ui as ui_tools
3
+ import reactor_ui.reactor_settings_ui as ui_settings
4
+ import reactor_ui.reactor_main_ui as ui_main
5
+ import reactor_ui.reactor_detection_ui as ui_detection
extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (550 Bytes). View file
 
extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_detection_ui.cpython-310.pyc ADDED
Binary file (1.77 kB). View file
 
extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_main_ui.cpython-310.pyc ADDED
Binary file (5.83 kB). View file
 
extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_settings_ui.cpython-310.pyc ADDED
Binary file (2.53 kB). View file
 
extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_tools_ui.cpython-310.pyc ADDED
Binary file (2.25 kB). View file
 
extensionsa/2-sd-webui-reactor/reactor_ui/__pycache__/reactor_upscale_ui.cpython-310.pyc ADDED
Binary file (1.93 kB). View file
 
extensionsa/2-sd-webui-reactor/reactor_ui/reactor_detection_ui.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from scripts.reactor_swapper import (
3
+ clear_faces,
4
+ clear_faces_list,
5
+ clear_faces_target,
6
+ clear_faces_all
7
+ )
8
+
9
+ # TAB DETECTION
10
+ def show(show_br: bool = True):
11
+ with gr.Tab("Detection"):
12
+ with gr.Row():
13
+ det_thresh = gr.Slider(
14
+ minimum=0.1,
15
+ maximum=1.0,
16
+ value=0.5,
17
+ step=0.01,
18
+ label="Threshold",
19
+ info="The higher the value, the more sensitive the detection is to what is considered a face (0.5 by default)",
20
+ scale=2
21
+ )
22
+ det_maxnum = gr.Slider(
23
+ minimum=0,
24
+ maximum=20,
25
+ value=0,
26
+ step=1,
27
+ label="Max Faces",
28
+ info="Maximum number of faces to detect (0 is unlimited)",
29
+ scale=1
30
+ )
31
+ # gr.Markdown("<br>", visible=show_br)
32
+ 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)
33
+ with gr.Row():
34
+ imgs_hash_clear_single = gr.Button(
35
+ value="Clear Source Images Hash (Single)",
36
+ scale=1
37
+ )
38
+ imgs_hash_clear_multiple = gr.Button(
39
+ value="Clear Source Images Hash (Multiple)",
40
+ scale=1
41
+ )
42
+ imgs_hash_clear_target = gr.Button(
43
+ value="Clear Target Image Hash",
44
+ scale=1
45
+ )
46
+ imgs_hash_clear_all = gr.Button(
47
+ value="Clear All Hash"
48
+ )
49
+ progressbar_area = gr.Markdown("")
50
+ imgs_hash_clear_single.click(clear_faces,None,[progressbar_area])
51
+ imgs_hash_clear_multiple.click(clear_faces_list,None,[progressbar_area])
52
+ imgs_hash_clear_target.click(clear_faces_target,None,[progressbar_area])
53
+ imgs_hash_clear_all.click(clear_faces_all,None,[progressbar_area])
54
+ return det_thresh, det_maxnum
extensionsa/2-sd-webui-reactor/reactor_ui/reactor_main_ui.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from scripts.reactor_helpers import (
3
+ get_model_names,
4
+ get_facemodels
5
+ )
6
+ from scripts.reactor_swapper import (
7
+ clear_faces_list,
8
+ )
9
+ from modules import shared
10
+
11
+ # SAVE_ORIGINAL: bool = False
12
+
13
+ def update_fm_list(selected: str):
14
+ try: # GR3.x
15
+ return gr.Dropdown.update(
16
+ value=selected, choices=get_model_names(get_facemodels)
17
+ )
18
+ except: # GR4.x
19
+ return gr.Dropdown(
20
+ value=selected, choices=get_model_names(get_facemodels)
21
+ )
22
+
23
+ # TAB MAIN
24
+ def show(is_img2img: bool, show_br: bool = True, **msgs):
25
+
26
+ # def on_select_source(selected: bool, evt: gr.SelectData):
27
+ def on_select_source(evt: gr.SelectData):
28
+ # global SAVE_ORIGINAL
29
+ if evt.index == 2:
30
+ # if SAVE_ORIGINAL != selected:
31
+ # SAVE_ORIGINAL = selected
32
+ try: # GR3.x
33
+ return {
34
+ control_col_1: gr.Column.update(visible=False),
35
+ control_col_2: gr.Column.update(visible=False),
36
+ control_col_3: gr.Column.update(visible=True),
37
+ # save_original: gr.Checkbox.update(value=False,visible=False),
38
+ imgs_hash_clear: gr.Button.update(visible=True)
39
+ }
40
+ except: # GR4.x
41
+ return {
42
+ control_col_1: gr.Column(visible=False),
43
+ control_col_2: gr.Column(visible=False),
44
+ control_col_3: gr.Column(visible=True),
45
+ # save_original: gr.Checkbox.update(value=False,visible=False),
46
+ imgs_hash_clear: gr.Button(visible=True)
47
+ }
48
+ if evt.index == 0:
49
+ try: # GR3.x
50
+ return {
51
+ control_col_1: gr.Column.update(visible=True),
52
+ control_col_2: gr.Column.update(visible=False),
53
+ control_col_3: gr.Column.update(visible=False),
54
+ # save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
55
+ imgs_hash_clear: gr.Button.update(visible=False)
56
+ }
57
+ except: # GR4.x
58
+ return {
59
+ control_col_1: gr.Column(visible=True),
60
+ control_col_2: gr.Column(visible=False),
61
+ control_col_3: gr.Column(visible=False),
62
+ # save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
63
+ imgs_hash_clear: gr.Button(visible=False)
64
+ }
65
+ if evt.index == 1:
66
+ try: # GR3.x
67
+ return {
68
+ control_col_1: gr.Column.update(visible=False),
69
+ control_col_2: gr.Column.update(visible=True),
70
+ control_col_3: gr.Column.update(visible=False),
71
+ # save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
72
+ imgs_hash_clear: gr.Button.update(visible=False)
73
+ }
74
+ except: # GR4.x
75
+ return {
76
+ control_col_1: gr.Column(visible=False),
77
+ control_col_2: gr.Column(visible=True),
78
+ control_col_3: gr.Column(visible=False),
79
+ # save_original: gr.Checkbox.update(value=SAVE_ORIGINAL,visible=show_br),
80
+ imgs_hash_clear: gr.Button(visible=False)
81
+ }
82
+
83
+ progressbar_area = gr.Markdown("")
84
+ with gr.Tab("Main"):
85
+ with gr.Column():
86
+ with gr.Row():
87
+ select_source = gr.Radio(
88
+ ["Image(s)","Face Model","Folder"],
89
+ value="Image(s)",
90
+ label="Select Source",
91
+ type="index",
92
+ scale=1,
93
+ )
94
+ with gr.Column(visible=False) as control_col_2:
95
+ with gr.Row():
96
+ face_models = get_model_names(get_facemodels)
97
+ face_model = gr.Dropdown(
98
+ choices=face_models,
99
+ label="Choose Face Model",
100
+ value="None",
101
+ scale=1,
102
+ )
103
+ fm_update = gr.Button(
104
+ value="🔄",
105
+ variant="tool",
106
+ )
107
+ fm_update.click(
108
+ update_fm_list,
109
+ inputs=[face_model],
110
+ outputs=[face_model],
111
+ )
112
+ imgs_hash_clear = gr.Button(
113
+ value="Clear Source Images Hash",
114
+ scale=1,
115
+ visible=False,
116
+ )
117
+ imgs_hash_clear.click(clear_faces_list,None,[progressbar_area])
118
+ gr.Markdown("<br>", visible=show_br)
119
+ with gr.Column(visible=True) as control_col_1:
120
+ with gr.Row():
121
+ selected_tab = gr.Textbox('tab_single', visible=False)
122
+ with gr.Tabs() as tab_single:
123
+ with gr.Tab('Single'):
124
+ img = gr.Image(
125
+ type="pil",
126
+ label="Single Source Image",
127
+ )
128
+ with gr.Tab('Multiple') as tab_multiple:
129
+ imgs = gr.Files(
130
+ label=f"Multiple Source Images{msgs['extra_multiple_source']}",
131
+ file_types=["image"],
132
+ )
133
+ tab_single.select(fn=lambda: 'tab_single', inputs=[], outputs=[selected_tab])
134
+ tab_multiple.select(fn=lambda: 'tab_multiple', inputs=[], outputs=[selected_tab])
135
+ with gr.Column(visible=False) as control_col_3:
136
+ 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>")
137
+ with gr.Row():
138
+ source_folder = gr.Textbox(
139
+ value="",
140
+ placeholder="Paste here the path to the folder containing source faces images",
141
+ label=f"Source Folder{msgs['extra_multiple_source']}",
142
+ scale=2,
143
+ )
144
+ random_image = gr.Checkbox(
145
+ False,
146
+ label="Random Image",
147
+ info="Randomly select an image from the path",
148
+ scale=1,
149
+ )
150
+ setattr(face_model, "do_not_save_to_config", True)
151
+ if is_img2img:
152
+ save_original = gr.Checkbox(
153
+ False,
154
+ label="Save Original (Swap in generated only)",
155
+ info="Save the original image(s) made before swapping"
156
+ )
157
+ else:
158
+ save_original = gr.Checkbox(
159
+ False,
160
+ label="Save Original",
161
+ info="Save the original image(s) made before swapping",
162
+ visible=show_br
163
+ )
164
+ # imgs.upload(on_files_upload_uncheck_so,[save_original],[save_original],show_progress=False)
165
+ # imgs.clear(on_files_clear,None,[save_original],show_progress=False)
166
+ imgs.clear(clear_faces_list,None,None,show_progress=False)
167
+ mask_face = gr.Checkbox(
168
+ False,
169
+ label="Face Mask Correction",
170
+ info="Apply this option if you see some pixelation around face contours"
171
+ )
172
+ gr.Markdown("<br>", visible=show_br)
173
+ gr.Markdown("Source Image (above):")
174
+ with gr.Row():
175
+ source_faces_index = gr.Textbox(
176
+ value="0",
177
+ placeholder="Which face(s) to use as Source (comma separated)",
178
+ label="Comma separated face number(s); Example: 0,2,1",
179
+ )
180
+ gender_source = gr.Radio(
181
+ ["No", "Female Only", "Male Only"],
182
+ value="No",
183
+ label="Gender Detection (Source)",
184
+ type="index",
185
+ )
186
+ gr.Markdown("<br>", visible=show_br)
187
+ gr.Markdown("Target Image (result):")
188
+ with gr.Row():
189
+ faces_index = gr.Textbox(
190
+ value="0",
191
+ placeholder="Which face(s) to Swap into Target (comma separated)",
192
+ label="Comma separated face number(s); Example: 1,0,2",
193
+ )
194
+ gender_target = gr.Radio(
195
+ ["No", "Female Only", "Male Only"],
196
+ value="No",
197
+ label="Gender Detection (Target)",
198
+ type="index",
199
+ )
200
+ gr.Markdown("<br>", visible=show_br)
201
+ with gr.Row():
202
+ face_restorer_name = gr.Radio(
203
+ label="Restore Face",
204
+ choices=["None"] + [x.name() for x in shared.face_restorers],
205
+ value=shared.face_restorers[0].name(),
206
+ type="value",
207
+ )
208
+ with gr.Column():
209
+ face_restorer_visibility = gr.Slider(
210
+ 0, 1, 1, step=0.1, label="Restore Face Visibility"
211
+ )
212
+ codeformer_weight = gr.Slider(
213
+ 0, 1, 0.5, step=0.1, label="CodeFormer Weight (Fidelity)", info="0 = far from original (max restoration), 1 = close to original (min restoration)"
214
+ )
215
+ gr.Markdown("<br>", visible=show_br)
216
+ swap_in_source = gr.Checkbox(
217
+ False,
218
+ label="Swap in source image",
219
+ visible=is_img2img,
220
+ )
221
+ swap_in_generated = gr.Checkbox(
222
+ True,
223
+ label="Swap in generated image",
224
+ visible=is_img2img,
225
+ )
226
+ # 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)
227
+ select_source.select(on_select_source,None,[control_col_1,control_col_2,control_col_3,imgs_hash_clear],show_progress=False)
228
+
229
+ 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
extensionsa/2-sd-webui-reactor/reactor_ui/reactor_settings_ui.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from scripts.reactor_logger import logger
3
+ from scripts.reactor_helpers import get_models, set_Device
4
+ from scripts.reactor_globals import DEVICE, DEVICE_LIST
5
+ try:
6
+ import torch.cuda as cuda
7
+ EP_is_visible = True if cuda.is_available() else False
8
+ except:
9
+ EP_is_visible = False
10
+
11
+ def update_models_list(selected: str):
12
+ return gr.Dropdown.update(
13
+ value=selected, choices=get_models()
14
+ )
15
+
16
+ def show(hash_check_block: bool = True):
17
+ # TAB SETTINGS
18
+ with gr.Tab("Settings"):
19
+ models = get_models()
20
+ with gr.Row(visible=EP_is_visible):
21
+ device = gr.Radio(
22
+ label="Execution Provider",
23
+ choices=DEVICE_LIST,
24
+ value=DEVICE,
25
+ type="value",
26
+ info="Click 'Save' to apply. If you already run 'Generate' - RESTART is required: (A1111) Extensions Tab -> 'Apply and restart UI' or (SD.Next) close the Server and start it again",
27
+ scale=2,
28
+ )
29
+ save_device_btn = gr.Button("Save", scale=0)
30
+ save = gr.Markdown("", visible=EP_is_visible)
31
+ setattr(device, "do_not_save_to_config", True)
32
+ save_device_btn.click(
33
+ set_Device,
34
+ inputs=[device],
35
+ outputs=[save],
36
+ )
37
+ with gr.Row():
38
+ if len(models) == 0:
39
+ logger.warning(
40
+ "You should at least have one model in models directory, please read the doc here: https://github.com/Gourieff/sd-webui-reactor/"
41
+ )
42
+ model = gr.Dropdown(
43
+ choices=models,
44
+ label="Model not found, please download one and refresh the list"
45
+ )
46
+ else:
47
+ model = gr.Dropdown(
48
+ choices=models, label="Model", value=models[0]
49
+ )
50
+ models_update = gr.Button(
51
+ value="🔄",
52
+ variant="tool",
53
+ )
54
+ models_update.click(
55
+ update_models_list,
56
+ inputs=[model],
57
+ outputs=[model],
58
+ )
59
+ console_logging_level = gr.Radio(
60
+ ["No log", "Minimum", "Default"],
61
+ value="Minimum",
62
+ label="Console Log Level",
63
+ type="index"
64
+ )
65
+ gr.Markdown("<br>", visible=hash_check_block)
66
+ with gr.Row(visible=hash_check_block):
67
+ source_hash_check = gr.Checkbox(
68
+ True,
69
+ label="Source Image Hash Check",
70
+ info="Recommended to keep it ON. Processing is faster when Source Image is the same."
71
+ )
72
+ target_hash_check = gr.Checkbox(
73
+ False,
74
+ label="Target Image Hash Check",
75
+ info="Affects if you use Extras tab or img2img with only 'Swap in source image' on."
76
+ )
77
+ return model, device, console_logging_level, source_hash_check, target_hash_check
extensionsa/2-sd-webui-reactor/reactor_ui/reactor_tools_ui.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from scripts.reactor_swapper import build_face_model, blend_faces
3
+
4
+ # TAB TOOLS
5
+ def show():
6
+ with gr.Tab("Tools"):
7
+ with gr.Tab("Face Models"):
8
+
9
+ with gr.Tab("Single"):
10
+ gr.Markdown("Load an image containing one person, name it and click 'Build and Save'")
11
+ img_fm = gr.Image(
12
+ type="pil",
13
+ label="Load an Image to build -Face Model-",
14
+ )
15
+ with gr.Row(equal_height=True):
16
+ fm_name = gr.Textbox(
17
+ value="",
18
+ placeholder="Please type any name (e.g. Elena)",
19
+ label="Face Model Name",
20
+ )
21
+ save_fm_btn = gr.Button("Build and Save")
22
+ save_fm = gr.Markdown("You can find saved models in 'models/reactor/faces'")
23
+ save_fm_btn.click(
24
+ build_face_model,
25
+ inputs=[img_fm, fm_name],
26
+ outputs=[save_fm],
27
+ )
28
+
29
+ with gr.Tab("Blend"):
30
+ gr.Markdown("Load a set of images containing any person, name it and click 'Build and Save'")
31
+ with gr.Row():
32
+ imgs_fm = gr.Files(
33
+ label=f"Load Images to build -Blended Face Model-",
34
+ file_types=["image"]
35
+ )
36
+ with gr.Column():
37
+ compute_method = gr.Radio(
38
+ ["Mean", "Median", "Mode"],
39
+ value="Mean",
40
+ label="Compute Method",
41
+ type="index",
42
+ 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"
43
+ )
44
+ shape_check = gr.Checkbox(
45
+ False,
46
+ label="Check -Embedding Shape- on Similarity",
47
+ 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'"
48
+ )
49
+ with gr.Row(equal_height=True):
50
+ fm_name = gr.Textbox(
51
+ value="",
52
+ placeholder="Please type any name (e.g. Elena)",
53
+ label="Face Model Name",
54
+ )
55
+ save_fm_btn = gr.Button("Build and Save")
56
+ save_fm = gr.Markdown("You can find saved models in 'models/reactor/faces'")
57
+ save_fm_btn.click(
58
+ blend_faces,
59
+ inputs=[imgs_fm, fm_name, compute_method, shape_check],
60
+ outputs=[save_fm],
61
+ )
extensionsa/2-sd-webui-reactor/reactor_ui/reactor_upscale_ui.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from modules import shared
3
+
4
+ def update_upscalers_list(selected: str):
5
+ return gr.Dropdown.update(
6
+ value=selected, choices=[upscaler.name for upscaler in shared.sd_upscalers]
7
+ )
8
+
9
+ # TAB UPSCALE
10
+ def show(show_br: bool = True):
11
+ with gr.Tab("Upscale"):
12
+ with gr.Row():
13
+ restore_first = gr.Checkbox(
14
+ True,
15
+ label="1. Restore Face -> 2. Upscale (-Uncheck- if you want vice versa)",
16
+ info="Postprocessing Order",
17
+ scale=2
18
+ )
19
+ upscale_force = gr.Checkbox(
20
+ False,
21
+ label="Force Upscale",
22
+ info="Upscale anyway - even if no face found",
23
+ scale=1
24
+ )
25
+ with gr.Row():
26
+ upscaler_name = gr.Dropdown(
27
+ choices=[upscaler.name for upscaler in shared.sd_upscalers],
28
+ label="Upscaler",
29
+ value="None",
30
+ info="Won't scale if you choose -Swap in Source- via img2img, only 1x-postprocessing will affect (texturing, denoising, restyling etc.)"
31
+ )
32
+ upscalers_update = gr.Button(
33
+ value="🔄",
34
+ variant="tool",
35
+ )
36
+ upscalers_update.click(
37
+ update_upscalers_list,
38
+ inputs=[upscaler_name],
39
+ outputs=[upscaler_name],
40
+ )
41
+ gr.Markdown("<br>", visible=show_br)
42
+ with gr.Row():
43
+ upscaler_scale = gr.Slider(1, 8, 1, step=0.1, label="Scale by")
44
+ upscaler_visibility = gr.Slider(
45
+ 0, 1, 1, step=0.1, label="Upscaler Visibility (if scale = 1)"
46
+ )
47
+ return restore_first, upscaler_name, upscaler_scale, upscaler_visibility, upscale_force
extensionsa/2-sd-webui-reactor/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ albumentations==1.4.3
2
+ insightface==0.7.3
3
+ onnx>=1.14.0
4
+ opencv-python>=4.7.0.72
extensionsa/2-sd-webui-reactor/scripts/__pycache__/console_log_patch.cpython-310.pyc ADDED
Binary file (4.3 kB). View file