first commit
This commit is contained in:
commit
e354d5af27
4
.eslintignore
Normal file
4
.eslintignore
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
extensions
|
||||||
|
extensions-disabled
|
||||||
|
repositories
|
||||||
|
venv
|
98
.eslintrc.js
Normal file
98
.eslintrc.js
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
/* global module */
|
||||||
|
module.exports = {
|
||||||
|
env: {
|
||||||
|
browser: true,
|
||||||
|
es2021: true,
|
||||||
|
},
|
||||||
|
extends: "eslint:recommended",
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: "latest",
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
"arrow-spacing": "error",
|
||||||
|
"block-spacing": "error",
|
||||||
|
"brace-style": "error",
|
||||||
|
"comma-dangle": ["error", "only-multiline"],
|
||||||
|
"comma-spacing": "error",
|
||||||
|
"comma-style": ["error", "last"],
|
||||||
|
"curly": ["error", "multi-line", "consistent"],
|
||||||
|
"eol-last": "error",
|
||||||
|
"func-call-spacing": "error",
|
||||||
|
"function-call-argument-newline": ["error", "consistent"],
|
||||||
|
"function-paren-newline": ["error", "consistent"],
|
||||||
|
"indent": ["error", 4],
|
||||||
|
"key-spacing": "error",
|
||||||
|
"keyword-spacing": "error",
|
||||||
|
"linebreak-style": ["error", "unix"],
|
||||||
|
"no-extra-semi": "error",
|
||||||
|
"no-mixed-spaces-and-tabs": "error",
|
||||||
|
"no-multi-spaces": "error",
|
||||||
|
"no-redeclare": ["error", {builtinGlobals: false}],
|
||||||
|
"no-trailing-spaces": "error",
|
||||||
|
"no-unused-vars": "off",
|
||||||
|
"no-whitespace-before-property": "error",
|
||||||
|
"object-curly-newline": ["error", {consistent: true, multiline: true}],
|
||||||
|
"object-curly-spacing": ["error", "never"],
|
||||||
|
"operator-linebreak": ["error", "after"],
|
||||||
|
"quote-props": ["error", "consistent-as-needed"],
|
||||||
|
"semi": ["error", "always"],
|
||||||
|
"semi-spacing": "error",
|
||||||
|
"semi-style": ["error", "last"],
|
||||||
|
"space-before-blocks": "error",
|
||||||
|
"space-before-function-paren": ["error", "never"],
|
||||||
|
"space-in-parens": ["error", "never"],
|
||||||
|
"space-infix-ops": "error",
|
||||||
|
"space-unary-ops": "error",
|
||||||
|
"switch-colon-spacing": "error",
|
||||||
|
"template-curly-spacing": ["error", "never"],
|
||||||
|
"unicode-bom": "error",
|
||||||
|
},
|
||||||
|
globals: {
|
||||||
|
//script.js
|
||||||
|
gradioApp: "readonly",
|
||||||
|
executeCallbacks: "readonly",
|
||||||
|
onAfterUiUpdate: "readonly",
|
||||||
|
onOptionsChanged: "readonly",
|
||||||
|
onUiLoaded: "readonly",
|
||||||
|
onUiUpdate: "readonly",
|
||||||
|
uiCurrentTab: "writable",
|
||||||
|
uiElementInSight: "readonly",
|
||||||
|
uiElementIsVisible: "readonly",
|
||||||
|
//ui.js
|
||||||
|
opts: "writable",
|
||||||
|
all_gallery_buttons: "readonly",
|
||||||
|
selected_gallery_button: "readonly",
|
||||||
|
selected_gallery_index: "readonly",
|
||||||
|
switch_to_txt2img: "readonly",
|
||||||
|
switch_to_img2img_tab: "readonly",
|
||||||
|
switch_to_img2img: "readonly",
|
||||||
|
switch_to_sketch: "readonly",
|
||||||
|
switch_to_inpaint: "readonly",
|
||||||
|
switch_to_inpaint_sketch: "readonly",
|
||||||
|
switch_to_extras: "readonly",
|
||||||
|
get_tab_index: "readonly",
|
||||||
|
create_submit_args: "readonly",
|
||||||
|
restart_reload: "readonly",
|
||||||
|
updateInput: "readonly",
|
||||||
|
onEdit: "readonly",
|
||||||
|
//extraNetworks.js
|
||||||
|
requestGet: "readonly",
|
||||||
|
popup: "readonly",
|
||||||
|
// profilerVisualization.js
|
||||||
|
createVisualizationTable: "readonly",
|
||||||
|
// from python
|
||||||
|
localization: "readonly",
|
||||||
|
// progrssbar.js
|
||||||
|
randomId: "readonly",
|
||||||
|
requestProgress: "readonly",
|
||||||
|
// imageviewer.js
|
||||||
|
modalPrevImage: "readonly",
|
||||||
|
modalNextImage: "readonly",
|
||||||
|
// localStorage.js
|
||||||
|
localSet: "readonly",
|
||||||
|
localGet: "readonly",
|
||||||
|
localRemove: "readonly",
|
||||||
|
// resizeHandle.js
|
||||||
|
setupResizeHandle: "writable"
|
||||||
|
}
|
||||||
|
};
|
2
.git-blame-ignore-revs
Normal file
2
.git-blame-ignore-revs
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# Apply ESlint
|
||||||
|
9c54b78d9dde5601e916f308d9a9d6953ec39430
|
105
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
105
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
name: Bug Report
|
||||||
|
description: You think something is broken in the UI
|
||||||
|
title: "[Bug]: "
|
||||||
|
labels: ["bug-report"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
> The title of the bug report should be short and descriptive.
|
||||||
|
> Use relevant keywords for searchability.
|
||||||
|
> Do not leave it blank, but also do not put an entire error log in it.
|
||||||
|
- type: checkboxes
|
||||||
|
attributes:
|
||||||
|
label: Checklist
|
||||||
|
description: |
|
||||||
|
Please perform basic debugging to see if extensions or configuration is the cause of the issue.
|
||||||
|
Basic debug procedure
|
||||||
|
1. Disable all third-party extensions - check if extension is the cause
|
||||||
|
2. Update extensions and webui - sometimes things just need to be updated
|
||||||
|
3. Backup and remove your config.json and ui-config.json - check if the issue is caused by bad configuration
|
||||||
|
4. Delete venv with third-party extensions disabled - sometimes extensions might cause wrong libraries to be installed
|
||||||
|
5. Try a fresh installation webui in a different directory - see if a clean installation solves the issue
|
||||||
|
Before making a issue report please, check that the issue hasn't been reported recently.
|
||||||
|
options:
|
||||||
|
- label: The issue exists after disabling all extensions
|
||||||
|
- label: The issue exists on a clean installation of webui
|
||||||
|
- label: The issue is caused by an extension, but I believe it is caused by a bug in the webui
|
||||||
|
- label: The issue exists in the current version of the webui
|
||||||
|
- label: The issue has not been reported before recently
|
||||||
|
- label: The issue has been reported before but has not been fixed yet
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
> Please fill this form with as much information as possible. Don't forget to "Upload Sysinfo" and "What browsers" and provide screenshots if possible
|
||||||
|
- type: textarea
|
||||||
|
id: what-did
|
||||||
|
attributes:
|
||||||
|
label: What happened?
|
||||||
|
description: Tell us what happened in a very clear and simple way
|
||||||
|
placeholder: |
|
||||||
|
txt2img is not working as intended.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: steps
|
||||||
|
attributes:
|
||||||
|
label: Steps to reproduce the problem
|
||||||
|
description: Please provide us with precise step by step instructions on how to reproduce the bug
|
||||||
|
placeholder: |
|
||||||
|
1. Go to ...
|
||||||
|
2. Press ...
|
||||||
|
3. ...
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: what-should
|
||||||
|
attributes:
|
||||||
|
label: What should have happened?
|
||||||
|
description: Tell us what you think the normal behavior should be
|
||||||
|
placeholder: |
|
||||||
|
WebUI should ...
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: browsers
|
||||||
|
attributes:
|
||||||
|
label: What browsers do you use to access the UI ?
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- Mozilla Firefox
|
||||||
|
- Google Chrome
|
||||||
|
- Brave
|
||||||
|
- Apple Safari
|
||||||
|
- Microsoft Edge
|
||||||
|
- Android
|
||||||
|
- iOS
|
||||||
|
- Other
|
||||||
|
- type: textarea
|
||||||
|
id: sysinfo
|
||||||
|
attributes:
|
||||||
|
label: Sysinfo
|
||||||
|
description: System info file, generated by WebUI. You can generate it in settings, on the Sysinfo page. Drag the file into the field to upload it. If you submit your report without including the sysinfo file, the report will be closed. If needed, review the report to make sure it includes no personal information you don't want to share. If you can't start WebUI, you can use --dump-sysinfo commandline argument to generate the file.
|
||||||
|
placeholder: |
|
||||||
|
1. Go to WebUI Settings -> Sysinfo -> Download system info.
|
||||||
|
If WebUI fails to launch, use --dump-sysinfo commandline argument to generate the file
|
||||||
|
2. Upload the Sysinfo as a attached file, Do NOT paste it in as plain text.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: Console logs
|
||||||
|
description: Please provide **full** cmd/terminal logs from the moment you started UI to the end of it, after the bug occurred. If it's very long, provide a link to pastebin or similar service.
|
||||||
|
render: Shell
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: misc
|
||||||
|
attributes:
|
||||||
|
label: Additional information
|
||||||
|
description: |
|
||||||
|
Please provide us with any relevant additional info or context.
|
||||||
|
Examples:
|
||||||
|
I have updated my GPU driver recently.
|
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
contact_links:
|
||||||
|
- name: WebUI Community Support
|
||||||
|
url: https://github.com/AUTOMATIC1111/stable-diffusion-webui/discussions
|
||||||
|
about: Please ask and answer questions here.
|
40
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
40
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
name: Feature request
|
||||||
|
description: Suggest an idea for this project
|
||||||
|
title: "[Feature Request]: "
|
||||||
|
labels: ["enhancement"]
|
||||||
|
|
||||||
|
body:
|
||||||
|
- type: checkboxes
|
||||||
|
attributes:
|
||||||
|
label: Is there an existing issue for this?
|
||||||
|
description: Please search to see if an issue already exists for the feature you want, and that it's not implemented in a recent build/commit.
|
||||||
|
options:
|
||||||
|
- label: I have searched the existing issues and checked the recent builds/commits
|
||||||
|
required: true
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
*Please fill this form with as much information as possible, provide screenshots and/or illustrations of the feature if possible*
|
||||||
|
- type: textarea
|
||||||
|
id: feature
|
||||||
|
attributes:
|
||||||
|
label: What would your feature do ?
|
||||||
|
description: Tell us about your feature in a very clear and simple way, and what problem it would solve
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: workflow
|
||||||
|
attributes:
|
||||||
|
label: Proposed workflow
|
||||||
|
description: Please provide us with step by step information on how you'd like the feature to be accessed and used
|
||||||
|
value: |
|
||||||
|
1. Go to ....
|
||||||
|
2. Press ....
|
||||||
|
3. ...
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: misc
|
||||||
|
attributes:
|
||||||
|
label: Additional information
|
||||||
|
description: Add any other context or screenshots about the feature request here.
|
15
.github/pull_request_template.md
vendored
Normal file
15
.github/pull_request_template.md
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
## Description
|
||||||
|
|
||||||
|
* a simple description of what you're trying to accomplish
|
||||||
|
* a summary of changes in code
|
||||||
|
* which issues it fixes, if any
|
||||||
|
|
||||||
|
## Screenshots/videos:
|
||||||
|
|
||||||
|
|
||||||
|
## Checklist:
|
||||||
|
|
||||||
|
- [ ] I have read [contributing wiki page](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing)
|
||||||
|
- [ ] I have performed a self-review of my own code
|
||||||
|
- [ ] My code follows the [style guidelines](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing#code-style)
|
||||||
|
- [ ] My code passes [tests](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Tests)
|
38
.github/workflows/on_pull_request.yaml
vendored
Normal file
38
.github/workflows/on_pull_request.yaml
vendored
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
name: Linter
|
||||||
|
|
||||||
|
on:
|
||||||
|
- push
|
||||||
|
- pull_request
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint-python:
|
||||||
|
name: ruff
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: 3.11
|
||||||
|
# NB: there's no cache: pip here since we're not installing anything
|
||||||
|
# from the requirements.txt file(s) in the repository; it's faster
|
||||||
|
# not to have GHA download an (at the time of writing) 4 GB cache
|
||||||
|
# of PyTorch and other dependencies.
|
||||||
|
- name: Install Ruff
|
||||||
|
run: pip install ruff==0.3.3
|
||||||
|
- name: Run Ruff
|
||||||
|
run: ruff .
|
||||||
|
lint-js:
|
||||||
|
name: eslint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Install Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 18
|
||||||
|
- run: npm i --ci
|
||||||
|
- run: npm run lint
|
81
.github/workflows/run_tests.yaml
vendored
Normal file
81
.github/workflows/run_tests.yaml
vendored
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
name: Tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
- push
|
||||||
|
- pull_request
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: tests on CPU with empty model
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up Python 3.10
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: 3.10.6
|
||||||
|
cache: pip
|
||||||
|
cache-dependency-path: |
|
||||||
|
**/requirements*txt
|
||||||
|
launch.py
|
||||||
|
- name: Cache models
|
||||||
|
id: cache-models
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: models
|
||||||
|
key: "2023-12-30"
|
||||||
|
- name: Install test dependencies
|
||||||
|
run: pip install wait-for-it -r requirements-test.txt
|
||||||
|
env:
|
||||||
|
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
||||||
|
PIP_PROGRESS_BAR: "off"
|
||||||
|
- name: Setup environment
|
||||||
|
run: python launch.py --skip-torch-cuda-test --exit
|
||||||
|
env:
|
||||||
|
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
||||||
|
PIP_PROGRESS_BAR: "off"
|
||||||
|
TORCH_INDEX_URL: https://download.pytorch.org/whl/cpu
|
||||||
|
WEBUI_LAUNCH_LIVE_OUTPUT: "1"
|
||||||
|
PYTHONUNBUFFERED: "1"
|
||||||
|
- name: Print installed packages
|
||||||
|
run: pip freeze
|
||||||
|
- name: Start test server
|
||||||
|
run: >
|
||||||
|
python -m coverage run
|
||||||
|
--data-file=.coverage.server
|
||||||
|
launch.py
|
||||||
|
--skip-prepare-environment
|
||||||
|
--skip-torch-cuda-test
|
||||||
|
--test-server
|
||||||
|
--do-not-download-clip
|
||||||
|
--no-half
|
||||||
|
--disable-opt-split-attention
|
||||||
|
--use-cpu all
|
||||||
|
--api-server-stop
|
||||||
|
2>&1 | tee output.txt &
|
||||||
|
- name: Run tests
|
||||||
|
run: |
|
||||||
|
wait-for-it --service 127.0.0.1:7860 -t 20
|
||||||
|
python -m pytest -vv --junitxml=test/results.xml --cov . --cov-report=xml --verify-base-url test
|
||||||
|
- name: Kill test server
|
||||||
|
if: always()
|
||||||
|
run: curl -vv -XPOST http://127.0.0.1:7860/sdapi/v1/server-stop && sleep 10
|
||||||
|
- name: Show coverage
|
||||||
|
run: |
|
||||||
|
python -m coverage combine .coverage*
|
||||||
|
python -m coverage report -i
|
||||||
|
python -m coverage html -i
|
||||||
|
- name: Upload main app output
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
name: output
|
||||||
|
path: output.txt
|
||||||
|
- name: Upload coverage HTML
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
name: htmlcov
|
||||||
|
path: htmlcov
|
19
.github/workflows/warns_merge_master.yml
vendored
Normal file
19
.github/workflows/warns_merge_master.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
name: Pull requests can't target master branch
|
||||||
|
|
||||||
|
"on":
|
||||||
|
pull_request:
|
||||||
|
types:
|
||||||
|
- opened
|
||||||
|
- synchronize
|
||||||
|
- reopened
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Warning marge into master
|
||||||
|
run: |
|
||||||
|
echo -e "::warning::This pull request directly merge into \"master\" branch, normally development happens on \"dev\" branch."
|
||||||
|
exit 1
|
44
.gitignore
vendored
Normal file
44
.gitignore
vendored
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
__pycache__
|
||||||
|
*.ckpt
|
||||||
|
*.safetensors
|
||||||
|
*.pth
|
||||||
|
.DS_Store
|
||||||
|
/ESRGAN/*
|
||||||
|
/SwinIR/*
|
||||||
|
/repositories
|
||||||
|
/venv
|
||||||
|
/tmp
|
||||||
|
/model.ckpt
|
||||||
|
/models/**/*
|
||||||
|
/GFPGANv1.3.pth
|
||||||
|
/gfpgan/weights/*.pth
|
||||||
|
/ui-config.json
|
||||||
|
/outputs
|
||||||
|
/config.json
|
||||||
|
/log
|
||||||
|
/webui.settings.bat
|
||||||
|
/embeddings
|
||||||
|
/styles.csv
|
||||||
|
/params.txt
|
||||||
|
/styles.csv.bak
|
||||||
|
/webui-user.bat
|
||||||
|
/webui-user.sh
|
||||||
|
/interrogate
|
||||||
|
/user.css
|
||||||
|
/.idea
|
||||||
|
notification.mp3
|
||||||
|
/SwinIR
|
||||||
|
/textual_inversion
|
||||||
|
.vscode
|
||||||
|
/extensions
|
||||||
|
/test/stdout.txt
|
||||||
|
/test/stderr.txt
|
||||||
|
/cache.json*
|
||||||
|
/config_states/
|
||||||
|
/node_modules
|
||||||
|
/package-lock.json
|
||||||
|
/.coverage*
|
||||||
|
/test/test_outputs
|
||||||
|
/cache
|
||||||
|
trace.json
|
||||||
|
/sysinfo-????-??-??-??-??.json
|
3
.pylintrc
Normal file
3
.pylintrc
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# See https://pylint.pycqa.org/en/latest/user_guide/messages/message_control.html
|
||||||
|
[MESSAGES CONTROL]
|
||||||
|
disable=C,R,W,E,I
|
1085
CHANGELOG.md
Normal file
1085
CHANGELOG.md
Normal file
File diff suppressed because it is too large
Load Diff
7
CITATION.cff
Normal file
7
CITATION.cff
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
cff-version: 1.2.0
|
||||||
|
message: "If you use this software, please cite it as below."
|
||||||
|
authors:
|
||||||
|
- given-names: AUTOMATIC1111
|
||||||
|
title: "Stable Diffusion Web UI"
|
||||||
|
date-released: 2022-08-22
|
||||||
|
url: "https://github.com/AUTOMATIC1111/stable-diffusion-webui"
|
12
CODEOWNERS
Normal file
12
CODEOWNERS
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
* @AUTOMATIC1111
|
||||||
|
|
||||||
|
# if you were managing a localization and were removed from this file, this is because
|
||||||
|
# the intended way to do localizations now is via extensions. See:
|
||||||
|
# https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Developing-extensions
|
||||||
|
# Make a repo with your localization and since you are still listed as a collaborator
|
||||||
|
# you can add it to the wiki page yourself. This change is because some people complained
|
||||||
|
# the git commit log is cluttered with things unrelated to almost everyone and
|
||||||
|
# because I believe this is the best overall for the project to handle localizations almost
|
||||||
|
# entirely without my oversight.
|
||||||
|
|
||||||
|
|
663
LICENSE.txt
Normal file
663
LICENSE.txt
Normal file
@ -0,0 +1,663 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (c) 2023 AUTOMATIC1111
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
205
README.md
Normal file
205
README.md
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
# Stable Diffusion web UI
|
||||||
|
A web interface for Stable Diffusion, implemented using Gradio library.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Features
|
||||||
|
[Detailed feature showcase with images](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features):
|
||||||
|
- Original txt2img and img2img modes
|
||||||
|
- One click install and run script (but you still must install python and git)
|
||||||
|
- Outpainting
|
||||||
|
- Inpainting
|
||||||
|
- Color Sketch
|
||||||
|
- Prompt Matrix
|
||||||
|
- Stable Diffusion Upscale
|
||||||
|
- Attention, specify parts of text that the model should pay more attention to
|
||||||
|
- a man in a `((tuxedo))` - will pay more attention to tuxedo
|
||||||
|
- a man in a `(tuxedo:1.21)` - alternative syntax
|
||||||
|
- select text and press `Ctrl+Up` or `Ctrl+Down` (or `Command+Up` or `Command+Down` if you're on a MacOS) to automatically adjust attention to selected text (code contributed by anonymous user)
|
||||||
|
- Loopback, run img2img processing multiple times
|
||||||
|
- X/Y/Z plot, a way to draw a 3 dimensional plot of images with different parameters
|
||||||
|
- Textual Inversion
|
||||||
|
- have as many embeddings as you want and use any names you like for them
|
||||||
|
- use multiple embeddings with different numbers of vectors per token
|
||||||
|
- works with half precision floating point numbers
|
||||||
|
- train embeddings on 8GB (also reports of 6GB working)
|
||||||
|
- Extras tab with:
|
||||||
|
- GFPGAN, neural network that fixes faces
|
||||||
|
- CodeFormer, face restoration tool as an alternative to GFPGAN
|
||||||
|
- RealESRGAN, neural network upscaler
|
||||||
|
- ESRGAN, neural network upscaler with a lot of third party models
|
||||||
|
- SwinIR and Swin2SR ([see here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/2092)), neural network upscalers
|
||||||
|
- LDSR, Latent diffusion super resolution upscaling
|
||||||
|
- Resizing aspect ratio options
|
||||||
|
- Sampling method selection
|
||||||
|
- Adjust sampler eta values (noise multiplier)
|
||||||
|
- More advanced noise setting options
|
||||||
|
- Interrupt processing at any time
|
||||||
|
- 4GB video card support (also reports of 2GB working)
|
||||||
|
- Correct seeds for batches
|
||||||
|
- Live prompt token length validation
|
||||||
|
- Generation parameters
|
||||||
|
- parameters you used to generate images are saved with that image
|
||||||
|
- in PNG chunks for PNG, in EXIF for JPEG
|
||||||
|
- can drag the image to PNG info tab to restore generation parameters and automatically copy them into UI
|
||||||
|
- can be disabled in settings
|
||||||
|
- drag and drop an image/text-parameters to promptbox
|
||||||
|
- Read Generation Parameters Button, loads parameters in promptbox to UI
|
||||||
|
- Settings page
|
||||||
|
- Running arbitrary python code from UI (must run with `--allow-code` to enable)
|
||||||
|
- Mouseover hints for most UI elements
|
||||||
|
- Possible to change defaults/mix/max/step values for UI elements via text config
|
||||||
|
- Tiling support, a checkbox to create images that can be tiled like textures
|
||||||
|
- Progress bar and live image generation preview
|
||||||
|
- Can use a separate neural network to produce previews with almost none VRAM or compute requirement
|
||||||
|
- Negative prompt, an extra text field that allows you to list what you don't want to see in generated image
|
||||||
|
- Styles, a way to save part of prompt and easily apply them via dropdown later
|
||||||
|
- Variations, a way to generate same image but with tiny differences
|
||||||
|
- Seed resizing, a way to generate same image but at slightly different resolution
|
||||||
|
- CLIP interrogator, a button that tries to guess prompt from an image
|
||||||
|
- Prompt Editing, a way to change prompt mid-generation, say to start making a watermelon and switch to anime girl midway
|
||||||
|
- Batch Processing, process a group of files using img2img
|
||||||
|
- Img2img Alternative, reverse Euler method of cross attention control
|
||||||
|
- Highres Fix, a convenience option to produce high resolution pictures in one click without usual distortions
|
||||||
|
- Reloading checkpoints on the fly
|
||||||
|
- Checkpoint Merger, a tab that allows you to merge up to 3 checkpoints into one
|
||||||
|
- [Custom scripts](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Custom-Scripts) with many extensions from community
|
||||||
|
- [Composable-Diffusion](https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/), a way to use multiple prompts at once
|
||||||
|
- separate prompts using uppercase `AND`
|
||||||
|
- also supports weights for prompts: `a cat :1.2 AND a dog AND a penguin :2.2`
|
||||||
|
- No token limit for prompts (original stable diffusion lets you use up to 75 tokens)
|
||||||
|
- DeepDanbooru integration, creates danbooru style tags for anime prompts
|
||||||
|
- [xformers](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Xformers), major speed increase for select cards: (add `--xformers` to commandline args)
|
||||||
|
- via extension: [History tab](https://github.com/yfszzx/stable-diffusion-webui-images-browser): view, direct and delete images conveniently within the UI
|
||||||
|
- Generate forever option
|
||||||
|
- Training tab
|
||||||
|
- hypernetworks and embeddings options
|
||||||
|
- Preprocessing images: cropping, mirroring, autotagging using BLIP or deepdanbooru (for anime)
|
||||||
|
- Clip skip
|
||||||
|
- Hypernetworks
|
||||||
|
- Loras (same as Hypernetworks but more pretty)
|
||||||
|
- A separate UI where you can choose, with preview, which embeddings, hypernetworks or Loras to add to your prompt
|
||||||
|
- Can select to load a different VAE from settings screen
|
||||||
|
- Estimated completion time in progress bar
|
||||||
|
- API
|
||||||
|
- Support for dedicated [inpainting model](https://github.com/runwayml/stable-diffusion#inpainting-with-stable-diffusion) by RunwayML
|
||||||
|
- via extension: [Aesthetic Gradients](https://github.com/AUTOMATIC1111/stable-diffusion-webui-aesthetic-gradients), a way to generate images with a specific aesthetic by using clip images embeds (implementation of [https://github.com/vicgalle/stable-diffusion-aesthetic-gradients](https://github.com/vicgalle/stable-diffusion-aesthetic-gradients))
|
||||||
|
- [Stable Diffusion 2.0](https://github.com/Stability-AI/stablediffusion) support - see [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#stable-diffusion-20) for instructions
|
||||||
|
- [Alt-Diffusion](https://arxiv.org/abs/2211.06679) support - see [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#alt-diffusion) for instructions
|
||||||
|
- Now without any bad letters!
|
||||||
|
- Load checkpoints in safetensors format
|
||||||
|
- Eased resolution restriction: generated image's dimensions must be a multiple of 8 rather than 64
|
||||||
|
- Now with a license!
|
||||||
|
- Reorder elements in the UI from settings screen
|
||||||
|
- [Segmind Stable Diffusion](https://huggingface.co/segmind/SSD-1B) support
|
||||||
|
|
||||||
|
## Installation and Running
|
||||||
|
Make sure the required [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) are met and follow the instructions available for:
|
||||||
|
- [NVidia](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs) (recommended)
|
||||||
|
- [AMD](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-AMD-GPUs) GPUs.
|
||||||
|
- [Intel CPUs, Intel GPUs (both integrated and discrete)](https://github.com/openvinotoolkit/stable-diffusion-webui/wiki/Installation-on-Intel-Silicon) (external wiki page)
|
||||||
|
- [Ascend NPUs](https://github.com/wangshuai09/stable-diffusion-webui/wiki/Install-and-run-on-Ascend-NPUs) (external wiki page)
|
||||||
|
|
||||||
|
Alternatively, use online services (like Google Colab):
|
||||||
|
|
||||||
|
- [List of Online Services](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Online-Services)
|
||||||
|
|
||||||
|
### Installation on Windows 10/11 with NVidia-GPUs using release package
|
||||||
|
1. Download `sd.webui.zip` from [v1.0.0-pre](https://github.com/AUTOMATIC1111/stable-diffusion-webui/releases/tag/v1.0.0-pre) and extract its contents.
|
||||||
|
2. Run `update.bat`.
|
||||||
|
3. Run `run.bat`.
|
||||||
|
> For more details see [Install-and-Run-on-NVidia-GPUs](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs)
|
||||||
|
|
||||||
|
### Automatic Installation on Windows
|
||||||
|
1. Install [Python 3.10.6](https://www.python.org/downloads/release/python-3106/) (Newer version of Python does not support torch), checking "Add Python to PATH".
|
||||||
|
2. Install [git](https://git-scm.com/download/win).
|
||||||
|
3. Download the stable-diffusion-webui repository, for example by running `git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git`.
|
||||||
|
4. Run `webui-user.bat` from Windows Explorer as normal, non-administrator, user.
|
||||||
|
|
||||||
|
### Automatic Installation on Linux
|
||||||
|
1. Install the dependencies:
|
||||||
|
```bash
|
||||||
|
# Debian-based:
|
||||||
|
sudo apt install wget git python3 python3-venv libgl1 libglib2.0-0
|
||||||
|
# Red Hat-based:
|
||||||
|
sudo dnf install wget git python3 gperftools-libs libglvnd-glx
|
||||||
|
# openSUSE-based:
|
||||||
|
sudo zypper install wget git python3 libtcmalloc4 libglvnd
|
||||||
|
# Arch-based:
|
||||||
|
sudo pacman -S wget git python3
|
||||||
|
```
|
||||||
|
If your system is very new, you need to install python3.11 or python3.10:
|
||||||
|
```bash
|
||||||
|
# Ubuntu 24.04
|
||||||
|
sudo add-apt-repository ppa:deadsnakes/ppa
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install python3.11
|
||||||
|
|
||||||
|
# Manjaro/Arch
|
||||||
|
sudo pacman -S yay
|
||||||
|
yay -S python311 # do not confuse with python3.11 package
|
||||||
|
|
||||||
|
# Only for 3.11
|
||||||
|
# Then set up env variable in launch script
|
||||||
|
export python_cmd="python3.11"
|
||||||
|
# or in webui-user.sh
|
||||||
|
python_cmd="python3.11"
|
||||||
|
```
|
||||||
|
2. Navigate to the directory you would like the webui to be installed and execute the following command:
|
||||||
|
```bash
|
||||||
|
wget -q https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/master/webui.sh
|
||||||
|
```
|
||||||
|
Or just clone the repo wherever you want:
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Run `webui.sh`.
|
||||||
|
4. Check `webui-user.sh` for options.
|
||||||
|
### Installation on Apple Silicon
|
||||||
|
|
||||||
|
Find the instructions [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Installation-on-Apple-Silicon).
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
Here's how to add code to this repo: [Contributing](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing)
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
The documentation was moved from this README over to the project's [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki).
|
||||||
|
|
||||||
|
For the purposes of getting Google and other search engines to crawl the wiki, here's a link to the (not for humans) [crawlable wiki](https://github-wiki-see.page/m/AUTOMATIC1111/stable-diffusion-webui/wiki).
|
||||||
|
|
||||||
|
## Credits
|
||||||
|
Licenses for borrowed code can be found in `Settings -> Licenses` screen, and also in `html/licenses.html` file.
|
||||||
|
|
||||||
|
- Stable Diffusion - https://github.com/Stability-AI/stablediffusion, https://github.com/CompVis/taming-transformers, https://github.com/mcmonkey4eva/sd3-ref
|
||||||
|
- k-diffusion - https://github.com/crowsonkb/k-diffusion.git
|
||||||
|
- Spandrel - https://github.com/chaiNNer-org/spandrel implementing
|
||||||
|
- GFPGAN - https://github.com/TencentARC/GFPGAN.git
|
||||||
|
- CodeFormer - https://github.com/sczhou/CodeFormer
|
||||||
|
- ESRGAN - https://github.com/xinntao/ESRGAN
|
||||||
|
- SwinIR - https://github.com/JingyunLiang/SwinIR
|
||||||
|
- Swin2SR - https://github.com/mv-lab/swin2sr
|
||||||
|
- LDSR - https://github.com/Hafiidz/latent-diffusion
|
||||||
|
- MiDaS - https://github.com/isl-org/MiDaS
|
||||||
|
- Ideas for optimizations - https://github.com/basujindal/stable-diffusion
|
||||||
|
- Cross Attention layer optimization - Doggettx - https://github.com/Doggettx/stable-diffusion, original idea for prompt editing.
|
||||||
|
- Cross Attention layer optimization - InvokeAI, lstein - https://github.com/invoke-ai/InvokeAI (originally http://github.com/lstein/stable-diffusion)
|
||||||
|
- Sub-quadratic Cross Attention layer optimization - Alex Birch (https://github.com/Birch-san/diffusers/pull/1), Amin Rezaei (https://github.com/AminRezaei0x443/memory-efficient-attention)
|
||||||
|
- Textual Inversion - Rinon Gal - https://github.com/rinongal/textual_inversion (we're not using his code, but we are using his ideas).
|
||||||
|
- Idea for SD upscale - https://github.com/jquesnelle/txt2imghd
|
||||||
|
- Noise generation for outpainting mk2 - https://github.com/parlance-zz/g-diffuser-bot
|
||||||
|
- CLIP interrogator idea and borrowing some code - https://github.com/pharmapsychotic/clip-interrogator
|
||||||
|
- Idea for Composable Diffusion - https://github.com/energy-based-model/Compositional-Visual-Generation-with-Composable-Diffusion-Models-PyTorch
|
||||||
|
- xformers - https://github.com/facebookresearch/xformers
|
||||||
|
- DeepDanbooru - interrogator for anime diffusers https://github.com/KichangKim/DeepDanbooru
|
||||||
|
- Sampling in float32 precision from a float16 UNet - marunine for the idea, Birch-san for the example Diffusers implementation (https://github.com/Birch-san/diffusers-play/tree/92feee6)
|
||||||
|
- Instruct pix2pix - Tim Brooks (star), Aleksander Holynski (star), Alexei A. Efros (no star) - https://github.com/timothybrooks/instruct-pix2pix
|
||||||
|
- Security advice - RyotaK
|
||||||
|
- UniPC sampler - Wenliang Zhao - https://github.com/wl-zhao/UniPC
|
||||||
|
- TAESD - Ollin Boer Bohan - https://github.com/madebyollin/taesd
|
||||||
|
- LyCORIS - KohakuBlueleaf
|
||||||
|
- Restart sampling - lambertae - https://github.com/Newbeeer/diffusion_restart_sampling
|
||||||
|
- Hypertile - tfernd - https://github.com/tfernd/HyperTile
|
||||||
|
- Initial Gradio script - posted on 4chan by an Anonymous user. Thank you Anonymous user.
|
||||||
|
- (You)
|
5
_typos.toml
Normal file
5
_typos.toml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
[default.extend-words]
|
||||||
|
# Part of "RGBa" (Pillow's pre-multiplied alpha RGB mode)
|
||||||
|
Ba = "Ba"
|
||||||
|
# HSA is something AMD uses for their GPUs
|
||||||
|
HSA = "HSA"
|
72
configs/alt-diffusion-inference.yaml
Normal file
72
configs/alt-diffusion-inference.yaml
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
model:
|
||||||
|
base_learning_rate: 1.0e-04
|
||||||
|
target: ldm.models.diffusion.ddpm.LatentDiffusion
|
||||||
|
params:
|
||||||
|
linear_start: 0.00085
|
||||||
|
linear_end: 0.0120
|
||||||
|
num_timesteps_cond: 1
|
||||||
|
log_every_t: 200
|
||||||
|
timesteps: 1000
|
||||||
|
first_stage_key: "jpg"
|
||||||
|
cond_stage_key: "txt"
|
||||||
|
image_size: 64
|
||||||
|
channels: 4
|
||||||
|
cond_stage_trainable: false # Note: different from the one we trained before
|
||||||
|
conditioning_key: crossattn
|
||||||
|
monitor: val/loss_simple_ema
|
||||||
|
scale_factor: 0.18215
|
||||||
|
use_ema: False
|
||||||
|
|
||||||
|
scheduler_config: # 10000 warmup steps
|
||||||
|
target: ldm.lr_scheduler.LambdaLinearScheduler
|
||||||
|
params:
|
||||||
|
warm_up_steps: [ 10000 ]
|
||||||
|
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
||||||
|
f_start: [ 1.e-6 ]
|
||||||
|
f_max: [ 1. ]
|
||||||
|
f_min: [ 1. ]
|
||||||
|
|
||||||
|
unet_config:
|
||||||
|
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
||||||
|
params:
|
||||||
|
image_size: 32 # unused
|
||||||
|
in_channels: 4
|
||||||
|
out_channels: 4
|
||||||
|
model_channels: 320
|
||||||
|
attention_resolutions: [ 4, 2, 1 ]
|
||||||
|
num_res_blocks: 2
|
||||||
|
channel_mult: [ 1, 2, 4, 4 ]
|
||||||
|
num_heads: 8
|
||||||
|
use_spatial_transformer: True
|
||||||
|
transformer_depth: 1
|
||||||
|
context_dim: 768
|
||||||
|
use_checkpoint: False
|
||||||
|
legacy: False
|
||||||
|
|
||||||
|
first_stage_config:
|
||||||
|
target: ldm.models.autoencoder.AutoencoderKL
|
||||||
|
params:
|
||||||
|
embed_dim: 4
|
||||||
|
monitor: val/rec_loss
|
||||||
|
ddconfig:
|
||||||
|
double_z: true
|
||||||
|
z_channels: 4
|
||||||
|
resolution: 256
|
||||||
|
in_channels: 3
|
||||||
|
out_ch: 3
|
||||||
|
ch: 128
|
||||||
|
ch_mult:
|
||||||
|
- 1
|
||||||
|
- 2
|
||||||
|
- 4
|
||||||
|
- 4
|
||||||
|
num_res_blocks: 2
|
||||||
|
attn_resolutions: []
|
||||||
|
dropout: 0.0
|
||||||
|
lossconfig:
|
||||||
|
target: torch.nn.Identity
|
||||||
|
|
||||||
|
cond_stage_config:
|
||||||
|
target: modules.xlmr.BertSeriesModelWithTransformation
|
||||||
|
params:
|
||||||
|
name: "XLMR-Large"
|
73
configs/alt-diffusion-m18-inference.yaml
Normal file
73
configs/alt-diffusion-m18-inference.yaml
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
model:
|
||||||
|
base_learning_rate: 1.0e-04
|
||||||
|
target: ldm.models.diffusion.ddpm.LatentDiffusion
|
||||||
|
params:
|
||||||
|
linear_start: 0.00085
|
||||||
|
linear_end: 0.0120
|
||||||
|
num_timesteps_cond: 1
|
||||||
|
log_every_t: 200
|
||||||
|
timesteps: 1000
|
||||||
|
first_stage_key: "jpg"
|
||||||
|
cond_stage_key: "txt"
|
||||||
|
image_size: 64
|
||||||
|
channels: 4
|
||||||
|
cond_stage_trainable: false # Note: different from the one we trained before
|
||||||
|
conditioning_key: crossattn
|
||||||
|
monitor: val/loss_simple_ema
|
||||||
|
scale_factor: 0.18215
|
||||||
|
use_ema: False
|
||||||
|
|
||||||
|
scheduler_config: # 10000 warmup steps
|
||||||
|
target: ldm.lr_scheduler.LambdaLinearScheduler
|
||||||
|
params:
|
||||||
|
warm_up_steps: [ 10000 ]
|
||||||
|
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
||||||
|
f_start: [ 1.e-6 ]
|
||||||
|
f_max: [ 1. ]
|
||||||
|
f_min: [ 1. ]
|
||||||
|
|
||||||
|
unet_config:
|
||||||
|
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
||||||
|
params:
|
||||||
|
image_size: 32 # unused
|
||||||
|
in_channels: 4
|
||||||
|
out_channels: 4
|
||||||
|
model_channels: 320
|
||||||
|
attention_resolutions: [ 4, 2, 1 ]
|
||||||
|
num_res_blocks: 2
|
||||||
|
channel_mult: [ 1, 2, 4, 4 ]
|
||||||
|
num_head_channels: 64
|
||||||
|
use_spatial_transformer: True
|
||||||
|
use_linear_in_transformer: True
|
||||||
|
transformer_depth: 1
|
||||||
|
context_dim: 1024
|
||||||
|
use_checkpoint: False
|
||||||
|
legacy: False
|
||||||
|
|
||||||
|
first_stage_config:
|
||||||
|
target: ldm.models.autoencoder.AutoencoderKL
|
||||||
|
params:
|
||||||
|
embed_dim: 4
|
||||||
|
monitor: val/rec_loss
|
||||||
|
ddconfig:
|
||||||
|
double_z: true
|
||||||
|
z_channels: 4
|
||||||
|
resolution: 256
|
||||||
|
in_channels: 3
|
||||||
|
out_ch: 3
|
||||||
|
ch: 128
|
||||||
|
ch_mult:
|
||||||
|
- 1
|
||||||
|
- 2
|
||||||
|
- 4
|
||||||
|
- 4
|
||||||
|
num_res_blocks: 2
|
||||||
|
attn_resolutions: []
|
||||||
|
dropout: 0.0
|
||||||
|
lossconfig:
|
||||||
|
target: torch.nn.Identity
|
||||||
|
|
||||||
|
cond_stage_config:
|
||||||
|
target: modules.xlmr_m18.BertSeriesModelWithTransformation
|
||||||
|
params:
|
||||||
|
name: "XLMR-Large"
|
98
configs/instruct-pix2pix.yaml
Normal file
98
configs/instruct-pix2pix.yaml
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
|
||||||
|
# See more details in LICENSE.
|
||||||
|
|
||||||
|
model:
|
||||||
|
base_learning_rate: 1.0e-04
|
||||||
|
target: modules.models.diffusion.ddpm_edit.LatentDiffusion
|
||||||
|
params:
|
||||||
|
linear_start: 0.00085
|
||||||
|
linear_end: 0.0120
|
||||||
|
num_timesteps_cond: 1
|
||||||
|
log_every_t: 200
|
||||||
|
timesteps: 1000
|
||||||
|
first_stage_key: edited
|
||||||
|
cond_stage_key: edit
|
||||||
|
# image_size: 64
|
||||||
|
# image_size: 32
|
||||||
|
image_size: 16
|
||||||
|
channels: 4
|
||||||
|
cond_stage_trainable: false # Note: different from the one we trained before
|
||||||
|
conditioning_key: hybrid
|
||||||
|
monitor: val/loss_simple_ema
|
||||||
|
scale_factor: 0.18215
|
||||||
|
use_ema: false
|
||||||
|
|
||||||
|
scheduler_config: # 10000 warmup steps
|
||||||
|
target: ldm.lr_scheduler.LambdaLinearScheduler
|
||||||
|
params:
|
||||||
|
warm_up_steps: [ 0 ]
|
||||||
|
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
||||||
|
f_start: [ 1.e-6 ]
|
||||||
|
f_max: [ 1. ]
|
||||||
|
f_min: [ 1. ]
|
||||||
|
|
||||||
|
unet_config:
|
||||||
|
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
||||||
|
params:
|
||||||
|
image_size: 32 # unused
|
||||||
|
in_channels: 8
|
||||||
|
out_channels: 4
|
||||||
|
model_channels: 320
|
||||||
|
attention_resolutions: [ 4, 2, 1 ]
|
||||||
|
num_res_blocks: 2
|
||||||
|
channel_mult: [ 1, 2, 4, 4 ]
|
||||||
|
num_heads: 8
|
||||||
|
use_spatial_transformer: True
|
||||||
|
transformer_depth: 1
|
||||||
|
context_dim: 768
|
||||||
|
use_checkpoint: False
|
||||||
|
legacy: False
|
||||||
|
|
||||||
|
first_stage_config:
|
||||||
|
target: ldm.models.autoencoder.AutoencoderKL
|
||||||
|
params:
|
||||||
|
embed_dim: 4
|
||||||
|
monitor: val/rec_loss
|
||||||
|
ddconfig:
|
||||||
|
double_z: true
|
||||||
|
z_channels: 4
|
||||||
|
resolution: 256
|
||||||
|
in_channels: 3
|
||||||
|
out_ch: 3
|
||||||
|
ch: 128
|
||||||
|
ch_mult:
|
||||||
|
- 1
|
||||||
|
- 2
|
||||||
|
- 4
|
||||||
|
- 4
|
||||||
|
num_res_blocks: 2
|
||||||
|
attn_resolutions: []
|
||||||
|
dropout: 0.0
|
||||||
|
lossconfig:
|
||||||
|
target: torch.nn.Identity
|
||||||
|
|
||||||
|
cond_stage_config:
|
||||||
|
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
||||||
|
|
||||||
|
data:
|
||||||
|
target: main.DataModuleFromConfig
|
||||||
|
params:
|
||||||
|
batch_size: 128
|
||||||
|
num_workers: 1
|
||||||
|
wrap: false
|
||||||
|
validation:
|
||||||
|
target: edit_dataset.EditDataset
|
||||||
|
params:
|
||||||
|
path: data/clip-filtered-dataset
|
||||||
|
cache_dir: data/
|
||||||
|
cache_name: data_10k
|
||||||
|
split: val
|
||||||
|
min_text_sim: 0.2
|
||||||
|
min_image_sim: 0.75
|
||||||
|
min_direction_sim: 0.2
|
||||||
|
max_samples_per_prompt: 1
|
||||||
|
min_resize_res: 512
|
||||||
|
max_resize_res: 512
|
||||||
|
crop_res: 512
|
||||||
|
output_as_edit: False
|
||||||
|
real_input: True
|
5
configs/sd3-inference.yaml
Normal file
5
configs/sd3-inference.yaml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
model:
|
||||||
|
target: modules.models.sd3.sd3_model.SD3Inferencer
|
||||||
|
params:
|
||||||
|
shift: 3
|
||||||
|
state_dict: null
|
98
configs/sd_xl_inpaint.yaml
Normal file
98
configs/sd_xl_inpaint.yaml
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
model:
|
||||||
|
target: sgm.models.diffusion.DiffusionEngine
|
||||||
|
params:
|
||||||
|
scale_factor: 0.13025
|
||||||
|
disable_first_stage_autocast: True
|
||||||
|
|
||||||
|
denoiser_config:
|
||||||
|
target: sgm.modules.diffusionmodules.denoiser.DiscreteDenoiser
|
||||||
|
params:
|
||||||
|
num_idx: 1000
|
||||||
|
|
||||||
|
weighting_config:
|
||||||
|
target: sgm.modules.diffusionmodules.denoiser_weighting.EpsWeighting
|
||||||
|
scaling_config:
|
||||||
|
target: sgm.modules.diffusionmodules.denoiser_scaling.EpsScaling
|
||||||
|
discretization_config:
|
||||||
|
target: sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization
|
||||||
|
|
||||||
|
network_config:
|
||||||
|
target: sgm.modules.diffusionmodules.openaimodel.UNetModel
|
||||||
|
params:
|
||||||
|
adm_in_channels: 2816
|
||||||
|
num_classes: sequential
|
||||||
|
use_checkpoint: False
|
||||||
|
in_channels: 9
|
||||||
|
out_channels: 4
|
||||||
|
model_channels: 320
|
||||||
|
attention_resolutions: [4, 2]
|
||||||
|
num_res_blocks: 2
|
||||||
|
channel_mult: [1, 2, 4]
|
||||||
|
num_head_channels: 64
|
||||||
|
use_spatial_transformer: True
|
||||||
|
use_linear_in_transformer: True
|
||||||
|
transformer_depth: [1, 2, 10] # note: the first is unused (due to attn_res starting at 2) 32, 16, 8 --> 64, 32, 16
|
||||||
|
context_dim: 2048
|
||||||
|
spatial_transformer_attn_type: softmax-xformers
|
||||||
|
legacy: False
|
||||||
|
|
||||||
|
conditioner_config:
|
||||||
|
target: sgm.modules.GeneralConditioner
|
||||||
|
params:
|
||||||
|
emb_models:
|
||||||
|
# crossattn cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: txt
|
||||||
|
target: sgm.modules.encoders.modules.FrozenCLIPEmbedder
|
||||||
|
params:
|
||||||
|
layer: hidden
|
||||||
|
layer_idx: 11
|
||||||
|
# crossattn and vector cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: txt
|
||||||
|
target: sgm.modules.encoders.modules.FrozenOpenCLIPEmbedder2
|
||||||
|
params:
|
||||||
|
arch: ViT-bigG-14
|
||||||
|
version: laion2b_s39b_b160k
|
||||||
|
freeze: True
|
||||||
|
layer: penultimate
|
||||||
|
always_return_pooled: True
|
||||||
|
legacy: False
|
||||||
|
# vector cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: original_size_as_tuple
|
||||||
|
target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
|
||||||
|
params:
|
||||||
|
outdim: 256 # multiplied by two
|
||||||
|
# vector cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: crop_coords_top_left
|
||||||
|
target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
|
||||||
|
params:
|
||||||
|
outdim: 256 # multiplied by two
|
||||||
|
# vector cond
|
||||||
|
- is_trainable: False
|
||||||
|
input_key: target_size_as_tuple
|
||||||
|
target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
|
||||||
|
params:
|
||||||
|
outdim: 256 # multiplied by two
|
||||||
|
|
||||||
|
first_stage_config:
|
||||||
|
target: sgm.models.autoencoder.AutoencoderKLInferenceWrapper
|
||||||
|
params:
|
||||||
|
embed_dim: 4
|
||||||
|
monitor: val/rec_loss
|
||||||
|
ddconfig:
|
||||||
|
attn_type: vanilla-xformers
|
||||||
|
double_z: true
|
||||||
|
z_channels: 4
|
||||||
|
resolution: 256
|
||||||
|
in_channels: 3
|
||||||
|
out_ch: 3
|
||||||
|
ch: 128
|
||||||
|
ch_mult: [1, 2, 4, 4]
|
||||||
|
num_res_blocks: 2
|
||||||
|
attn_resolutions: []
|
||||||
|
dropout: 0.0
|
||||||
|
lossconfig:
|
||||||
|
target: torch.nn.Identity
|
70
configs/v1-inference.yaml
Normal file
70
configs/v1-inference.yaml
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
model:
|
||||||
|
base_learning_rate: 1.0e-04
|
||||||
|
target: ldm.models.diffusion.ddpm.LatentDiffusion
|
||||||
|
params:
|
||||||
|
linear_start: 0.00085
|
||||||
|
linear_end: 0.0120
|
||||||
|
num_timesteps_cond: 1
|
||||||
|
log_every_t: 200
|
||||||
|
timesteps: 1000
|
||||||
|
first_stage_key: "jpg"
|
||||||
|
cond_stage_key: "txt"
|
||||||
|
image_size: 64
|
||||||
|
channels: 4
|
||||||
|
cond_stage_trainable: false # Note: different from the one we trained before
|
||||||
|
conditioning_key: crossattn
|
||||||
|
monitor: val/loss_simple_ema
|
||||||
|
scale_factor: 0.18215
|
||||||
|
use_ema: False
|
||||||
|
|
||||||
|
scheduler_config: # 10000 warmup steps
|
||||||
|
target: ldm.lr_scheduler.LambdaLinearScheduler
|
||||||
|
params:
|
||||||
|
warm_up_steps: [ 10000 ]
|
||||||
|
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
||||||
|
f_start: [ 1.e-6 ]
|
||||||
|
f_max: [ 1. ]
|
||||||
|
f_min: [ 1. ]
|
||||||
|
|
||||||
|
unet_config:
|
||||||
|
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
||||||
|
params:
|
||||||
|
image_size: 32 # unused
|
||||||
|
in_channels: 4
|
||||||
|
out_channels: 4
|
||||||
|
model_channels: 320
|
||||||
|
attention_resolutions: [ 4, 2, 1 ]
|
||||||
|
num_res_blocks: 2
|
||||||
|
channel_mult: [ 1, 2, 4, 4 ]
|
||||||
|
num_heads: 8
|
||||||
|
use_spatial_transformer: True
|
||||||
|
transformer_depth: 1
|
||||||
|
context_dim: 768
|
||||||
|
use_checkpoint: False
|
||||||
|
legacy: False
|
||||||
|
|
||||||
|
first_stage_config:
|
||||||
|
target: ldm.models.autoencoder.AutoencoderKL
|
||||||
|
params:
|
||||||
|
embed_dim: 4
|
||||||
|
monitor: val/rec_loss
|
||||||
|
ddconfig:
|
||||||
|
double_z: true
|
||||||
|
z_channels: 4
|
||||||
|
resolution: 256
|
||||||
|
in_channels: 3
|
||||||
|
out_ch: 3
|
||||||
|
ch: 128
|
||||||
|
ch_mult:
|
||||||
|
- 1
|
||||||
|
- 2
|
||||||
|
- 4
|
||||||
|
- 4
|
||||||
|
num_res_blocks: 2
|
||||||
|
attn_resolutions: []
|
||||||
|
dropout: 0.0
|
||||||
|
lossconfig:
|
||||||
|
target: torch.nn.Identity
|
||||||
|
|
||||||
|
cond_stage_config:
|
||||||
|
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
70
configs/v1-inpainting-inference.yaml
Normal file
70
configs/v1-inpainting-inference.yaml
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
model:
|
||||||
|
base_learning_rate: 7.5e-05
|
||||||
|
target: ldm.models.diffusion.ddpm.LatentInpaintDiffusion
|
||||||
|
params:
|
||||||
|
linear_start: 0.00085
|
||||||
|
linear_end: 0.0120
|
||||||
|
num_timesteps_cond: 1
|
||||||
|
log_every_t: 200
|
||||||
|
timesteps: 1000
|
||||||
|
first_stage_key: "jpg"
|
||||||
|
cond_stage_key: "txt"
|
||||||
|
image_size: 64
|
||||||
|
channels: 4
|
||||||
|
cond_stage_trainable: false # Note: different from the one we trained before
|
||||||
|
conditioning_key: hybrid # important
|
||||||
|
monitor: val/loss_simple_ema
|
||||||
|
scale_factor: 0.18215
|
||||||
|
finetune_keys: null
|
||||||
|
|
||||||
|
scheduler_config: # 10000 warmup steps
|
||||||
|
target: ldm.lr_scheduler.LambdaLinearScheduler
|
||||||
|
params:
|
||||||
|
warm_up_steps: [ 2500 ] # NOTE for resuming. use 10000 if starting from scratch
|
||||||
|
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
||||||
|
f_start: [ 1.e-6 ]
|
||||||
|
f_max: [ 1. ]
|
||||||
|
f_min: [ 1. ]
|
||||||
|
|
||||||
|
unet_config:
|
||||||
|
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
||||||
|
params:
|
||||||
|
image_size: 32 # unused
|
||||||
|
in_channels: 9 # 4 data + 4 downscaled image + 1 mask
|
||||||
|
out_channels: 4
|
||||||
|
model_channels: 320
|
||||||
|
attention_resolutions: [ 4, 2, 1 ]
|
||||||
|
num_res_blocks: 2
|
||||||
|
channel_mult: [ 1, 2, 4, 4 ]
|
||||||
|
num_heads: 8
|
||||||
|
use_spatial_transformer: True
|
||||||
|
transformer_depth: 1
|
||||||
|
context_dim: 768
|
||||||
|
use_checkpoint: False
|
||||||
|
legacy: False
|
||||||
|
|
||||||
|
first_stage_config:
|
||||||
|
target: ldm.models.autoencoder.AutoencoderKL
|
||||||
|
params:
|
||||||
|
embed_dim: 4
|
||||||
|
monitor: val/rec_loss
|
||||||
|
ddconfig:
|
||||||
|
double_z: true
|
||||||
|
z_channels: 4
|
||||||
|
resolution: 256
|
||||||
|
in_channels: 3
|
||||||
|
out_ch: 3
|
||||||
|
ch: 128
|
||||||
|
ch_mult:
|
||||||
|
- 1
|
||||||
|
- 2
|
||||||
|
- 4
|
||||||
|
- 4
|
||||||
|
num_res_blocks: 2
|
||||||
|
attn_resolutions: []
|
||||||
|
dropout: 0.0
|
||||||
|
lossconfig:
|
||||||
|
target: torch.nn.Identity
|
||||||
|
|
||||||
|
cond_stage_config:
|
||||||
|
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
11
environment-wsl2.yaml
Normal file
11
environment-wsl2.yaml
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
name: automatic
|
||||||
|
channels:
|
||||||
|
- pytorch
|
||||||
|
- defaults
|
||||||
|
dependencies:
|
||||||
|
- python=3.10
|
||||||
|
- pip=23.0
|
||||||
|
- cudatoolkit=11.8
|
||||||
|
- pytorch=2.0
|
||||||
|
- torchvision=0.15
|
||||||
|
- numpy=1.23
|
250
extensions-builtin/LDSR/ldsr_model_arch.py
Normal file
250
extensions-builtin/LDSR/ldsr_model_arch.py
Normal file
@ -0,0 +1,250 @@
|
|||||||
|
import os
|
||||||
|
import gc
|
||||||
|
import time
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import torchvision
|
||||||
|
from PIL import Image
|
||||||
|
from einops import rearrange, repeat
|
||||||
|
from omegaconf import OmegaConf
|
||||||
|
import safetensors.torch
|
||||||
|
|
||||||
|
from ldm.models.diffusion.ddim import DDIMSampler
|
||||||
|
from ldm.util import instantiate_from_config, ismap
|
||||||
|
from modules import shared, sd_hijack, devices
|
||||||
|
|
||||||
|
cached_ldsr_model: torch.nn.Module = None
|
||||||
|
|
||||||
|
|
||||||
|
# Create LDSR Class
|
||||||
|
class LDSR:
|
||||||
|
def load_model_from_config(self, half_attention):
|
||||||
|
global cached_ldsr_model
|
||||||
|
|
||||||
|
if shared.opts.ldsr_cached and cached_ldsr_model is not None:
|
||||||
|
print("Loading model from cache")
|
||||||
|
model: torch.nn.Module = cached_ldsr_model
|
||||||
|
else:
|
||||||
|
print(f"Loading model from {self.modelPath}")
|
||||||
|
_, extension = os.path.splitext(self.modelPath)
|
||||||
|
if extension.lower() == ".safetensors":
|
||||||
|
pl_sd = safetensors.torch.load_file(self.modelPath, device="cpu")
|
||||||
|
else:
|
||||||
|
pl_sd = torch.load(self.modelPath, map_location="cpu")
|
||||||
|
sd = pl_sd["state_dict"] if "state_dict" in pl_sd else pl_sd
|
||||||
|
config = OmegaConf.load(self.yamlPath)
|
||||||
|
config.model.target = "ldm.models.diffusion.ddpm.LatentDiffusionV1"
|
||||||
|
model: torch.nn.Module = instantiate_from_config(config.model)
|
||||||
|
model.load_state_dict(sd, strict=False)
|
||||||
|
model = model.to(shared.device)
|
||||||
|
if half_attention:
|
||||||
|
model = model.half()
|
||||||
|
if shared.cmd_opts.opt_channelslast:
|
||||||
|
model = model.to(memory_format=torch.channels_last)
|
||||||
|
|
||||||
|
sd_hijack.model_hijack.hijack(model) # apply optimization
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
if shared.opts.ldsr_cached:
|
||||||
|
cached_ldsr_model = model
|
||||||
|
|
||||||
|
return {"model": model}
|
||||||
|
|
||||||
|
def __init__(self, model_path, yaml_path):
|
||||||
|
self.modelPath = model_path
|
||||||
|
self.yamlPath = yaml_path
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def run(model, selected_path, custom_steps, eta):
|
||||||
|
example = get_cond(selected_path)
|
||||||
|
|
||||||
|
n_runs = 1
|
||||||
|
guider = None
|
||||||
|
ckwargs = None
|
||||||
|
ddim_use_x0_pred = False
|
||||||
|
temperature = 1.
|
||||||
|
eta = eta
|
||||||
|
custom_shape = None
|
||||||
|
|
||||||
|
height, width = example["image"].shape[1:3]
|
||||||
|
split_input = height >= 128 and width >= 128
|
||||||
|
|
||||||
|
if split_input:
|
||||||
|
ks = 128
|
||||||
|
stride = 64
|
||||||
|
vqf = 4 #
|
||||||
|
model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride),
|
||||||
|
"vqf": vqf,
|
||||||
|
"patch_distributed_vq": True,
|
||||||
|
"tie_braker": False,
|
||||||
|
"clip_max_weight": 0.5,
|
||||||
|
"clip_min_weight": 0.01,
|
||||||
|
"clip_max_tie_weight": 0.5,
|
||||||
|
"clip_min_tie_weight": 0.01}
|
||||||
|
else:
|
||||||
|
if hasattr(model, "split_input_params"):
|
||||||
|
delattr(model, "split_input_params")
|
||||||
|
|
||||||
|
x_t = None
|
||||||
|
logs = None
|
||||||
|
for _ in range(n_runs):
|
||||||
|
if custom_shape is not None:
|
||||||
|
x_t = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)
|
||||||
|
x_t = repeat(x_t, '1 c h w -> b c h w', b=custom_shape[0])
|
||||||
|
|
||||||
|
logs = make_convolutional_sample(example, model,
|
||||||
|
custom_steps=custom_steps,
|
||||||
|
eta=eta, quantize_x0=False,
|
||||||
|
custom_shape=custom_shape,
|
||||||
|
temperature=temperature, noise_dropout=0.,
|
||||||
|
corrector=guider, corrector_kwargs=ckwargs, x_T=x_t,
|
||||||
|
ddim_use_x0_pred=ddim_use_x0_pred
|
||||||
|
)
|
||||||
|
return logs
|
||||||
|
|
||||||
|
def super_resolution(self, image, steps=100, target_scale=2, half_attention=False):
|
||||||
|
model = self.load_model_from_config(half_attention)
|
||||||
|
|
||||||
|
# Run settings
|
||||||
|
diffusion_steps = int(steps)
|
||||||
|
eta = 1.0
|
||||||
|
|
||||||
|
|
||||||
|
gc.collect()
|
||||||
|
devices.torch_gc()
|
||||||
|
|
||||||
|
im_og = image
|
||||||
|
width_og, height_og = im_og.size
|
||||||
|
# If we can adjust the max upscale size, then the 4 below should be our variable
|
||||||
|
down_sample_rate = target_scale / 4
|
||||||
|
wd = width_og * down_sample_rate
|
||||||
|
hd = height_og * down_sample_rate
|
||||||
|
width_downsampled_pre = int(np.ceil(wd))
|
||||||
|
height_downsampled_pre = int(np.ceil(hd))
|
||||||
|
|
||||||
|
if down_sample_rate != 1:
|
||||||
|
print(
|
||||||
|
f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]')
|
||||||
|
im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS)
|
||||||
|
else:
|
||||||
|
print(f"Down sample rate is 1 from {target_scale} / 4 (Not downsampling)")
|
||||||
|
|
||||||
|
# pad width and height to multiples of 64, pads with the edge values of image to avoid artifacts
|
||||||
|
pad_w, pad_h = np.max(((2, 2), np.ceil(np.array(im_og.size) / 64).astype(int)), axis=0) * 64 - im_og.size
|
||||||
|
im_padded = Image.fromarray(np.pad(np.array(im_og), ((0, pad_h), (0, pad_w), (0, 0)), mode='edge'))
|
||||||
|
|
||||||
|
logs = self.run(model["model"], im_padded, diffusion_steps, eta)
|
||||||
|
|
||||||
|
sample = logs["sample"]
|
||||||
|
sample = sample.detach().cpu()
|
||||||
|
sample = torch.clamp(sample, -1., 1.)
|
||||||
|
sample = (sample + 1.) / 2. * 255
|
||||||
|
sample = sample.numpy().astype(np.uint8)
|
||||||
|
sample = np.transpose(sample, (0, 2, 3, 1))
|
||||||
|
a = Image.fromarray(sample[0])
|
||||||
|
|
||||||
|
# remove padding
|
||||||
|
a = a.crop((0, 0) + tuple(np.array(im_og.size) * 4))
|
||||||
|
|
||||||
|
del model
|
||||||
|
gc.collect()
|
||||||
|
devices.torch_gc()
|
||||||
|
|
||||||
|
return a
|
||||||
|
|
||||||
|
|
||||||
|
def get_cond(selected_path):
|
||||||
|
example = {}
|
||||||
|
up_f = 4
|
||||||
|
c = selected_path.convert('RGB')
|
||||||
|
c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)
|
||||||
|
c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]],
|
||||||
|
antialias=True)
|
||||||
|
c_up = rearrange(c_up, '1 c h w -> 1 h w c')
|
||||||
|
c = rearrange(c, '1 c h w -> 1 h w c')
|
||||||
|
c = 2. * c - 1.
|
||||||
|
|
||||||
|
c = c.to(shared.device)
|
||||||
|
example["LR_image"] = c
|
||||||
|
example["image"] = c_up
|
||||||
|
|
||||||
|
return example
|
||||||
|
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None,
|
||||||
|
mask=None, x0=None, quantize_x0=False, temperature=1., score_corrector=None,
|
||||||
|
corrector_kwargs=None, x_t=None
|
||||||
|
):
|
||||||
|
ddim = DDIMSampler(model)
|
||||||
|
bs = shape[0]
|
||||||
|
shape = shape[1:]
|
||||||
|
print(f"Sampling with eta = {eta}; steps: {steps}")
|
||||||
|
samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback,
|
||||||
|
normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta,
|
||||||
|
mask=mask, x0=x0, temperature=temperature, verbose=False,
|
||||||
|
score_corrector=score_corrector,
|
||||||
|
corrector_kwargs=corrector_kwargs, x_t=x_t)
|
||||||
|
|
||||||
|
return samples, intermediates
|
||||||
|
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def make_convolutional_sample(batch, model, custom_steps=None, eta=1.0, quantize_x0=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,
|
||||||
|
corrector_kwargs=None, x_T=None, ddim_use_x0_pred=False):
|
||||||
|
log = {}
|
||||||
|
|
||||||
|
z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,
|
||||||
|
return_first_stage_outputs=True,
|
||||||
|
force_c_encode=not (hasattr(model, 'split_input_params')
|
||||||
|
and model.cond_stage_key == 'coordinates_bbox'),
|
||||||
|
return_original_cond=True)
|
||||||
|
|
||||||
|
if custom_shape is not None:
|
||||||
|
z = torch.randn(custom_shape)
|
||||||
|
print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}")
|
||||||
|
|
||||||
|
z0 = None
|
||||||
|
|
||||||
|
log["input"] = x
|
||||||
|
log["reconstruction"] = xrec
|
||||||
|
|
||||||
|
if ismap(xc):
|
||||||
|
log["original_conditioning"] = model.to_rgb(xc)
|
||||||
|
if hasattr(model, 'cond_stage_key'):
|
||||||
|
log[model.cond_stage_key] = model.to_rgb(xc)
|
||||||
|
|
||||||
|
else:
|
||||||
|
log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x)
|
||||||
|
if model.cond_stage_model:
|
||||||
|
log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x)
|
||||||
|
if model.cond_stage_key == 'class_label':
|
||||||
|
log[model.cond_stage_key] = xc[model.cond_stage_key]
|
||||||
|
|
||||||
|
with model.ema_scope("Plotting"):
|
||||||
|
t0 = time.time()
|
||||||
|
|
||||||
|
sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape,
|
||||||
|
eta=eta,
|
||||||
|
quantize_x0=quantize_x0, mask=None, x0=z0,
|
||||||
|
temperature=temperature, score_corrector=corrector, corrector_kwargs=corrector_kwargs,
|
||||||
|
x_t=x_T)
|
||||||
|
t1 = time.time()
|
||||||
|
|
||||||
|
if ddim_use_x0_pred:
|
||||||
|
sample = intermediates['pred_x0'][-1]
|
||||||
|
|
||||||
|
x_sample = model.decode_first_stage(sample)
|
||||||
|
|
||||||
|
try:
|
||||||
|
x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)
|
||||||
|
log["sample_noquant"] = x_sample_noquant
|
||||||
|
log["sample_diff"] = torch.abs(x_sample_noquant - x_sample)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
log["sample"] = x_sample
|
||||||
|
log["time"] = t1 - t0
|
||||||
|
|
||||||
|
return log
|
6
extensions-builtin/LDSR/preload.py
Normal file
6
extensions-builtin/LDSR/preload.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
import os
|
||||||
|
from modules import paths
|
||||||
|
|
||||||
|
|
||||||
|
def preload(parser):
|
||||||
|
parser.add_argument("--ldsr-models-path", type=str, help="Path to directory with LDSR model file(s).", default=os.path.join(paths.models_path, 'LDSR'))
|
68
extensions-builtin/LDSR/scripts/ldsr_model.py
Normal file
68
extensions-builtin/LDSR/scripts/ldsr_model.py
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
from modules.modelloader import load_file_from_url
|
||||||
|
from modules.upscaler import Upscaler, UpscalerData
|
||||||
|
from ldsr_model_arch import LDSR
|
||||||
|
from modules import shared, script_callbacks, errors
|
||||||
|
import sd_hijack_autoencoder # noqa: F401
|
||||||
|
import sd_hijack_ddpm_v1 # noqa: F401
|
||||||
|
|
||||||
|
|
||||||
|
class UpscalerLDSR(Upscaler):
|
||||||
|
def __init__(self, user_path):
|
||||||
|
self.name = "LDSR"
|
||||||
|
self.user_path = user_path
|
||||||
|
self.model_url = "https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1"
|
||||||
|
self.yaml_url = "https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1"
|
||||||
|
super().__init__()
|
||||||
|
scaler_data = UpscalerData("LDSR", None, self)
|
||||||
|
self.scalers = [scaler_data]
|
||||||
|
|
||||||
|
def load_model(self, path: str):
|
||||||
|
# Remove incorrect project.yaml file if too big
|
||||||
|
yaml_path = os.path.join(self.model_path, "project.yaml")
|
||||||
|
old_model_path = os.path.join(self.model_path, "model.pth")
|
||||||
|
new_model_path = os.path.join(self.model_path, "model.ckpt")
|
||||||
|
|
||||||
|
local_model_paths = self.find_models(ext_filter=[".ckpt", ".safetensors"])
|
||||||
|
local_ckpt_path = next(iter([local_model for local_model in local_model_paths if local_model.endswith("model.ckpt")]), None)
|
||||||
|
local_safetensors_path = next(iter([local_model for local_model in local_model_paths if local_model.endswith("model.safetensors")]), None)
|
||||||
|
local_yaml_path = next(iter([local_model for local_model in local_model_paths if local_model.endswith("project.yaml")]), None)
|
||||||
|
|
||||||
|
if os.path.exists(yaml_path):
|
||||||
|
statinfo = os.stat(yaml_path)
|
||||||
|
if statinfo.st_size >= 10485760:
|
||||||
|
print("Removing invalid LDSR YAML file.")
|
||||||
|
os.remove(yaml_path)
|
||||||
|
|
||||||
|
if os.path.exists(old_model_path):
|
||||||
|
print("Renaming model from model.pth to model.ckpt")
|
||||||
|
os.rename(old_model_path, new_model_path)
|
||||||
|
|
||||||
|
if local_safetensors_path is not None and os.path.exists(local_safetensors_path):
|
||||||
|
model = local_safetensors_path
|
||||||
|
else:
|
||||||
|
model = local_ckpt_path or load_file_from_url(self.model_url, model_dir=self.model_download_path, file_name="model.ckpt")
|
||||||
|
|
||||||
|
yaml = local_yaml_path or load_file_from_url(self.yaml_url, model_dir=self.model_download_path, file_name="project.yaml")
|
||||||
|
|
||||||
|
return LDSR(model, yaml)
|
||||||
|
|
||||||
|
def do_upscale(self, img, path):
|
||||||
|
try:
|
||||||
|
ldsr = self.load_model(path)
|
||||||
|
except Exception:
|
||||||
|
errors.report(f"Failed loading LDSR model {path}", exc_info=True)
|
||||||
|
return img
|
||||||
|
ddim_steps = shared.opts.ldsr_steps
|
||||||
|
return ldsr.super_resolution(img, ddim_steps, self.scale)
|
||||||
|
|
||||||
|
|
||||||
|
def on_ui_settings():
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
shared.opts.add_option("ldsr_steps", shared.OptionInfo(100, "LDSR processing steps. Lower = faster", gr.Slider, {"minimum": 1, "maximum": 200, "step": 1}, section=('upscaling', "Upscaling")))
|
||||||
|
shared.opts.add_option("ldsr_cached", shared.OptionInfo(False, "Cache LDSR model in memory", gr.Checkbox, {"interactive": True}, section=('upscaling', "Upscaling")))
|
||||||
|
|
||||||
|
|
||||||
|
script_callbacks.on_ui_settings(on_ui_settings)
|
293
extensions-builtin/LDSR/sd_hijack_autoencoder.py
Normal file
293
extensions-builtin/LDSR/sd_hijack_autoencoder.py
Normal file
@ -0,0 +1,293 @@
|
|||||||
|
# The content of this file comes from the ldm/models/autoencoder.py file of the compvis/stable-diffusion repo
|
||||||
|
# The VQModel & VQModelInterface were subsequently removed from ldm/models/autoencoder.py when we moved to the stability-ai/stablediffusion repo
|
||||||
|
# As the LDSR upscaler relies on VQModel & VQModelInterface, the hijack aims to put them back into the ldm.models.autoencoder
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import pytorch_lightning as pl
|
||||||
|
import torch.nn.functional as F
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
from torch.optim.lr_scheduler import LambdaLR
|
||||||
|
|
||||||
|
from ldm.modules.ema import LitEma
|
||||||
|
from vqvae_quantize import VectorQuantizer2 as VectorQuantizer
|
||||||
|
from ldm.modules.diffusionmodules.model import Encoder, Decoder
|
||||||
|
from ldm.util import instantiate_from_config
|
||||||
|
|
||||||
|
import ldm.models.autoencoder
|
||||||
|
from packaging import version
|
||||||
|
|
||||||
|
class VQModel(pl.LightningModule):
|
||||||
|
def __init__(self,
|
||||||
|
ddconfig,
|
||||||
|
lossconfig,
|
||||||
|
n_embed,
|
||||||
|
embed_dim,
|
||||||
|
ckpt_path=None,
|
||||||
|
ignore_keys=None,
|
||||||
|
image_key="image",
|
||||||
|
colorize_nlabels=None,
|
||||||
|
monitor=None,
|
||||||
|
batch_resize_range=None,
|
||||||
|
scheduler_config=None,
|
||||||
|
lr_g_factor=1.0,
|
||||||
|
remap=None,
|
||||||
|
sane_index_shape=False, # tell vector quantizer to return indices as bhw
|
||||||
|
use_ema=False
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.embed_dim = embed_dim
|
||||||
|
self.n_embed = n_embed
|
||||||
|
self.image_key = image_key
|
||||||
|
self.encoder = Encoder(**ddconfig)
|
||||||
|
self.decoder = Decoder(**ddconfig)
|
||||||
|
self.loss = instantiate_from_config(lossconfig)
|
||||||
|
self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25,
|
||||||
|
remap=remap,
|
||||||
|
sane_index_shape=sane_index_shape)
|
||||||
|
self.quant_conv = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
|
||||||
|
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
||||||
|
if colorize_nlabels is not None:
|
||||||
|
assert type(colorize_nlabels)==int
|
||||||
|
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
||||||
|
if monitor is not None:
|
||||||
|
self.monitor = monitor
|
||||||
|
self.batch_resize_range = batch_resize_range
|
||||||
|
if self.batch_resize_range is not None:
|
||||||
|
print(f"{self.__class__.__name__}: Using per-batch resizing in range {batch_resize_range}.")
|
||||||
|
|
||||||
|
self.use_ema = use_ema
|
||||||
|
if self.use_ema:
|
||||||
|
self.model_ema = LitEma(self)
|
||||||
|
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
||||||
|
|
||||||
|
if ckpt_path is not None:
|
||||||
|
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys or [])
|
||||||
|
self.scheduler_config = scheduler_config
|
||||||
|
self.lr_g_factor = lr_g_factor
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def ema_scope(self, context=None):
|
||||||
|
if self.use_ema:
|
||||||
|
self.model_ema.store(self.parameters())
|
||||||
|
self.model_ema.copy_to(self)
|
||||||
|
if context is not None:
|
||||||
|
print(f"{context}: Switched to EMA weights")
|
||||||
|
try:
|
||||||
|
yield None
|
||||||
|
finally:
|
||||||
|
if self.use_ema:
|
||||||
|
self.model_ema.restore(self.parameters())
|
||||||
|
if context is not None:
|
||||||
|
print(f"{context}: Restored training weights")
|
||||||
|
|
||||||
|
def init_from_ckpt(self, path, ignore_keys=None):
|
||||||
|
sd = torch.load(path, map_location="cpu")["state_dict"]
|
||||||
|
keys = list(sd.keys())
|
||||||
|
for k in keys:
|
||||||
|
for ik in ignore_keys or []:
|
||||||
|
if k.startswith(ik):
|
||||||
|
print("Deleting key {} from state_dict.".format(k))
|
||||||
|
del sd[k]
|
||||||
|
missing, unexpected = self.load_state_dict(sd, strict=False)
|
||||||
|
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
||||||
|
if missing:
|
||||||
|
print(f"Missing Keys: {missing}")
|
||||||
|
if unexpected:
|
||||||
|
print(f"Unexpected Keys: {unexpected}")
|
||||||
|
|
||||||
|
def on_train_batch_end(self, *args, **kwargs):
|
||||||
|
if self.use_ema:
|
||||||
|
self.model_ema(self)
|
||||||
|
|
||||||
|
def encode(self, x):
|
||||||
|
h = self.encoder(x)
|
||||||
|
h = self.quant_conv(h)
|
||||||
|
quant, emb_loss, info = self.quantize(h)
|
||||||
|
return quant, emb_loss, info
|
||||||
|
|
||||||
|
def encode_to_prequant(self, x):
|
||||||
|
h = self.encoder(x)
|
||||||
|
h = self.quant_conv(h)
|
||||||
|
return h
|
||||||
|
|
||||||
|
def decode(self, quant):
|
||||||
|
quant = self.post_quant_conv(quant)
|
||||||
|
dec = self.decoder(quant)
|
||||||
|
return dec
|
||||||
|
|
||||||
|
def decode_code(self, code_b):
|
||||||
|
quant_b = self.quantize.embed_code(code_b)
|
||||||
|
dec = self.decode(quant_b)
|
||||||
|
return dec
|
||||||
|
|
||||||
|
def forward(self, input, return_pred_indices=False):
|
||||||
|
quant, diff, (_,_,ind) = self.encode(input)
|
||||||
|
dec = self.decode(quant)
|
||||||
|
if return_pred_indices:
|
||||||
|
return dec, diff, ind
|
||||||
|
return dec, diff
|
||||||
|
|
||||||
|
def get_input(self, batch, k):
|
||||||
|
x = batch[k]
|
||||||
|
if len(x.shape) == 3:
|
||||||
|
x = x[..., None]
|
||||||
|
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
|
||||||
|
if self.batch_resize_range is not None:
|
||||||
|
lower_size = self.batch_resize_range[0]
|
||||||
|
upper_size = self.batch_resize_range[1]
|
||||||
|
if self.global_step <= 4:
|
||||||
|
# do the first few batches with max size to avoid later oom
|
||||||
|
new_resize = upper_size
|
||||||
|
else:
|
||||||
|
new_resize = np.random.choice(np.arange(lower_size, upper_size+16, 16))
|
||||||
|
if new_resize != x.shape[2]:
|
||||||
|
x = F.interpolate(x, size=new_resize, mode="bicubic")
|
||||||
|
x = x.detach()
|
||||||
|
return x
|
||||||
|
|
||||||
|
def training_step(self, batch, batch_idx, optimizer_idx):
|
||||||
|
# https://github.com/pytorch/pytorch/issues/37142
|
||||||
|
# try not to fool the heuristics
|
||||||
|
x = self.get_input(batch, self.image_key)
|
||||||
|
xrec, qloss, ind = self(x, return_pred_indices=True)
|
||||||
|
|
||||||
|
if optimizer_idx == 0:
|
||||||
|
# autoencode
|
||||||
|
aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
||||||
|
last_layer=self.get_last_layer(), split="train",
|
||||||
|
predicted_indices=ind)
|
||||||
|
|
||||||
|
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
||||||
|
return aeloss
|
||||||
|
|
||||||
|
if optimizer_idx == 1:
|
||||||
|
# discriminator
|
||||||
|
discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
||||||
|
last_layer=self.get_last_layer(), split="train")
|
||||||
|
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
||||||
|
return discloss
|
||||||
|
|
||||||
|
def validation_step(self, batch, batch_idx):
|
||||||
|
log_dict = self._validation_step(batch, batch_idx)
|
||||||
|
with self.ema_scope():
|
||||||
|
self._validation_step(batch, batch_idx, suffix="_ema")
|
||||||
|
return log_dict
|
||||||
|
|
||||||
|
def _validation_step(self, batch, batch_idx, suffix=""):
|
||||||
|
x = self.get_input(batch, self.image_key)
|
||||||
|
xrec, qloss, ind = self(x, return_pred_indices=True)
|
||||||
|
aeloss, log_dict_ae = self.loss(qloss, x, xrec, 0,
|
||||||
|
self.global_step,
|
||||||
|
last_layer=self.get_last_layer(),
|
||||||
|
split="val"+suffix,
|
||||||
|
predicted_indices=ind
|
||||||
|
)
|
||||||
|
|
||||||
|
discloss, log_dict_disc = self.loss(qloss, x, xrec, 1,
|
||||||
|
self.global_step,
|
||||||
|
last_layer=self.get_last_layer(),
|
||||||
|
split="val"+suffix,
|
||||||
|
predicted_indices=ind
|
||||||
|
)
|
||||||
|
rec_loss = log_dict_ae[f"val{suffix}/rec_loss"]
|
||||||
|
self.log(f"val{suffix}/rec_loss", rec_loss,
|
||||||
|
prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
|
||||||
|
self.log(f"val{suffix}/aeloss", aeloss,
|
||||||
|
prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
|
||||||
|
if version.parse(pl.__version__) >= version.parse('1.4.0'):
|
||||||
|
del log_dict_ae[f"val{suffix}/rec_loss"]
|
||||||
|
self.log_dict(log_dict_ae)
|
||||||
|
self.log_dict(log_dict_disc)
|
||||||
|
return self.log_dict
|
||||||
|
|
||||||
|
def configure_optimizers(self):
|
||||||
|
lr_d = self.learning_rate
|
||||||
|
lr_g = self.lr_g_factor*self.learning_rate
|
||||||
|
print("lr_d", lr_d)
|
||||||
|
print("lr_g", lr_g)
|
||||||
|
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
|
||||||
|
list(self.decoder.parameters())+
|
||||||
|
list(self.quantize.parameters())+
|
||||||
|
list(self.quant_conv.parameters())+
|
||||||
|
list(self.post_quant_conv.parameters()),
|
||||||
|
lr=lr_g, betas=(0.5, 0.9))
|
||||||
|
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
||||||
|
lr=lr_d, betas=(0.5, 0.9))
|
||||||
|
|
||||||
|
if self.scheduler_config is not None:
|
||||||
|
scheduler = instantiate_from_config(self.scheduler_config)
|
||||||
|
|
||||||
|
print("Setting up LambdaLR scheduler...")
|
||||||
|
scheduler = [
|
||||||
|
{
|
||||||
|
'scheduler': LambdaLR(opt_ae, lr_lambda=scheduler.schedule),
|
||||||
|
'interval': 'step',
|
||||||
|
'frequency': 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'scheduler': LambdaLR(opt_disc, lr_lambda=scheduler.schedule),
|
||||||
|
'interval': 'step',
|
||||||
|
'frequency': 1
|
||||||
|
},
|
||||||
|
]
|
||||||
|
return [opt_ae, opt_disc], scheduler
|
||||||
|
return [opt_ae, opt_disc], []
|
||||||
|
|
||||||
|
def get_last_layer(self):
|
||||||
|
return self.decoder.conv_out.weight
|
||||||
|
|
||||||
|
def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
|
||||||
|
log = {}
|
||||||
|
x = self.get_input(batch, self.image_key)
|
||||||
|
x = x.to(self.device)
|
||||||
|
if only_inputs:
|
||||||
|
log["inputs"] = x
|
||||||
|
return log
|
||||||
|
xrec, _ = self(x)
|
||||||
|
if x.shape[1] > 3:
|
||||||
|
# colorize with random projection
|
||||||
|
assert xrec.shape[1] > 3
|
||||||
|
x = self.to_rgb(x)
|
||||||
|
xrec = self.to_rgb(xrec)
|
||||||
|
log["inputs"] = x
|
||||||
|
log["reconstructions"] = xrec
|
||||||
|
if plot_ema:
|
||||||
|
with self.ema_scope():
|
||||||
|
xrec_ema, _ = self(x)
|
||||||
|
if x.shape[1] > 3:
|
||||||
|
xrec_ema = self.to_rgb(xrec_ema)
|
||||||
|
log["reconstructions_ema"] = xrec_ema
|
||||||
|
return log
|
||||||
|
|
||||||
|
def to_rgb(self, x):
|
||||||
|
assert self.image_key == "segmentation"
|
||||||
|
if not hasattr(self, "colorize"):
|
||||||
|
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
||||||
|
x = F.conv2d(x, weight=self.colorize)
|
||||||
|
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
class VQModelInterface(VQModel):
|
||||||
|
def __init__(self, embed_dim, *args, **kwargs):
|
||||||
|
super().__init__(*args, embed_dim=embed_dim, **kwargs)
|
||||||
|
self.embed_dim = embed_dim
|
||||||
|
|
||||||
|
def encode(self, x):
|
||||||
|
h = self.encoder(x)
|
||||||
|
h = self.quant_conv(h)
|
||||||
|
return h
|
||||||
|
|
||||||
|
def decode(self, h, force_not_quantize=False):
|
||||||
|
# also go through quantization layer
|
||||||
|
if not force_not_quantize:
|
||||||
|
quant, emb_loss, info = self.quantize(h)
|
||||||
|
else:
|
||||||
|
quant = h
|
||||||
|
quant = self.post_quant_conv(quant)
|
||||||
|
dec = self.decoder(quant)
|
||||||
|
return dec
|
||||||
|
|
||||||
|
ldm.models.autoencoder.VQModel = VQModel
|
||||||
|
ldm.models.autoencoder.VQModelInterface = VQModelInterface
|
1443
extensions-builtin/LDSR/sd_hijack_ddpm_v1.py
Normal file
1443
extensions-builtin/LDSR/sd_hijack_ddpm_v1.py
Normal file
File diff suppressed because it is too large
Load Diff
147
extensions-builtin/LDSR/vqvae_quantize.py
Normal file
147
extensions-builtin/LDSR/vqvae_quantize.py
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
# Vendored from https://raw.githubusercontent.com/CompVis/taming-transformers/24268930bf1dce879235a7fddd0b2355b84d7ea6/taming/modules/vqvae/quantize.py,
|
||||||
|
# where the license is as follows:
|
||||||
|
#
|
||||||
|
# Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer
|
||||||
|
#
|
||||||
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
# of this software and associated documentation files (the "Software"), to deal
|
||||||
|
# in the Software without restriction, including without limitation the rights
|
||||||
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
# copies of the Software, and to permit persons to whom the Software is
|
||||||
|
# furnished to do so, subject to the following conditions:
|
||||||
|
#
|
||||||
|
# The above copyright notice and this permission notice shall be included in all
|
||||||
|
# copies or substantial portions of the Software.
|
||||||
|
#
|
||||||
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||||
|
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||||
|
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||||
|
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
||||||
|
# OR OTHER DEALINGS IN THE SOFTWARE./
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
from einops import rearrange
|
||||||
|
|
||||||
|
|
||||||
|
class VectorQuantizer2(nn.Module):
|
||||||
|
"""
|
||||||
|
Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly
|
||||||
|
avoids costly matrix multiplications and allows for post-hoc remapping of indices.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# NOTE: due to a bug the beta term was applied to the wrong term. for
|
||||||
|
# backwards compatibility we use the buggy version by default, but you can
|
||||||
|
# specify legacy=False to fix it.
|
||||||
|
def __init__(self, n_e, e_dim, beta, remap=None, unknown_index="random",
|
||||||
|
sane_index_shape=False, legacy=True):
|
||||||
|
super().__init__()
|
||||||
|
self.n_e = n_e
|
||||||
|
self.e_dim = e_dim
|
||||||
|
self.beta = beta
|
||||||
|
self.legacy = legacy
|
||||||
|
|
||||||
|
self.embedding = nn.Embedding(self.n_e, self.e_dim)
|
||||||
|
self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
|
||||||
|
|
||||||
|
self.remap = remap
|
||||||
|
if self.remap is not None:
|
||||||
|
self.register_buffer("used", torch.tensor(np.load(self.remap)))
|
||||||
|
self.re_embed = self.used.shape[0]
|
||||||
|
self.unknown_index = unknown_index # "random" or "extra" or integer
|
||||||
|
if self.unknown_index == "extra":
|
||||||
|
self.unknown_index = self.re_embed
|
||||||
|
self.re_embed = self.re_embed + 1
|
||||||
|
print(f"Remapping {self.n_e} indices to {self.re_embed} indices. "
|
||||||
|
f"Using {self.unknown_index} for unknown indices.")
|
||||||
|
else:
|
||||||
|
self.re_embed = n_e
|
||||||
|
|
||||||
|
self.sane_index_shape = sane_index_shape
|
||||||
|
|
||||||
|
def remap_to_used(self, inds):
|
||||||
|
ishape = inds.shape
|
||||||
|
assert len(ishape) > 1
|
||||||
|
inds = inds.reshape(ishape[0], -1)
|
||||||
|
used = self.used.to(inds)
|
||||||
|
match = (inds[:, :, None] == used[None, None, ...]).long()
|
||||||
|
new = match.argmax(-1)
|
||||||
|
unknown = match.sum(2) < 1
|
||||||
|
if self.unknown_index == "random":
|
||||||
|
new[unknown] = torch.randint(0, self.re_embed, size=new[unknown].shape).to(device=new.device)
|
||||||
|
else:
|
||||||
|
new[unknown] = self.unknown_index
|
||||||
|
return new.reshape(ishape)
|
||||||
|
|
||||||
|
def unmap_to_all(self, inds):
|
||||||
|
ishape = inds.shape
|
||||||
|
assert len(ishape) > 1
|
||||||
|
inds = inds.reshape(ishape[0], -1)
|
||||||
|
used = self.used.to(inds)
|
||||||
|
if self.re_embed > self.used.shape[0]: # extra token
|
||||||
|
inds[inds >= self.used.shape[0]] = 0 # simply set to zero
|
||||||
|
back = torch.gather(used[None, :][inds.shape[0] * [0], :], 1, inds)
|
||||||
|
return back.reshape(ishape)
|
||||||
|
|
||||||
|
def forward(self, z, temp=None, rescale_logits=False, return_logits=False):
|
||||||
|
assert temp is None or temp == 1.0, "Only for interface compatible with Gumbel"
|
||||||
|
assert rescale_logits is False, "Only for interface compatible with Gumbel"
|
||||||
|
assert return_logits is False, "Only for interface compatible with Gumbel"
|
||||||
|
# reshape z -> (batch, height, width, channel) and flatten
|
||||||
|
z = rearrange(z, 'b c h w -> b h w c').contiguous()
|
||||||
|
z_flattened = z.view(-1, self.e_dim)
|
||||||
|
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
|
||||||
|
|
||||||
|
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
|
||||||
|
torch.sum(self.embedding.weight ** 2, dim=1) - 2 * \
|
||||||
|
torch.einsum('bd,dn->bn', z_flattened, rearrange(self.embedding.weight, 'n d -> d n'))
|
||||||
|
|
||||||
|
min_encoding_indices = torch.argmin(d, dim=1)
|
||||||
|
z_q = self.embedding(min_encoding_indices).view(z.shape)
|
||||||
|
perplexity = None
|
||||||
|
min_encodings = None
|
||||||
|
|
||||||
|
# compute loss for embedding
|
||||||
|
if not self.legacy:
|
||||||
|
loss = self.beta * torch.mean((z_q.detach() - z) ** 2) + \
|
||||||
|
torch.mean((z_q - z.detach()) ** 2)
|
||||||
|
else:
|
||||||
|
loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * \
|
||||||
|
torch.mean((z_q - z.detach()) ** 2)
|
||||||
|
|
||||||
|
# preserve gradients
|
||||||
|
z_q = z + (z_q - z).detach()
|
||||||
|
|
||||||
|
# reshape back to match original input shape
|
||||||
|
z_q = rearrange(z_q, 'b h w c -> b c h w').contiguous()
|
||||||
|
|
||||||
|
if self.remap is not None:
|
||||||
|
min_encoding_indices = min_encoding_indices.reshape(z.shape[0], -1) # add batch axis
|
||||||
|
min_encoding_indices = self.remap_to_used(min_encoding_indices)
|
||||||
|
min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten
|
||||||
|
|
||||||
|
if self.sane_index_shape:
|
||||||
|
min_encoding_indices = min_encoding_indices.reshape(
|
||||||
|
z_q.shape[0], z_q.shape[2], z_q.shape[3])
|
||||||
|
|
||||||
|
return z_q, loss, (perplexity, min_encodings, min_encoding_indices)
|
||||||
|
|
||||||
|
def get_codebook_entry(self, indices, shape):
|
||||||
|
# shape specifying (batch, height, width, channel)
|
||||||
|
if self.remap is not None:
|
||||||
|
indices = indices.reshape(shape[0], -1) # add batch axis
|
||||||
|
indices = self.unmap_to_all(indices)
|
||||||
|
indices = indices.reshape(-1) # flatten again
|
||||||
|
|
||||||
|
# get quantized latent vectors
|
||||||
|
z_q = self.embedding(indices)
|
||||||
|
|
||||||
|
if shape is not None:
|
||||||
|
z_q = z_q.view(shape)
|
||||||
|
# reshape back to match original input shape
|
||||||
|
z_q = z_q.permute(0, 3, 1, 2).contiguous()
|
||||||
|
|
||||||
|
return z_q
|
62
extensions-builtin/Lora/extra_networks_lora.py
Normal file
62
extensions-builtin/Lora/extra_networks_lora.py
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
from modules import extra_networks, shared
|
||||||
|
import networks
|
||||||
|
|
||||||
|
|
||||||
|
class ExtraNetworkLora(extra_networks.ExtraNetwork):
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__('lora')
|
||||||
|
|
||||||
|
self.errors = {}
|
||||||
|
"""mapping of network names to the number of errors the network had during operation"""
|
||||||
|
|
||||||
|
remove_symbols = str.maketrans('', '', ":,")
|
||||||
|
|
||||||
|
def activate(self, p, params_list):
|
||||||
|
additional = shared.opts.sd_lora
|
||||||
|
|
||||||
|
self.errors.clear()
|
||||||
|
|
||||||
|
if additional != "None" and additional in networks.available_networks and not any(x for x in params_list if x.items[0] == additional):
|
||||||
|
p.all_prompts = [x + f"<lora:{additional}:{shared.opts.extra_networks_default_multiplier}>" for x in p.all_prompts]
|
||||||
|
params_list.append(extra_networks.ExtraNetworkParams(items=[additional, shared.opts.extra_networks_default_multiplier]))
|
||||||
|
|
||||||
|
names = []
|
||||||
|
te_multipliers = []
|
||||||
|
unet_multipliers = []
|
||||||
|
dyn_dims = []
|
||||||
|
for params in params_list:
|
||||||
|
assert params.items
|
||||||
|
|
||||||
|
names.append(params.positional[0])
|
||||||
|
|
||||||
|
te_multiplier = float(params.positional[1]) if len(params.positional) > 1 else 1.0
|
||||||
|
te_multiplier = float(params.named.get("te", te_multiplier))
|
||||||
|
|
||||||
|
unet_multiplier = float(params.positional[2]) if len(params.positional) > 2 else te_multiplier
|
||||||
|
unet_multiplier = float(params.named.get("unet", unet_multiplier))
|
||||||
|
|
||||||
|
dyn_dim = int(params.positional[3]) if len(params.positional) > 3 else None
|
||||||
|
dyn_dim = int(params.named["dyn"]) if "dyn" in params.named else dyn_dim
|
||||||
|
|
||||||
|
te_multipliers.append(te_multiplier)
|
||||||
|
unet_multipliers.append(unet_multiplier)
|
||||||
|
dyn_dims.append(dyn_dim)
|
||||||
|
|
||||||
|
networks.load_networks(names, te_multipliers, unet_multipliers, dyn_dims)
|
||||||
|
|
||||||
|
if shared.opts.lora_add_hashes_to_infotext:
|
||||||
|
if not getattr(p, "is_hr_pass", False) or not hasattr(p, "lora_hashes"):
|
||||||
|
p.lora_hashes = {}
|
||||||
|
|
||||||
|
for item in networks.loaded_networks:
|
||||||
|
if item.network_on_disk.shorthash and item.mentioned_name:
|
||||||
|
p.lora_hashes[item.mentioned_name.translate(self.remove_symbols)] = item.network_on_disk.shorthash
|
||||||
|
|
||||||
|
if p.lora_hashes:
|
||||||
|
p.extra_generation_params["Lora hashes"] = ', '.join(f'{k}: {v}' for k, v in p.lora_hashes.items())
|
||||||
|
|
||||||
|
def deactivate(self, p):
|
||||||
|
if self.errors:
|
||||||
|
p.comment("Networks with errors: " + ", ".join(f"{k} ({v})" for k, v in self.errors.items()))
|
||||||
|
|
||||||
|
self.errors.clear()
|
9
extensions-builtin/Lora/lora.py
Normal file
9
extensions-builtin/Lora/lora.py
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import networks
|
||||||
|
|
||||||
|
list_available_loras = networks.list_available_networks
|
||||||
|
|
||||||
|
available_loras = networks.available_networks
|
||||||
|
available_lora_aliases = networks.available_network_aliases
|
||||||
|
available_lora_hash_lookup = networks.available_network_hash_lookup
|
||||||
|
forbidden_lora_aliases = networks.forbidden_network_aliases
|
||||||
|
loaded_loras = networks.loaded_networks
|
33
extensions-builtin/Lora/lora_logger.py
Normal file
33
extensions-builtin/Lora/lora_logger.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import sys
|
||||||
|
import copy
|
||||||
|
import logging
|
||||||
|
|
||||||
|
|
||||||
|
class ColoredFormatter(logging.Formatter):
|
||||||
|
COLORS = {
|
||||||
|
"DEBUG": "\033[0;36m", # CYAN
|
||||||
|
"INFO": "\033[0;32m", # GREEN
|
||||||
|
"WARNING": "\033[0;33m", # YELLOW
|
||||||
|
"ERROR": "\033[0;31m", # RED
|
||||||
|
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
|
||||||
|
"RESET": "\033[0m", # RESET COLOR
|
||||||
|
}
|
||||||
|
|
||||||
|
def format(self, record):
|
||||||
|
colored_record = copy.copy(record)
|
||||||
|
levelname = colored_record.levelname
|
||||||
|
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
|
||||||
|
colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
|
||||||
|
return super().format(colored_record)
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger("lora")
|
||||||
|
logger.propagate = False
|
||||||
|
|
||||||
|
|
||||||
|
if not logger.handlers:
|
||||||
|
handler = logging.StreamHandler(sys.stdout)
|
||||||
|
handler.setFormatter(
|
||||||
|
ColoredFormatter("[%(name)s]-%(levelname)s: %(message)s")
|
||||||
|
)
|
||||||
|
logger.addHandler(handler)
|
31
extensions-builtin/Lora/lora_patches.py
Normal file
31
extensions-builtin/Lora/lora_patches.py
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
import networks
|
||||||
|
from modules import patches
|
||||||
|
|
||||||
|
|
||||||
|
class LoraPatches:
|
||||||
|
def __init__(self):
|
||||||
|
self.Linear_forward = patches.patch(__name__, torch.nn.Linear, 'forward', networks.network_Linear_forward)
|
||||||
|
self.Linear_load_state_dict = patches.patch(__name__, torch.nn.Linear, '_load_from_state_dict', networks.network_Linear_load_state_dict)
|
||||||
|
self.Conv2d_forward = patches.patch(__name__, torch.nn.Conv2d, 'forward', networks.network_Conv2d_forward)
|
||||||
|
self.Conv2d_load_state_dict = patches.patch(__name__, torch.nn.Conv2d, '_load_from_state_dict', networks.network_Conv2d_load_state_dict)
|
||||||
|
self.GroupNorm_forward = patches.patch(__name__, torch.nn.GroupNorm, 'forward', networks.network_GroupNorm_forward)
|
||||||
|
self.GroupNorm_load_state_dict = patches.patch(__name__, torch.nn.GroupNorm, '_load_from_state_dict', networks.network_GroupNorm_load_state_dict)
|
||||||
|
self.LayerNorm_forward = patches.patch(__name__, torch.nn.LayerNorm, 'forward', networks.network_LayerNorm_forward)
|
||||||
|
self.LayerNorm_load_state_dict = patches.patch(__name__, torch.nn.LayerNorm, '_load_from_state_dict', networks.network_LayerNorm_load_state_dict)
|
||||||
|
self.MultiheadAttention_forward = patches.patch(__name__, torch.nn.MultiheadAttention, 'forward', networks.network_MultiheadAttention_forward)
|
||||||
|
self.MultiheadAttention_load_state_dict = patches.patch(__name__, torch.nn.MultiheadAttention, '_load_from_state_dict', networks.network_MultiheadAttention_load_state_dict)
|
||||||
|
|
||||||
|
def undo(self):
|
||||||
|
self.Linear_forward = patches.undo(__name__, torch.nn.Linear, 'forward')
|
||||||
|
self.Linear_load_state_dict = patches.undo(__name__, torch.nn.Linear, '_load_from_state_dict')
|
||||||
|
self.Conv2d_forward = patches.undo(__name__, torch.nn.Conv2d, 'forward')
|
||||||
|
self.Conv2d_load_state_dict = patches.undo(__name__, torch.nn.Conv2d, '_load_from_state_dict')
|
||||||
|
self.GroupNorm_forward = patches.undo(__name__, torch.nn.GroupNorm, 'forward')
|
||||||
|
self.GroupNorm_load_state_dict = patches.undo(__name__, torch.nn.GroupNorm, '_load_from_state_dict')
|
||||||
|
self.LayerNorm_forward = patches.undo(__name__, torch.nn.LayerNorm, 'forward')
|
||||||
|
self.LayerNorm_load_state_dict = patches.undo(__name__, torch.nn.LayerNorm, '_load_from_state_dict')
|
||||||
|
self.MultiheadAttention_forward = patches.undo(__name__, torch.nn.MultiheadAttention, 'forward')
|
||||||
|
self.MultiheadAttention_load_state_dict = patches.undo(__name__, torch.nn.MultiheadAttention, '_load_from_state_dict')
|
||||||
|
|
68
extensions-builtin/Lora/lyco_helpers.py
Normal file
68
extensions-builtin/Lora/lyco_helpers.py
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
|
||||||
|
def make_weight_cp(t, wa, wb):
|
||||||
|
temp = torch.einsum('i j k l, j r -> i r k l', t, wb)
|
||||||
|
return torch.einsum('i j k l, i r -> r j k l', temp, wa)
|
||||||
|
|
||||||
|
|
||||||
|
def rebuild_conventional(up, down, shape, dyn_dim=None):
|
||||||
|
up = up.reshape(up.size(0), -1)
|
||||||
|
down = down.reshape(down.size(0), -1)
|
||||||
|
if dyn_dim is not None:
|
||||||
|
up = up[:, :dyn_dim]
|
||||||
|
down = down[:dyn_dim, :]
|
||||||
|
return (up @ down).reshape(shape)
|
||||||
|
|
||||||
|
|
||||||
|
def rebuild_cp_decomposition(up, down, mid):
|
||||||
|
up = up.reshape(up.size(0), -1)
|
||||||
|
down = down.reshape(down.size(0), -1)
|
||||||
|
return torch.einsum('n m k l, i n, m j -> i j k l', mid, up, down)
|
||||||
|
|
||||||
|
|
||||||
|
# copied from https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/lokr.py
|
||||||
|
def factorization(dimension: int, factor:int=-1) -> tuple[int, int]:
|
||||||
|
'''
|
||||||
|
return a tuple of two value of input dimension decomposed by the number closest to factor
|
||||||
|
second value is higher or equal than first value.
|
||||||
|
|
||||||
|
In LoRA with Kroneckor Product, first value is a value for weight scale.
|
||||||
|
secon value is a value for weight.
|
||||||
|
|
||||||
|
Because of non-commutative property, A⊗B ≠ B⊗A. Meaning of two matrices is slightly different.
|
||||||
|
|
||||||
|
examples)
|
||||||
|
factor
|
||||||
|
-1 2 4 8 16 ...
|
||||||
|
127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127
|
||||||
|
128 -> 8, 16 128 -> 2, 64 128 -> 4, 32 128 -> 8, 16 128 -> 8, 16
|
||||||
|
250 -> 10, 25 250 -> 2, 125 250 -> 2, 125 250 -> 5, 50 250 -> 10, 25
|
||||||
|
360 -> 8, 45 360 -> 2, 180 360 -> 4, 90 360 -> 8, 45 360 -> 12, 30
|
||||||
|
512 -> 16, 32 512 -> 2, 256 512 -> 4, 128 512 -> 8, 64 512 -> 16, 32
|
||||||
|
1024 -> 32, 32 1024 -> 2, 512 1024 -> 4, 256 1024 -> 8, 128 1024 -> 16, 64
|
||||||
|
'''
|
||||||
|
|
||||||
|
if factor > 0 and (dimension % factor) == 0:
|
||||||
|
m = factor
|
||||||
|
n = dimension // factor
|
||||||
|
if m > n:
|
||||||
|
n, m = m, n
|
||||||
|
return m, n
|
||||||
|
if factor < 0:
|
||||||
|
factor = dimension
|
||||||
|
m, n = 1, dimension
|
||||||
|
length = m + n
|
||||||
|
while m<n:
|
||||||
|
new_m = m + 1
|
||||||
|
while dimension%new_m != 0:
|
||||||
|
new_m += 1
|
||||||
|
new_n = dimension // new_m
|
||||||
|
if new_m + new_n > length or new_m>factor:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
m, n = new_m, new_n
|
||||||
|
if m > n:
|
||||||
|
n, m = m, n
|
||||||
|
return m, n
|
||||||
|
|
228
extensions-builtin/Lora/network.py
Normal file
228
extensions-builtin/Lora/network.py
Normal file
@ -0,0 +1,228 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import os
|
||||||
|
from collections import namedtuple
|
||||||
|
import enum
|
||||||
|
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
|
from modules import sd_models, cache, errors, hashes, shared
|
||||||
|
import modules.models.sd3.mmdit
|
||||||
|
|
||||||
|
NetworkWeights = namedtuple('NetworkWeights', ['network_key', 'sd_key', 'w', 'sd_module'])
|
||||||
|
|
||||||
|
metadata_tags_order = {"ss_sd_model_name": 1, "ss_resolution": 2, "ss_clip_skip": 3, "ss_num_train_images": 10, "ss_tag_frequency": 20}
|
||||||
|
|
||||||
|
|
||||||
|
class SdVersion(enum.Enum):
|
||||||
|
Unknown = 1
|
||||||
|
SD1 = 2
|
||||||
|
SD2 = 3
|
||||||
|
SDXL = 4
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkOnDisk:
|
||||||
|
def __init__(self, name, filename):
|
||||||
|
self.name = name
|
||||||
|
self.filename = filename
|
||||||
|
self.metadata = {}
|
||||||
|
self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors"
|
||||||
|
|
||||||
|
def read_metadata():
|
||||||
|
metadata = sd_models.read_metadata_from_safetensors(filename)
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
|
||||||
|
if self.is_safetensors:
|
||||||
|
try:
|
||||||
|
self.metadata = cache.cached_data_for_file('safetensors-metadata', "lora/" + self.name, filename, read_metadata)
|
||||||
|
except Exception as e:
|
||||||
|
errors.display(e, f"reading lora {filename}")
|
||||||
|
|
||||||
|
if self.metadata:
|
||||||
|
m = {}
|
||||||
|
for k, v in sorted(self.metadata.items(), key=lambda x: metadata_tags_order.get(x[0], 999)):
|
||||||
|
m[k] = v
|
||||||
|
|
||||||
|
self.metadata = m
|
||||||
|
|
||||||
|
self.alias = self.metadata.get('ss_output_name', self.name)
|
||||||
|
|
||||||
|
self.hash = None
|
||||||
|
self.shorthash = None
|
||||||
|
self.set_hash(
|
||||||
|
self.metadata.get('sshs_model_hash') or
|
||||||
|
hashes.sha256_from_cache(self.filename, "lora/" + self.name, use_addnet_hash=self.is_safetensors) or
|
||||||
|
''
|
||||||
|
)
|
||||||
|
|
||||||
|
self.sd_version = self.detect_version()
|
||||||
|
|
||||||
|
def detect_version(self):
|
||||||
|
if str(self.metadata.get('ss_base_model_version', "")).startswith("sdxl_"):
|
||||||
|
return SdVersion.SDXL
|
||||||
|
elif str(self.metadata.get('ss_v2', "")) == "True":
|
||||||
|
return SdVersion.SD2
|
||||||
|
elif len(self.metadata):
|
||||||
|
return SdVersion.SD1
|
||||||
|
|
||||||
|
return SdVersion.Unknown
|
||||||
|
|
||||||
|
def set_hash(self, v):
|
||||||
|
self.hash = v
|
||||||
|
self.shorthash = self.hash[0:12]
|
||||||
|
|
||||||
|
if self.shorthash:
|
||||||
|
import networks
|
||||||
|
networks.available_network_hash_lookup[self.shorthash] = self
|
||||||
|
|
||||||
|
def read_hash(self):
|
||||||
|
if not self.hash:
|
||||||
|
self.set_hash(hashes.sha256(self.filename, "lora/" + self.name, use_addnet_hash=self.is_safetensors) or '')
|
||||||
|
|
||||||
|
def get_alias(self):
|
||||||
|
import networks
|
||||||
|
if shared.opts.lora_preferred_name == "Filename" or self.alias.lower() in networks.forbidden_network_aliases:
|
||||||
|
return self.name
|
||||||
|
else:
|
||||||
|
return self.alias
|
||||||
|
|
||||||
|
|
||||||
|
class Network: # LoraModule
|
||||||
|
def __init__(self, name, network_on_disk: NetworkOnDisk):
|
||||||
|
self.name = name
|
||||||
|
self.network_on_disk = network_on_disk
|
||||||
|
self.te_multiplier = 1.0
|
||||||
|
self.unet_multiplier = 1.0
|
||||||
|
self.dyn_dim = None
|
||||||
|
self.modules = {}
|
||||||
|
self.bundle_embeddings = {}
|
||||||
|
self.mtime = None
|
||||||
|
|
||||||
|
self.mentioned_name = None
|
||||||
|
"""the text that was used to add the network to prompt - can be either name or an alias"""
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleType:
|
||||||
|
def create_module(self, net: Network, weights: NetworkWeights) -> Network | None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModule:
|
||||||
|
def __init__(self, net: Network, weights: NetworkWeights):
|
||||||
|
self.network = net
|
||||||
|
self.network_key = weights.network_key
|
||||||
|
self.sd_key = weights.sd_key
|
||||||
|
self.sd_module = weights.sd_module
|
||||||
|
|
||||||
|
if isinstance(self.sd_module, modules.models.sd3.mmdit.QkvLinear):
|
||||||
|
s = self.sd_module.weight.shape
|
||||||
|
self.shape = (s[0] // 3, s[1])
|
||||||
|
elif hasattr(self.sd_module, 'weight'):
|
||||||
|
self.shape = self.sd_module.weight.shape
|
||||||
|
elif isinstance(self.sd_module, nn.MultiheadAttention):
|
||||||
|
# For now, only self-attn use Pytorch's MHA
|
||||||
|
# So assume all qkvo proj have same shape
|
||||||
|
self.shape = self.sd_module.out_proj.weight.shape
|
||||||
|
else:
|
||||||
|
self.shape = None
|
||||||
|
|
||||||
|
self.ops = None
|
||||||
|
self.extra_kwargs = {}
|
||||||
|
if isinstance(self.sd_module, nn.Conv2d):
|
||||||
|
self.ops = F.conv2d
|
||||||
|
self.extra_kwargs = {
|
||||||
|
'stride': self.sd_module.stride,
|
||||||
|
'padding': self.sd_module.padding
|
||||||
|
}
|
||||||
|
elif isinstance(self.sd_module, nn.Linear):
|
||||||
|
self.ops = F.linear
|
||||||
|
elif isinstance(self.sd_module, nn.LayerNorm):
|
||||||
|
self.ops = F.layer_norm
|
||||||
|
self.extra_kwargs = {
|
||||||
|
'normalized_shape': self.sd_module.normalized_shape,
|
||||||
|
'eps': self.sd_module.eps
|
||||||
|
}
|
||||||
|
elif isinstance(self.sd_module, nn.GroupNorm):
|
||||||
|
self.ops = F.group_norm
|
||||||
|
self.extra_kwargs = {
|
||||||
|
'num_groups': self.sd_module.num_groups,
|
||||||
|
'eps': self.sd_module.eps
|
||||||
|
}
|
||||||
|
|
||||||
|
self.dim = None
|
||||||
|
self.bias = weights.w.get("bias")
|
||||||
|
self.alpha = weights.w["alpha"].item() if "alpha" in weights.w else None
|
||||||
|
self.scale = weights.w["scale"].item() if "scale" in weights.w else None
|
||||||
|
|
||||||
|
self.dora_scale = weights.w.get("dora_scale", None)
|
||||||
|
self.dora_norm_dims = len(self.shape) - 1
|
||||||
|
|
||||||
|
def multiplier(self):
|
||||||
|
if 'transformer' in self.sd_key[:20]:
|
||||||
|
return self.network.te_multiplier
|
||||||
|
else:
|
||||||
|
return self.network.unet_multiplier
|
||||||
|
|
||||||
|
def calc_scale(self):
|
||||||
|
if self.scale is not None:
|
||||||
|
return self.scale
|
||||||
|
if self.dim is not None and self.alpha is not None:
|
||||||
|
return self.alpha / self.dim
|
||||||
|
|
||||||
|
return 1.0
|
||||||
|
|
||||||
|
def apply_weight_decompose(self, updown, orig_weight):
|
||||||
|
# Match the device/dtype
|
||||||
|
orig_weight = orig_weight.to(updown.dtype)
|
||||||
|
dora_scale = self.dora_scale.to(device=orig_weight.device, dtype=updown.dtype)
|
||||||
|
updown = updown.to(orig_weight.device)
|
||||||
|
|
||||||
|
merged_scale1 = updown + orig_weight
|
||||||
|
merged_scale1_norm = (
|
||||||
|
merged_scale1.transpose(0, 1)
|
||||||
|
.reshape(merged_scale1.shape[1], -1)
|
||||||
|
.norm(dim=1, keepdim=True)
|
||||||
|
.reshape(merged_scale1.shape[1], *[1] * self.dora_norm_dims)
|
||||||
|
.transpose(0, 1)
|
||||||
|
)
|
||||||
|
|
||||||
|
dora_merged = (
|
||||||
|
merged_scale1 * (dora_scale / merged_scale1_norm)
|
||||||
|
)
|
||||||
|
final_updown = dora_merged - orig_weight
|
||||||
|
return final_updown
|
||||||
|
|
||||||
|
def finalize_updown(self, updown, orig_weight, output_shape, ex_bias=None):
|
||||||
|
if self.bias is not None:
|
||||||
|
updown = updown.reshape(self.bias.shape)
|
||||||
|
updown += self.bias.to(orig_weight.device, dtype=updown.dtype)
|
||||||
|
updown = updown.reshape(output_shape)
|
||||||
|
|
||||||
|
if len(output_shape) == 4:
|
||||||
|
updown = updown.reshape(output_shape)
|
||||||
|
|
||||||
|
if orig_weight.size().numel() == updown.size().numel():
|
||||||
|
updown = updown.reshape(orig_weight.shape)
|
||||||
|
|
||||||
|
if ex_bias is not None:
|
||||||
|
ex_bias = ex_bias * self.multiplier()
|
||||||
|
|
||||||
|
updown = updown * self.calc_scale()
|
||||||
|
|
||||||
|
if self.dora_scale is not None:
|
||||||
|
updown = self.apply_weight_decompose(updown, orig_weight)
|
||||||
|
|
||||||
|
return updown * self.multiplier(), ex_bias
|
||||||
|
|
||||||
|
def calc_updown(self, target):
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def forward(self, x, y):
|
||||||
|
"""A general forward implementation for all modules"""
|
||||||
|
if self.ops is None:
|
||||||
|
raise NotImplementedError()
|
||||||
|
else:
|
||||||
|
updown, ex_bias = self.calc_updown(self.sd_module.weight)
|
||||||
|
return y + self.ops(x, weight=updown, bias=ex_bias, **self.extra_kwargs)
|
||||||
|
|
27
extensions-builtin/Lora/network_full.py
Normal file
27
extensions-builtin/Lora/network_full.py
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeFull(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["diff"]):
|
||||||
|
return NetworkModuleFull(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleFull(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.weight = weights.w.get("diff")
|
||||||
|
self.ex_bias = weights.w.get("diff_b")
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
output_shape = self.weight.shape
|
||||||
|
updown = self.weight.to(orig_weight.device)
|
||||||
|
if self.ex_bias is not None:
|
||||||
|
ex_bias = self.ex_bias.to(orig_weight.device)
|
||||||
|
else:
|
||||||
|
ex_bias = None
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
|
33
extensions-builtin/Lora/network_glora.py
Normal file
33
extensions-builtin/Lora/network_glora.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
|
||||||
|
import network
|
||||||
|
|
||||||
|
class ModuleTypeGLora(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["a1.weight", "a2.weight", "alpha", "b1.weight", "b2.weight"]):
|
||||||
|
return NetworkModuleGLora(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
# adapted from https://github.com/KohakuBlueleaf/LyCORIS
|
||||||
|
class NetworkModuleGLora(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
if hasattr(self.sd_module, 'weight'):
|
||||||
|
self.shape = self.sd_module.weight.shape
|
||||||
|
|
||||||
|
self.w1a = weights.w["a1.weight"]
|
||||||
|
self.w1b = weights.w["b1.weight"]
|
||||||
|
self.w2a = weights.w["a2.weight"]
|
||||||
|
self.w2b = weights.w["b2.weight"]
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
w1a = self.w1a.to(orig_weight.device)
|
||||||
|
w1b = self.w1b.to(orig_weight.device)
|
||||||
|
w2a = self.w2a.to(orig_weight.device)
|
||||||
|
w2b = self.w2b.to(orig_weight.device)
|
||||||
|
|
||||||
|
output_shape = [w1a.size(0), w1b.size(1)]
|
||||||
|
updown = ((w2b @ w1b) + ((orig_weight.to(dtype = w1a.dtype) @ w2a) @ w1a))
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
55
extensions-builtin/Lora/network_hada.py
Normal file
55
extensions-builtin/Lora/network_hada.py
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
import lyco_helpers
|
||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeHada(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b"]):
|
||||||
|
return NetworkModuleHada(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleHada(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
if hasattr(self.sd_module, 'weight'):
|
||||||
|
self.shape = self.sd_module.weight.shape
|
||||||
|
|
||||||
|
self.w1a = weights.w["hada_w1_a"]
|
||||||
|
self.w1b = weights.w["hada_w1_b"]
|
||||||
|
self.dim = self.w1b.shape[0]
|
||||||
|
self.w2a = weights.w["hada_w2_a"]
|
||||||
|
self.w2b = weights.w["hada_w2_b"]
|
||||||
|
|
||||||
|
self.t1 = weights.w.get("hada_t1")
|
||||||
|
self.t2 = weights.w.get("hada_t2")
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
w1a = self.w1a.to(orig_weight.device)
|
||||||
|
w1b = self.w1b.to(orig_weight.device)
|
||||||
|
w2a = self.w2a.to(orig_weight.device)
|
||||||
|
w2b = self.w2b.to(orig_weight.device)
|
||||||
|
|
||||||
|
output_shape = [w1a.size(0), w1b.size(1)]
|
||||||
|
|
||||||
|
if self.t1 is not None:
|
||||||
|
output_shape = [w1a.size(1), w1b.size(1)]
|
||||||
|
t1 = self.t1.to(orig_weight.device)
|
||||||
|
updown1 = lyco_helpers.make_weight_cp(t1, w1a, w1b)
|
||||||
|
output_shape += t1.shape[2:]
|
||||||
|
else:
|
||||||
|
if len(w1b.shape) == 4:
|
||||||
|
output_shape += w1b.shape[2:]
|
||||||
|
updown1 = lyco_helpers.rebuild_conventional(w1a, w1b, output_shape)
|
||||||
|
|
||||||
|
if self.t2 is not None:
|
||||||
|
t2 = self.t2.to(orig_weight.device)
|
||||||
|
updown2 = lyco_helpers.make_weight_cp(t2, w2a, w2b)
|
||||||
|
else:
|
||||||
|
updown2 = lyco_helpers.rebuild_conventional(w2a, w2b, output_shape)
|
||||||
|
|
||||||
|
updown = updown1 * updown2
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
30
extensions-builtin/Lora/network_ia3.py
Normal file
30
extensions-builtin/Lora/network_ia3.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeIa3(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["weight"]):
|
||||||
|
return NetworkModuleIa3(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleIa3(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.w = weights.w["weight"]
|
||||||
|
self.on_input = weights.w["on_input"].item()
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
w = self.w.to(orig_weight.device)
|
||||||
|
|
||||||
|
output_shape = [w.size(0), orig_weight.size(1)]
|
||||||
|
if self.on_input:
|
||||||
|
output_shape.reverse()
|
||||||
|
else:
|
||||||
|
w = w.reshape(-1, 1)
|
||||||
|
|
||||||
|
updown = orig_weight * w
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
64
extensions-builtin/Lora/network_lokr.py
Normal file
64
extensions-builtin/Lora/network_lokr.py
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
import lyco_helpers
|
||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeLokr(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
|
||||||
|
has_2 = "lokr_w2" in weights.w or ("lokr_w2_a" in weights.w and "lokr_w2_b" in weights.w)
|
||||||
|
if has_1 and has_2:
|
||||||
|
return NetworkModuleLokr(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def make_kron(orig_shape, w1, w2):
|
||||||
|
if len(w2.shape) == 4:
|
||||||
|
w1 = w1.unsqueeze(2).unsqueeze(2)
|
||||||
|
w2 = w2.contiguous()
|
||||||
|
return torch.kron(w1, w2).reshape(orig_shape)
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleLokr(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.w1 = weights.w.get("lokr_w1")
|
||||||
|
self.w1a = weights.w.get("lokr_w1_a")
|
||||||
|
self.w1b = weights.w.get("lokr_w1_b")
|
||||||
|
self.dim = self.w1b.shape[0] if self.w1b is not None else self.dim
|
||||||
|
self.w2 = weights.w.get("lokr_w2")
|
||||||
|
self.w2a = weights.w.get("lokr_w2_a")
|
||||||
|
self.w2b = weights.w.get("lokr_w2_b")
|
||||||
|
self.dim = self.w2b.shape[0] if self.w2b is not None else self.dim
|
||||||
|
self.t2 = weights.w.get("lokr_t2")
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
if self.w1 is not None:
|
||||||
|
w1 = self.w1.to(orig_weight.device)
|
||||||
|
else:
|
||||||
|
w1a = self.w1a.to(orig_weight.device)
|
||||||
|
w1b = self.w1b.to(orig_weight.device)
|
||||||
|
w1 = w1a @ w1b
|
||||||
|
|
||||||
|
if self.w2 is not None:
|
||||||
|
w2 = self.w2.to(orig_weight.device)
|
||||||
|
elif self.t2 is None:
|
||||||
|
w2a = self.w2a.to(orig_weight.device)
|
||||||
|
w2b = self.w2b.to(orig_weight.device)
|
||||||
|
w2 = w2a @ w2b
|
||||||
|
else:
|
||||||
|
t2 = self.t2.to(orig_weight.device)
|
||||||
|
w2a = self.w2a.to(orig_weight.device)
|
||||||
|
w2b = self.w2b.to(orig_weight.device)
|
||||||
|
w2 = lyco_helpers.make_weight_cp(t2, w2a, w2b)
|
||||||
|
|
||||||
|
output_shape = [w1.size(0) * w2.size(0), w1.size(1) * w2.size(1)]
|
||||||
|
if len(orig_weight.shape) == 4:
|
||||||
|
output_shape = orig_weight.shape
|
||||||
|
|
||||||
|
updown = make_kron(output_shape, w1, w2)
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
94
extensions-builtin/Lora/network_lora.py
Normal file
94
extensions-builtin/Lora/network_lora.py
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
import lyco_helpers
|
||||||
|
import modules.models.sd3.mmdit
|
||||||
|
import network
|
||||||
|
from modules import devices
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeLora(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["lora_up.weight", "lora_down.weight"]):
|
||||||
|
return NetworkModuleLora(net, weights)
|
||||||
|
|
||||||
|
if all(x in weights.w for x in ["lora_A.weight", "lora_B.weight"]):
|
||||||
|
w = weights.w.copy()
|
||||||
|
weights.w.clear()
|
||||||
|
weights.w.update({"lora_up.weight": w["lora_B.weight"], "lora_down.weight": w["lora_A.weight"]})
|
||||||
|
|
||||||
|
return NetworkModuleLora(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleLora(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.up_model = self.create_module(weights.w, "lora_up.weight")
|
||||||
|
self.down_model = self.create_module(weights.w, "lora_down.weight")
|
||||||
|
self.mid_model = self.create_module(weights.w, "lora_mid.weight", none_ok=True)
|
||||||
|
|
||||||
|
self.dim = weights.w["lora_down.weight"].shape[0]
|
||||||
|
|
||||||
|
def create_module(self, weights, key, none_ok=False):
|
||||||
|
weight = weights.get(key)
|
||||||
|
|
||||||
|
if weight is None and none_ok:
|
||||||
|
return None
|
||||||
|
|
||||||
|
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear, torch.nn.MultiheadAttention, modules.models.sd3.mmdit.QkvLinear]
|
||||||
|
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
|
||||||
|
|
||||||
|
if is_linear:
|
||||||
|
weight = weight.reshape(weight.shape[0], -1)
|
||||||
|
module = torch.nn.Linear(weight.shape[1], weight.shape[0], bias=False)
|
||||||
|
elif is_conv and key == "lora_down.weight" or key == "dyn_up":
|
||||||
|
if len(weight.shape) == 2:
|
||||||
|
weight = weight.reshape(weight.shape[0], -1, 1, 1)
|
||||||
|
|
||||||
|
if weight.shape[2] != 1 or weight.shape[3] != 1:
|
||||||
|
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], self.sd_module.kernel_size, self.sd_module.stride, self.sd_module.padding, bias=False)
|
||||||
|
else:
|
||||||
|
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False)
|
||||||
|
elif is_conv and key == "lora_mid.weight":
|
||||||
|
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], self.sd_module.kernel_size, self.sd_module.stride, self.sd_module.padding, bias=False)
|
||||||
|
elif is_conv and key == "lora_up.weight" or key == "dyn_down":
|
||||||
|
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False)
|
||||||
|
else:
|
||||||
|
raise AssertionError(f'Lora layer {self.network_key} matched a layer with unsupported type: {type(self.sd_module).__name__}')
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
if weight.shape != module.weight.shape:
|
||||||
|
weight = weight.reshape(module.weight.shape)
|
||||||
|
module.weight.copy_(weight)
|
||||||
|
|
||||||
|
module.to(device=devices.cpu, dtype=devices.dtype)
|
||||||
|
module.weight.requires_grad_(False)
|
||||||
|
|
||||||
|
return module
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
up = self.up_model.weight.to(orig_weight.device)
|
||||||
|
down = self.down_model.weight.to(orig_weight.device)
|
||||||
|
|
||||||
|
output_shape = [up.size(0), down.size(1)]
|
||||||
|
if self.mid_model is not None:
|
||||||
|
# cp-decomposition
|
||||||
|
mid = self.mid_model.weight.to(orig_weight.device)
|
||||||
|
updown = lyco_helpers.rebuild_cp_decomposition(up, down, mid)
|
||||||
|
output_shape += mid.shape[2:]
|
||||||
|
else:
|
||||||
|
if len(down.shape) == 4:
|
||||||
|
output_shape += down.shape[2:]
|
||||||
|
updown = lyco_helpers.rebuild_conventional(up, down, output_shape, self.network.dyn_dim)
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
||||||
|
|
||||||
|
def forward(self, x, y):
|
||||||
|
self.up_model.to(device=devices.device)
|
||||||
|
self.down_model.to(device=devices.device)
|
||||||
|
|
||||||
|
return y + self.up_model(self.down_model(x)) * self.multiplier() * self.calc_scale()
|
||||||
|
|
||||||
|
|
28
extensions-builtin/Lora/network_norm.py
Normal file
28
extensions-builtin/Lora/network_norm.py
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import network
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeNorm(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["w_norm", "b_norm"]):
|
||||||
|
return NetworkModuleNorm(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkModuleNorm(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.w_norm = weights.w.get("w_norm")
|
||||||
|
self.b_norm = weights.w.get("b_norm")
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
output_shape = self.w_norm.shape
|
||||||
|
updown = self.w_norm.to(orig_weight.device)
|
||||||
|
|
||||||
|
if self.b_norm is not None:
|
||||||
|
ex_bias = self.b_norm.to(orig_weight.device)
|
||||||
|
else:
|
||||||
|
ex_bias = None
|
||||||
|
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
|
118
extensions-builtin/Lora/network_oft.py
Normal file
118
extensions-builtin/Lora/network_oft.py
Normal file
@ -0,0 +1,118 @@
|
|||||||
|
import torch
|
||||||
|
import network
|
||||||
|
from einops import rearrange
|
||||||
|
|
||||||
|
|
||||||
|
class ModuleTypeOFT(network.ModuleType):
|
||||||
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
|
||||||
|
return NetworkModuleOFT(net, weights)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Supports both kohya-ss' implementation of COFT https://github.com/kohya-ss/sd-scripts/blob/main/networks/oft.py
|
||||||
|
# and KohakuBlueleaf's implementation of OFT/COFT https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/diag_oft.py
|
||||||
|
class NetworkModuleOFT(network.NetworkModule):
|
||||||
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
||||||
|
|
||||||
|
super().__init__(net, weights)
|
||||||
|
|
||||||
|
self.lin_module = None
|
||||||
|
self.org_module: list[torch.Module] = [self.sd_module]
|
||||||
|
|
||||||
|
self.scale = 1.0
|
||||||
|
self.is_R = False
|
||||||
|
self.is_boft = False
|
||||||
|
|
||||||
|
# kohya-ss/New LyCORIS OFT/BOFT
|
||||||
|
if "oft_blocks" in weights.w.keys():
|
||||||
|
self.oft_blocks = weights.w["oft_blocks"] # (num_blocks, block_size, block_size)
|
||||||
|
self.alpha = weights.w.get("alpha", None) # alpha is constraint
|
||||||
|
self.dim = self.oft_blocks.shape[0] # lora dim
|
||||||
|
# Old LyCORIS OFT
|
||||||
|
elif "oft_diag" in weights.w.keys():
|
||||||
|
self.is_R = True
|
||||||
|
self.oft_blocks = weights.w["oft_diag"]
|
||||||
|
# self.alpha is unused
|
||||||
|
self.dim = self.oft_blocks.shape[1] # (num_blocks, block_size, block_size)
|
||||||
|
|
||||||
|
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear]
|
||||||
|
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
|
||||||
|
is_other_linear = type(self.sd_module) in [torch.nn.MultiheadAttention] # unsupported
|
||||||
|
|
||||||
|
if is_linear:
|
||||||
|
self.out_dim = self.sd_module.out_features
|
||||||
|
elif is_conv:
|
||||||
|
self.out_dim = self.sd_module.out_channels
|
||||||
|
elif is_other_linear:
|
||||||
|
self.out_dim = self.sd_module.embed_dim
|
||||||
|
|
||||||
|
# LyCORIS BOFT
|
||||||
|
if self.oft_blocks.dim() == 4:
|
||||||
|
self.is_boft = True
|
||||||
|
self.rescale = weights.w.get('rescale', None)
|
||||||
|
if self.rescale is not None and not is_other_linear:
|
||||||
|
self.rescale = self.rescale.reshape(-1, *[1]*(self.org_module[0].weight.dim() - 1))
|
||||||
|
|
||||||
|
self.num_blocks = self.dim
|
||||||
|
self.block_size = self.out_dim // self.dim
|
||||||
|
self.constraint = (0 if self.alpha is None else self.alpha) * self.out_dim
|
||||||
|
if self.is_R:
|
||||||
|
self.constraint = None
|
||||||
|
self.block_size = self.dim
|
||||||
|
self.num_blocks = self.out_dim // self.dim
|
||||||
|
elif self.is_boft:
|
||||||
|
self.boft_m = self.oft_blocks.shape[0]
|
||||||
|
self.num_blocks = self.oft_blocks.shape[1]
|
||||||
|
self.block_size = self.oft_blocks.shape[2]
|
||||||
|
self.boft_b = self.block_size
|
||||||
|
|
||||||
|
def calc_updown(self, orig_weight):
|
||||||
|
oft_blocks = self.oft_blocks.to(orig_weight.device)
|
||||||
|
eye = torch.eye(self.block_size, device=oft_blocks.device)
|
||||||
|
|
||||||
|
if not self.is_R:
|
||||||
|
block_Q = oft_blocks - oft_blocks.transpose(-1, -2) # ensure skew-symmetric orthogonal matrix
|
||||||
|
if self.constraint != 0:
|
||||||
|
norm_Q = torch.norm(block_Q.flatten())
|
||||||
|
new_norm_Q = torch.clamp(norm_Q, max=self.constraint.to(oft_blocks.device))
|
||||||
|
block_Q = block_Q * ((new_norm_Q + 1e-8) / (norm_Q + 1e-8))
|
||||||
|
oft_blocks = torch.matmul(eye + block_Q, (eye - block_Q).float().inverse())
|
||||||
|
|
||||||
|
R = oft_blocks.to(orig_weight.device)
|
||||||
|
|
||||||
|
if not self.is_boft:
|
||||||
|
# This errors out for MultiheadAttention, might need to be handled up-stream
|
||||||
|
merged_weight = rearrange(orig_weight, '(k n) ... -> k n ...', k=self.num_blocks, n=self.block_size)
|
||||||
|
merged_weight = torch.einsum(
|
||||||
|
'k n m, k n ... -> k m ...',
|
||||||
|
R,
|
||||||
|
merged_weight
|
||||||
|
)
|
||||||
|
merged_weight = rearrange(merged_weight, 'k m ... -> (k m) ...')
|
||||||
|
else:
|
||||||
|
# TODO: determine correct value for scale
|
||||||
|
scale = 1.0
|
||||||
|
m = self.boft_m
|
||||||
|
b = self.boft_b
|
||||||
|
r_b = b // 2
|
||||||
|
inp = orig_weight
|
||||||
|
for i in range(m):
|
||||||
|
bi = R[i] # b_num, b_size, b_size
|
||||||
|
if i == 0:
|
||||||
|
# Apply multiplier/scale and rescale into first weight
|
||||||
|
bi = bi * scale + (1 - scale) * eye
|
||||||
|
inp = rearrange(inp, "(c g k) ... -> (c k g) ...", g=2, k=2**i * r_b)
|
||||||
|
inp = rearrange(inp, "(d b) ... -> d b ...", b=b)
|
||||||
|
inp = torch.einsum("b i j, b j ... -> b i ...", bi, inp)
|
||||||
|
inp = rearrange(inp, "d b ... -> (d b) ...")
|
||||||
|
inp = rearrange(inp, "(c k g) ... -> (c g k) ...", g=2, k=2**i * r_b)
|
||||||
|
merged_weight = inp
|
||||||
|
|
||||||
|
# Rescale mechanism
|
||||||
|
if self.rescale is not None:
|
||||||
|
merged_weight = self.rescale.to(merged_weight) * merged_weight
|
||||||
|
|
||||||
|
updown = merged_weight.to(orig_weight.device) - orig_weight.to(merged_weight.dtype)
|
||||||
|
output_shape = orig_weight.shape
|
||||||
|
return self.finalize_updown(updown, orig_weight, output_shape)
|
737
extensions-builtin/Lora/networks.py
Normal file
737
extensions-builtin/Lora/networks.py
Normal file
@ -0,0 +1,737 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import gradio as gr
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
import lora_patches
|
||||||
|
import network
|
||||||
|
import network_lora
|
||||||
|
import network_glora
|
||||||
|
import network_hada
|
||||||
|
import network_ia3
|
||||||
|
import network_lokr
|
||||||
|
import network_full
|
||||||
|
import network_norm
|
||||||
|
import network_oft
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
from modules import shared, devices, sd_models, errors, scripts, sd_hijack
|
||||||
|
import modules.textual_inversion.textual_inversion as textual_inversion
|
||||||
|
import modules.models.sd3.mmdit
|
||||||
|
|
||||||
|
from lora_logger import logger
|
||||||
|
|
||||||
|
module_types = [
|
||||||
|
network_lora.ModuleTypeLora(),
|
||||||
|
network_hada.ModuleTypeHada(),
|
||||||
|
network_ia3.ModuleTypeIa3(),
|
||||||
|
network_lokr.ModuleTypeLokr(),
|
||||||
|
network_full.ModuleTypeFull(),
|
||||||
|
network_norm.ModuleTypeNorm(),
|
||||||
|
network_glora.ModuleTypeGLora(),
|
||||||
|
network_oft.ModuleTypeOFT(),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
re_digits = re.compile(r"\d+")
|
||||||
|
re_x_proj = re.compile(r"(.*)_([qkv]_proj)$")
|
||||||
|
re_compiled = {}
|
||||||
|
|
||||||
|
suffix_conversion = {
|
||||||
|
"attentions": {},
|
||||||
|
"resnets": {
|
||||||
|
"conv1": "in_layers_2",
|
||||||
|
"conv2": "out_layers_3",
|
||||||
|
"norm1": "in_layers_0",
|
||||||
|
"norm2": "out_layers_0",
|
||||||
|
"time_emb_proj": "emb_layers_1",
|
||||||
|
"conv_shortcut": "skip_connection",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def convert_diffusers_name_to_compvis(key, is_sd2):
|
||||||
|
def match(match_list, regex_text):
|
||||||
|
regex = re_compiled.get(regex_text)
|
||||||
|
if regex is None:
|
||||||
|
regex = re.compile(regex_text)
|
||||||
|
re_compiled[regex_text] = regex
|
||||||
|
|
||||||
|
r = re.match(regex, key)
|
||||||
|
if not r:
|
||||||
|
return False
|
||||||
|
|
||||||
|
match_list.clear()
|
||||||
|
match_list.extend([int(x) if re.match(re_digits, x) else x for x in r.groups()])
|
||||||
|
return True
|
||||||
|
|
||||||
|
m = []
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_conv_in(.*)"):
|
||||||
|
return f'diffusion_model_input_blocks_0_0{m[0]}'
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_conv_out(.*)"):
|
||||||
|
return f'diffusion_model_out_2{m[0]}'
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_time_embedding_linear_(\d+)(.*)"):
|
||||||
|
return f"diffusion_model_time_embed_{m[0] * 2 - 2}{m[1]}"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_down_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
|
||||||
|
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
|
||||||
|
return f"diffusion_model_input_blocks_{1 + m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_mid_block_(attentions|resnets)_(\d+)_(.+)"):
|
||||||
|
suffix = suffix_conversion.get(m[0], {}).get(m[2], m[2])
|
||||||
|
return f"diffusion_model_middle_block_{1 if m[0] == 'attentions' else m[1] * 2}_{suffix}"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_up_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
|
||||||
|
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
|
||||||
|
return f"diffusion_model_output_blocks_{m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_down_blocks_(\d+)_downsamplers_0_conv"):
|
||||||
|
return f"diffusion_model_input_blocks_{3 + m[0] * 3}_0_op"
|
||||||
|
|
||||||
|
if match(m, r"lora_unet_up_blocks_(\d+)_upsamplers_0_conv"):
|
||||||
|
return f"diffusion_model_output_blocks_{2 + m[0] * 3}_{2 if m[0]>0 else 1}_conv"
|
||||||
|
|
||||||
|
if match(m, r"lora_te_text_model_encoder_layers_(\d+)_(.+)"):
|
||||||
|
if is_sd2:
|
||||||
|
if 'mlp_fc1' in m[1]:
|
||||||
|
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
|
||||||
|
elif 'mlp_fc2' in m[1]:
|
||||||
|
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
|
||||||
|
else:
|
||||||
|
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
|
||||||
|
|
||||||
|
return f"transformer_text_model_encoder_layers_{m[0]}_{m[1]}"
|
||||||
|
|
||||||
|
if match(m, r"lora_te2_text_model_encoder_layers_(\d+)_(.+)"):
|
||||||
|
if 'mlp_fc1' in m[1]:
|
||||||
|
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
|
||||||
|
elif 'mlp_fc2' in m[1]:
|
||||||
|
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
|
||||||
|
else:
|
||||||
|
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
|
||||||
|
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def assign_network_names_to_compvis_modules(sd_model):
|
||||||
|
network_layer_mapping = {}
|
||||||
|
|
||||||
|
if shared.sd_model.is_sdxl:
|
||||||
|
for i, embedder in enumerate(shared.sd_model.conditioner.embedders):
|
||||||
|
if not hasattr(embedder, 'wrapped'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
for name, module in embedder.wrapped.named_modules():
|
||||||
|
network_name = f'{i}_{name.replace(".", "_")}'
|
||||||
|
network_layer_mapping[network_name] = module
|
||||||
|
module.network_layer_name = network_name
|
||||||
|
else:
|
||||||
|
cond_stage_model = getattr(shared.sd_model.cond_stage_model, 'wrapped', shared.sd_model.cond_stage_model)
|
||||||
|
|
||||||
|
for name, module in cond_stage_model.named_modules():
|
||||||
|
network_name = name.replace(".", "_")
|
||||||
|
network_layer_mapping[network_name] = module
|
||||||
|
module.network_layer_name = network_name
|
||||||
|
|
||||||
|
for name, module in shared.sd_model.model.named_modules():
|
||||||
|
network_name = name.replace(".", "_")
|
||||||
|
network_layer_mapping[network_name] = module
|
||||||
|
module.network_layer_name = network_name
|
||||||
|
|
||||||
|
sd_model.network_layer_mapping = network_layer_mapping
|
||||||
|
|
||||||
|
|
||||||
|
class BundledTIHash(str):
|
||||||
|
def __init__(self, hash_str):
|
||||||
|
self.hash = hash_str
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.hash if shared.opts.lora_bundled_ti_to_infotext else ''
|
||||||
|
|
||||||
|
|
||||||
|
def load_network(name, network_on_disk):
|
||||||
|
net = network.Network(name, network_on_disk)
|
||||||
|
net.mtime = os.path.getmtime(network_on_disk.filename)
|
||||||
|
|
||||||
|
sd = sd_models.read_state_dict(network_on_disk.filename)
|
||||||
|
|
||||||
|
# this should not be needed but is here as an emergency fix for an unknown error people are experiencing in 1.2.0
|
||||||
|
if not hasattr(shared.sd_model, 'network_layer_mapping'):
|
||||||
|
assign_network_names_to_compvis_modules(shared.sd_model)
|
||||||
|
|
||||||
|
keys_failed_to_match = {}
|
||||||
|
is_sd2 = 'model_transformer_resblocks' in shared.sd_model.network_layer_mapping
|
||||||
|
if hasattr(shared.sd_model, 'diffusers_weight_map'):
|
||||||
|
diffusers_weight_map = shared.sd_model.diffusers_weight_map
|
||||||
|
elif hasattr(shared.sd_model, 'diffusers_weight_mapping'):
|
||||||
|
diffusers_weight_map = {}
|
||||||
|
for k, v in shared.sd_model.diffusers_weight_mapping():
|
||||||
|
diffusers_weight_map[k] = v
|
||||||
|
shared.sd_model.diffusers_weight_map = diffusers_weight_map
|
||||||
|
else:
|
||||||
|
diffusers_weight_map = None
|
||||||
|
|
||||||
|
matched_networks = {}
|
||||||
|
bundle_embeddings = {}
|
||||||
|
|
||||||
|
for key_network, weight in sd.items():
|
||||||
|
|
||||||
|
if diffusers_weight_map:
|
||||||
|
key_network_without_network_parts, network_name, network_weight = key_network.rsplit(".", 2)
|
||||||
|
network_part = network_name + '.' + network_weight
|
||||||
|
else:
|
||||||
|
key_network_without_network_parts, _, network_part = key_network.partition(".")
|
||||||
|
|
||||||
|
if key_network_without_network_parts == "bundle_emb":
|
||||||
|
emb_name, vec_name = network_part.split(".", 1)
|
||||||
|
emb_dict = bundle_embeddings.get(emb_name, {})
|
||||||
|
if vec_name.split('.')[0] == 'string_to_param':
|
||||||
|
_, k2 = vec_name.split('.', 1)
|
||||||
|
emb_dict['string_to_param'] = {k2: weight}
|
||||||
|
else:
|
||||||
|
emb_dict[vec_name] = weight
|
||||||
|
bundle_embeddings[emb_name] = emb_dict
|
||||||
|
|
||||||
|
if diffusers_weight_map:
|
||||||
|
key = diffusers_weight_map.get(key_network_without_network_parts, key_network_without_network_parts)
|
||||||
|
else:
|
||||||
|
key = convert_diffusers_name_to_compvis(key_network_without_network_parts, is_sd2)
|
||||||
|
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
if sd_module is None:
|
||||||
|
m = re_x_proj.match(key)
|
||||||
|
if m:
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(m.group(1), None)
|
||||||
|
|
||||||
|
# SDXL loras seem to already have correct compvis keys, so only need to replace "lora_unet" with "diffusion_model"
|
||||||
|
if sd_module is None and "lora_unet" in key_network_without_network_parts:
|
||||||
|
key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
elif sd_module is None and "lora_te1_text_model" in key_network_without_network_parts:
|
||||||
|
key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
# some SD1 Loras also have correct compvis keys
|
||||||
|
if sd_module is None:
|
||||||
|
key = key_network_without_network_parts.replace("lora_te1_text_model", "transformer_text_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
# kohya_ss OFT module
|
||||||
|
elif sd_module is None and "oft_unet" in key_network_without_network_parts:
|
||||||
|
key = key_network_without_network_parts.replace("oft_unet", "diffusion_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
# KohakuBlueLeaf OFT module
|
||||||
|
if sd_module is None and "oft_diag" in key:
|
||||||
|
key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
|
||||||
|
key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
|
||||||
|
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
||||||
|
|
||||||
|
if sd_module is None:
|
||||||
|
keys_failed_to_match[key_network] = key
|
||||||
|
continue
|
||||||
|
|
||||||
|
if key not in matched_networks:
|
||||||
|
matched_networks[key] = network.NetworkWeights(network_key=key_network, sd_key=key, w={}, sd_module=sd_module)
|
||||||
|
|
||||||
|
matched_networks[key].w[network_part] = weight
|
||||||
|
|
||||||
|
for key, weights in matched_networks.items():
|
||||||
|
net_module = None
|
||||||
|
for nettype in module_types:
|
||||||
|
net_module = nettype.create_module(net, weights)
|
||||||
|
if net_module is not None:
|
||||||
|
break
|
||||||
|
|
||||||
|
if net_module is None:
|
||||||
|
raise AssertionError(f"Could not find a module type (out of {', '.join([x.__class__.__name__ for x in module_types])}) that would accept those keys: {', '.join(weights.w)}")
|
||||||
|
|
||||||
|
net.modules[key] = net_module
|
||||||
|
|
||||||
|
embeddings = {}
|
||||||
|
for emb_name, data in bundle_embeddings.items():
|
||||||
|
embedding = textual_inversion.create_embedding_from_data(data, emb_name, filename=network_on_disk.filename + "/" + emb_name)
|
||||||
|
embedding.loaded = None
|
||||||
|
embedding.shorthash = BundledTIHash(name)
|
||||||
|
embeddings[emb_name] = embedding
|
||||||
|
|
||||||
|
net.bundle_embeddings = embeddings
|
||||||
|
|
||||||
|
if keys_failed_to_match:
|
||||||
|
logging.debug(f"Network {network_on_disk.filename} didn't match keys: {keys_failed_to_match}")
|
||||||
|
|
||||||
|
return net
|
||||||
|
|
||||||
|
|
||||||
|
def purge_networks_from_memory():
|
||||||
|
while len(networks_in_memory) > shared.opts.lora_in_memory_limit and len(networks_in_memory) > 0:
|
||||||
|
name = next(iter(networks_in_memory))
|
||||||
|
networks_in_memory.pop(name, None)
|
||||||
|
|
||||||
|
devices.torch_gc()
|
||||||
|
|
||||||
|
|
||||||
|
def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=None):
|
||||||
|
emb_db = sd_hijack.model_hijack.embedding_db
|
||||||
|
already_loaded = {}
|
||||||
|
|
||||||
|
for net in loaded_networks:
|
||||||
|
if net.name in names:
|
||||||
|
already_loaded[net.name] = net
|
||||||
|
for emb_name, embedding in net.bundle_embeddings.items():
|
||||||
|
if embedding.loaded:
|
||||||
|
emb_db.register_embedding_by_name(None, shared.sd_model, emb_name)
|
||||||
|
|
||||||
|
loaded_networks.clear()
|
||||||
|
|
||||||
|
unavailable_networks = []
|
||||||
|
for name in names:
|
||||||
|
if name.lower() in forbidden_network_aliases and available_networks.get(name) is None:
|
||||||
|
unavailable_networks.append(name)
|
||||||
|
elif available_network_aliases.get(name) is None:
|
||||||
|
unavailable_networks.append(name)
|
||||||
|
|
||||||
|
if unavailable_networks:
|
||||||
|
update_available_networks_by_names(unavailable_networks)
|
||||||
|
|
||||||
|
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
|
||||||
|
if any(x is None for x in networks_on_disk):
|
||||||
|
list_available_networks()
|
||||||
|
|
||||||
|
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
|
||||||
|
|
||||||
|
failed_to_load_networks = []
|
||||||
|
|
||||||
|
for i, (network_on_disk, name) in enumerate(zip(networks_on_disk, names)):
|
||||||
|
net = already_loaded.get(name, None)
|
||||||
|
|
||||||
|
if network_on_disk is not None:
|
||||||
|
if net is None:
|
||||||
|
net = networks_in_memory.get(name)
|
||||||
|
|
||||||
|
if net is None or os.path.getmtime(network_on_disk.filename) > net.mtime:
|
||||||
|
try:
|
||||||
|
net = load_network(name, network_on_disk)
|
||||||
|
|
||||||
|
networks_in_memory.pop(name, None)
|
||||||
|
networks_in_memory[name] = net
|
||||||
|
except Exception as e:
|
||||||
|
errors.display(e, f"loading network {network_on_disk.filename}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
net.mentioned_name = name
|
||||||
|
|
||||||
|
network_on_disk.read_hash()
|
||||||
|
|
||||||
|
if net is None:
|
||||||
|
failed_to_load_networks.append(name)
|
||||||
|
logging.info(f"Couldn't find network with name {name}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
net.te_multiplier = te_multipliers[i] if te_multipliers else 1.0
|
||||||
|
net.unet_multiplier = unet_multipliers[i] if unet_multipliers else 1.0
|
||||||
|
net.dyn_dim = dyn_dims[i] if dyn_dims else 1.0
|
||||||
|
loaded_networks.append(net)
|
||||||
|
|
||||||
|
for emb_name, embedding in net.bundle_embeddings.items():
|
||||||
|
if embedding.loaded is None and emb_name in emb_db.word_embeddings:
|
||||||
|
logger.warning(
|
||||||
|
f'Skip bundle embedding: "{emb_name}"'
|
||||||
|
' as it was already loaded from embeddings folder'
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
embedding.loaded = False
|
||||||
|
if emb_db.expected_shape == -1 or emb_db.expected_shape == embedding.shape:
|
||||||
|
embedding.loaded = True
|
||||||
|
emb_db.register_embedding(embedding, shared.sd_model)
|
||||||
|
else:
|
||||||
|
emb_db.skipped_embeddings[name] = embedding
|
||||||
|
|
||||||
|
if failed_to_load_networks:
|
||||||
|
lora_not_found_message = f'Lora not found: {", ".join(failed_to_load_networks)}'
|
||||||
|
sd_hijack.model_hijack.comments.append(lora_not_found_message)
|
||||||
|
if shared.opts.lora_not_found_warning_console:
|
||||||
|
print(f'\n{lora_not_found_message}\n')
|
||||||
|
if shared.opts.lora_not_found_gradio_warning:
|
||||||
|
gr.Warning(lora_not_found_message)
|
||||||
|
|
||||||
|
purge_networks_from_memory()
|
||||||
|
|
||||||
|
|
||||||
|
def allowed_layer_without_weight(layer):
|
||||||
|
if isinstance(layer, torch.nn.LayerNorm) and not layer.elementwise_affine:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def store_weights_backup(weight):
|
||||||
|
if weight is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return weight.to(devices.cpu, copy=True)
|
||||||
|
|
||||||
|
|
||||||
|
def restore_weights_backup(obj, field, weight):
|
||||||
|
if weight is None:
|
||||||
|
setattr(obj, field, None)
|
||||||
|
return
|
||||||
|
|
||||||
|
getattr(obj, field).copy_(weight)
|
||||||
|
|
||||||
|
|
||||||
|
def network_restore_weights_from_backup(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
|
||||||
|
weights_backup = getattr(self, "network_weights_backup", None)
|
||||||
|
bias_backup = getattr(self, "network_bias_backup", None)
|
||||||
|
|
||||||
|
if weights_backup is None and bias_backup is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if weights_backup is not None:
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention):
|
||||||
|
restore_weights_backup(self, 'in_proj_weight', weights_backup[0])
|
||||||
|
restore_weights_backup(self.out_proj, 'weight', weights_backup[1])
|
||||||
|
else:
|
||||||
|
restore_weights_backup(self, 'weight', weights_backup)
|
||||||
|
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention):
|
||||||
|
restore_weights_backup(self.out_proj, 'bias', bias_backup)
|
||||||
|
else:
|
||||||
|
restore_weights_backup(self, 'bias', bias_backup)
|
||||||
|
|
||||||
|
|
||||||
|
def network_apply_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
|
||||||
|
"""
|
||||||
|
Applies the currently selected set of networks to the weights of torch layer self.
|
||||||
|
If weights already have this particular set of networks applied, does nothing.
|
||||||
|
If not, restores original weights from backup and alters weights according to networks.
|
||||||
|
"""
|
||||||
|
|
||||||
|
network_layer_name = getattr(self, 'network_layer_name', None)
|
||||||
|
if network_layer_name is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
current_names = getattr(self, "network_current_names", ())
|
||||||
|
wanted_names = tuple((x.name, x.te_multiplier, x.unet_multiplier, x.dyn_dim) for x in loaded_networks)
|
||||||
|
|
||||||
|
weights_backup = getattr(self, "network_weights_backup", None)
|
||||||
|
if weights_backup is None and wanted_names != ():
|
||||||
|
if current_names != () and not allowed_layer_without_weight(self):
|
||||||
|
raise RuntimeError(f"{network_layer_name} - no backup weights found and current weights are not unchanged")
|
||||||
|
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention):
|
||||||
|
weights_backup = (store_weights_backup(self.in_proj_weight), store_weights_backup(self.out_proj.weight))
|
||||||
|
else:
|
||||||
|
weights_backup = store_weights_backup(self.weight)
|
||||||
|
|
||||||
|
self.network_weights_backup = weights_backup
|
||||||
|
|
||||||
|
bias_backup = getattr(self, "network_bias_backup", None)
|
||||||
|
if bias_backup is None and wanted_names != ():
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention) and self.out_proj.bias is not None:
|
||||||
|
bias_backup = store_weights_backup(self.out_proj.bias)
|
||||||
|
elif getattr(self, 'bias', None) is not None:
|
||||||
|
bias_backup = store_weights_backup(self.bias)
|
||||||
|
else:
|
||||||
|
bias_backup = None
|
||||||
|
|
||||||
|
# Unlike weight which always has value, some modules don't have bias.
|
||||||
|
# Only report if bias is not None and current bias are not unchanged.
|
||||||
|
if bias_backup is not None and current_names != ():
|
||||||
|
raise RuntimeError("no backup bias found and current bias are not unchanged")
|
||||||
|
|
||||||
|
self.network_bias_backup = bias_backup
|
||||||
|
|
||||||
|
if current_names != wanted_names:
|
||||||
|
network_restore_weights_from_backup(self)
|
||||||
|
|
||||||
|
for net in loaded_networks:
|
||||||
|
module = net.modules.get(network_layer_name, None)
|
||||||
|
if module is not None and hasattr(self, 'weight') and not isinstance(module, modules.models.sd3.mmdit.QkvLinear):
|
||||||
|
try:
|
||||||
|
with torch.no_grad():
|
||||||
|
if getattr(self, 'fp16_weight', None) is None:
|
||||||
|
weight = self.weight
|
||||||
|
bias = self.bias
|
||||||
|
else:
|
||||||
|
weight = self.fp16_weight.clone().to(self.weight.device)
|
||||||
|
bias = getattr(self, 'fp16_bias', None)
|
||||||
|
if bias is not None:
|
||||||
|
bias = bias.clone().to(self.bias.device)
|
||||||
|
updown, ex_bias = module.calc_updown(weight)
|
||||||
|
|
||||||
|
if len(weight.shape) == 4 and weight.shape[1] == 9:
|
||||||
|
# inpainting model. zero pad updown to make channel[1] 4 to 9
|
||||||
|
updown = torch.nn.functional.pad(updown, (0, 0, 0, 0, 0, 5))
|
||||||
|
|
||||||
|
self.weight.copy_((weight.to(dtype=updown.dtype) + updown).to(dtype=self.weight.dtype))
|
||||||
|
if ex_bias is not None and hasattr(self, 'bias'):
|
||||||
|
if self.bias is None:
|
||||||
|
self.bias = torch.nn.Parameter(ex_bias).to(self.weight.dtype)
|
||||||
|
else:
|
||||||
|
self.bias.copy_((bias + ex_bias).to(dtype=self.bias.dtype))
|
||||||
|
except RuntimeError as e:
|
||||||
|
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
|
||||||
|
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
||||||
|
|
||||||
|
continue
|
||||||
|
|
||||||
|
module_q = net.modules.get(network_layer_name + "_q_proj", None)
|
||||||
|
module_k = net.modules.get(network_layer_name + "_k_proj", None)
|
||||||
|
module_v = net.modules.get(network_layer_name + "_v_proj", None)
|
||||||
|
module_out = net.modules.get(network_layer_name + "_out_proj", None)
|
||||||
|
|
||||||
|
if isinstance(self, torch.nn.MultiheadAttention) and module_q and module_k and module_v and module_out:
|
||||||
|
try:
|
||||||
|
with torch.no_grad():
|
||||||
|
# Send "real" orig_weight into MHA's lora module
|
||||||
|
qw, kw, vw = self.in_proj_weight.chunk(3, 0)
|
||||||
|
updown_q, _ = module_q.calc_updown(qw)
|
||||||
|
updown_k, _ = module_k.calc_updown(kw)
|
||||||
|
updown_v, _ = module_v.calc_updown(vw)
|
||||||
|
del qw, kw, vw
|
||||||
|
updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
|
||||||
|
updown_out, ex_bias = module_out.calc_updown(self.out_proj.weight)
|
||||||
|
|
||||||
|
self.in_proj_weight += updown_qkv
|
||||||
|
self.out_proj.weight += updown_out
|
||||||
|
if ex_bias is not None:
|
||||||
|
if self.out_proj.bias is None:
|
||||||
|
self.out_proj.bias = torch.nn.Parameter(ex_bias)
|
||||||
|
else:
|
||||||
|
self.out_proj.bias += ex_bias
|
||||||
|
|
||||||
|
except RuntimeError as e:
|
||||||
|
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
|
||||||
|
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
||||||
|
|
||||||
|
continue
|
||||||
|
|
||||||
|
if isinstance(self, modules.models.sd3.mmdit.QkvLinear) and module_q and module_k and module_v:
|
||||||
|
try:
|
||||||
|
with torch.no_grad():
|
||||||
|
# Send "real" orig_weight into MHA's lora module
|
||||||
|
qw, kw, vw = self.weight.chunk(3, 0)
|
||||||
|
updown_q, _ = module_q.calc_updown(qw)
|
||||||
|
updown_k, _ = module_k.calc_updown(kw)
|
||||||
|
updown_v, _ = module_v.calc_updown(vw)
|
||||||
|
del qw, kw, vw
|
||||||
|
updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
|
||||||
|
self.weight += updown_qkv
|
||||||
|
|
||||||
|
except RuntimeError as e:
|
||||||
|
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
|
||||||
|
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
||||||
|
|
||||||
|
continue
|
||||||
|
|
||||||
|
if module is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
logging.debug(f"Network {net.name} layer {network_layer_name}: couldn't find supported operation")
|
||||||
|
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
||||||
|
|
||||||
|
self.network_current_names = wanted_names
|
||||||
|
|
||||||
|
|
||||||
|
def network_forward(org_module, input, original_forward):
|
||||||
|
"""
|
||||||
|
Old way of applying Lora by executing operations during layer's forward.
|
||||||
|
Stacking many loras this way results in big performance degradation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if len(loaded_networks) == 0:
|
||||||
|
return original_forward(org_module, input)
|
||||||
|
|
||||||
|
input = devices.cond_cast_unet(input)
|
||||||
|
|
||||||
|
network_restore_weights_from_backup(org_module)
|
||||||
|
network_reset_cached_weight(org_module)
|
||||||
|
|
||||||
|
y = original_forward(org_module, input)
|
||||||
|
|
||||||
|
network_layer_name = getattr(org_module, 'network_layer_name', None)
|
||||||
|
for lora in loaded_networks:
|
||||||
|
module = lora.modules.get(network_layer_name, None)
|
||||||
|
if module is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
y = module.forward(input, y)
|
||||||
|
|
||||||
|
return y
|
||||||
|
|
||||||
|
|
||||||
|
def network_reset_cached_weight(self: Union[torch.nn.Conv2d, torch.nn.Linear]):
|
||||||
|
self.network_current_names = ()
|
||||||
|
self.network_weights_backup = None
|
||||||
|
self.network_bias_backup = None
|
||||||
|
|
||||||
|
|
||||||
|
def network_Linear_forward(self, input):
|
||||||
|
if shared.opts.lora_functional:
|
||||||
|
return network_forward(self, input, originals.Linear_forward)
|
||||||
|
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.Linear_forward(self, input)
|
||||||
|
|
||||||
|
|
||||||
|
def network_Linear_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.Linear_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_Conv2d_forward(self, input):
|
||||||
|
if shared.opts.lora_functional:
|
||||||
|
return network_forward(self, input, originals.Conv2d_forward)
|
||||||
|
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.Conv2d_forward(self, input)
|
||||||
|
|
||||||
|
|
||||||
|
def network_Conv2d_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.Conv2d_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_GroupNorm_forward(self, input):
|
||||||
|
if shared.opts.lora_functional:
|
||||||
|
return network_forward(self, input, originals.GroupNorm_forward)
|
||||||
|
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.GroupNorm_forward(self, input)
|
||||||
|
|
||||||
|
|
||||||
|
def network_GroupNorm_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.GroupNorm_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_LayerNorm_forward(self, input):
|
||||||
|
if shared.opts.lora_functional:
|
||||||
|
return network_forward(self, input, originals.LayerNorm_forward)
|
||||||
|
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.LayerNorm_forward(self, input)
|
||||||
|
|
||||||
|
|
||||||
|
def network_LayerNorm_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.LayerNorm_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_MultiheadAttention_forward(self, *args, **kwargs):
|
||||||
|
network_apply_weights(self)
|
||||||
|
|
||||||
|
return originals.MultiheadAttention_forward(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def network_MultiheadAttention_load_state_dict(self, *args, **kwargs):
|
||||||
|
network_reset_cached_weight(self)
|
||||||
|
|
||||||
|
return originals.MultiheadAttention_load_state_dict(self, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def process_network_files(names: list[str] | None = None):
|
||||||
|
candidates = list(shared.walk_files(shared.cmd_opts.lora_dir, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
|
||||||
|
candidates += list(shared.walk_files(shared.cmd_opts.lyco_dir_backcompat, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
|
||||||
|
for filename in candidates:
|
||||||
|
if os.path.isdir(filename):
|
||||||
|
continue
|
||||||
|
name = os.path.splitext(os.path.basename(filename))[0]
|
||||||
|
# if names is provided, only load networks with names in the list
|
||||||
|
if names and name not in names:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
entry = network.NetworkOnDisk(name, filename)
|
||||||
|
except OSError: # should catch FileNotFoundError and PermissionError etc.
|
||||||
|
errors.report(f"Failed to load network {name} from {filename}", exc_info=True)
|
||||||
|
continue
|
||||||
|
|
||||||
|
available_networks[name] = entry
|
||||||
|
|
||||||
|
if entry.alias in available_network_aliases:
|
||||||
|
forbidden_network_aliases[entry.alias.lower()] = 1
|
||||||
|
|
||||||
|
available_network_aliases[name] = entry
|
||||||
|
available_network_aliases[entry.alias] = entry
|
||||||
|
|
||||||
|
|
||||||
|
def update_available_networks_by_names(names: list[str]):
|
||||||
|
process_network_files(names)
|
||||||
|
|
||||||
|
|
||||||
|
def list_available_networks():
|
||||||
|
available_networks.clear()
|
||||||
|
available_network_aliases.clear()
|
||||||
|
forbidden_network_aliases.clear()
|
||||||
|
available_network_hash_lookup.clear()
|
||||||
|
forbidden_network_aliases.update({"none": 1, "Addams": 1})
|
||||||
|
|
||||||
|
os.makedirs(shared.cmd_opts.lora_dir, exist_ok=True)
|
||||||
|
|
||||||
|
process_network_files()
|
||||||
|
|
||||||
|
|
||||||
|
re_network_name = re.compile(r"(.*)\s*\([0-9a-fA-F]+\)")
|
||||||
|
|
||||||
|
|
||||||
|
def infotext_pasted(infotext, params):
|
||||||
|
if "AddNet Module 1" in [x[1] for x in scripts.scripts_txt2img.infotext_fields]:
|
||||||
|
return # if the other extension is active, it will handle those fields, no need to do anything
|
||||||
|
|
||||||
|
added = []
|
||||||
|
|
||||||
|
for k in params:
|
||||||
|
if not k.startswith("AddNet Model "):
|
||||||
|
continue
|
||||||
|
|
||||||
|
num = k[13:]
|
||||||
|
|
||||||
|
if params.get("AddNet Module " + num) != "LoRA":
|
||||||
|
continue
|
||||||
|
|
||||||
|
name = params.get("AddNet Model " + num)
|
||||||
|
if name is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
m = re_network_name.match(name)
|
||||||
|
if m:
|
||||||
|
name = m.group(1)
|
||||||
|
|
||||||
|
multiplier = params.get("AddNet Weight A " + num, "1.0")
|
||||||
|
|
||||||
|
added.append(f"<lora:{name}:{multiplier}>")
|
||||||
|
|
||||||
|
if added:
|
||||||
|
params["Prompt"] += "\n" + "".join(added)
|
||||||
|
|
||||||
|
|
||||||
|
originals: lora_patches.LoraPatches = None
|
||||||
|
|
||||||
|
extra_network_lora = None
|
||||||
|
|
||||||
|
available_networks = {}
|
||||||
|
available_network_aliases = {}
|
||||||
|
loaded_networks = []
|
||||||
|
loaded_bundle_embeddings = {}
|
||||||
|
networks_in_memory = {}
|
||||||
|
available_network_hash_lookup = {}
|
||||||
|
forbidden_network_aliases = {}
|
||||||
|
|
||||||
|
list_available_networks()
|
8
extensions-builtin/Lora/preload.py
Normal file
8
extensions-builtin/Lora/preload.py
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import os
|
||||||
|
from modules import paths
|
||||||
|
from modules.paths_internal import normalized_filepath
|
||||||
|
|
||||||
|
|
||||||
|
def preload(parser):
|
||||||
|
parser.add_argument("--lora-dir", type=normalized_filepath, help="Path to directory with Lora networks.", default=os.path.join(paths.models_path, 'Lora'))
|
||||||
|
parser.add_argument("--lyco-dir-backcompat", type=normalized_filepath, help="Path to directory with LyCORIS networks (for backawards compatibility; can also use --lyco-dir).", default=os.path.join(paths.models_path, 'LyCORIS'))
|
102
extensions-builtin/Lora/scripts/lora_script.py
Normal file
102
extensions-builtin/Lora/scripts/lora_script.py
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
import re
|
||||||
|
|
||||||
|
import gradio as gr
|
||||||
|
from fastapi import FastAPI
|
||||||
|
|
||||||
|
import network
|
||||||
|
import networks
|
||||||
|
import lora # noqa:F401
|
||||||
|
import lora_patches
|
||||||
|
import extra_networks_lora
|
||||||
|
import ui_extra_networks_lora
|
||||||
|
from modules import script_callbacks, ui_extra_networks, extra_networks, shared
|
||||||
|
|
||||||
|
|
||||||
|
def unload():
|
||||||
|
networks.originals.undo()
|
||||||
|
|
||||||
|
|
||||||
|
def before_ui():
|
||||||
|
ui_extra_networks.register_page(ui_extra_networks_lora.ExtraNetworksPageLora())
|
||||||
|
|
||||||
|
networks.extra_network_lora = extra_networks_lora.ExtraNetworkLora()
|
||||||
|
extra_networks.register_extra_network(networks.extra_network_lora)
|
||||||
|
extra_networks.register_extra_network_alias(networks.extra_network_lora, "lyco")
|
||||||
|
|
||||||
|
|
||||||
|
networks.originals = lora_patches.LoraPatches()
|
||||||
|
|
||||||
|
script_callbacks.on_model_loaded(networks.assign_network_names_to_compvis_modules)
|
||||||
|
script_callbacks.on_script_unloaded(unload)
|
||||||
|
script_callbacks.on_before_ui(before_ui)
|
||||||
|
script_callbacks.on_infotext_pasted(networks.infotext_pasted)
|
||||||
|
|
||||||
|
|
||||||
|
shared.options_templates.update(shared.options_section(('extra_networks', "Extra Networks"), {
|
||||||
|
"sd_lora": shared.OptionInfo("None", "Add network to prompt", gr.Dropdown, lambda: {"choices": ["None", *networks.available_networks]}, refresh=networks.list_available_networks),
|
||||||
|
"lora_preferred_name": shared.OptionInfo("Alias from file", "When adding to prompt, refer to Lora by", gr.Radio, {"choices": ["Alias from file", "Filename"]}),
|
||||||
|
"lora_add_hashes_to_infotext": shared.OptionInfo(True, "Add Lora hashes to infotext"),
|
||||||
|
"lora_bundled_ti_to_infotext": shared.OptionInfo(True, "Add Lora name as TI hashes for bundled Textual Inversion").info('"Add Textual Inversion hashes to infotext" needs to be enabled'),
|
||||||
|
"lora_show_all": shared.OptionInfo(False, "Always show all networks on the Lora page").info("otherwise, those detected as for incompatible version of Stable Diffusion will be hidden"),
|
||||||
|
"lora_hide_unknown_for_versions": shared.OptionInfo([], "Hide networks of unknown versions for model versions", gr.CheckboxGroup, {"choices": ["SD1", "SD2", "SDXL"]}),
|
||||||
|
"lora_in_memory_limit": shared.OptionInfo(0, "Number of Lora networks to keep cached in memory", gr.Number, {"precision": 0}),
|
||||||
|
"lora_not_found_warning_console": shared.OptionInfo(False, "Lora not found warning in console"),
|
||||||
|
"lora_not_found_gradio_warning": shared.OptionInfo(False, "Lora not found warning popup in webui"),
|
||||||
|
}))
|
||||||
|
|
||||||
|
|
||||||
|
shared.options_templates.update(shared.options_section(('compatibility', "Compatibility"), {
|
||||||
|
"lora_functional": shared.OptionInfo(False, "Lora/Networks: use old method that takes longer when you have multiple Loras active and produces same results as kohya-ss/sd-webui-additional-networks extension"),
|
||||||
|
}))
|
||||||
|
|
||||||
|
|
||||||
|
def create_lora_json(obj: network.NetworkOnDisk):
|
||||||
|
return {
|
||||||
|
"name": obj.name,
|
||||||
|
"alias": obj.alias,
|
||||||
|
"path": obj.filename,
|
||||||
|
"metadata": obj.metadata,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def api_networks(_: gr.Blocks, app: FastAPI):
|
||||||
|
@app.get("/sdapi/v1/loras")
|
||||||
|
async def get_loras():
|
||||||
|
return [create_lora_json(obj) for obj in networks.available_networks.values()]
|
||||||
|
|
||||||
|
@app.post("/sdapi/v1/refresh-loras")
|
||||||
|
async def refresh_loras():
|
||||||
|
return networks.list_available_networks()
|
||||||
|
|
||||||
|
|
||||||
|
script_callbacks.on_app_started(api_networks)
|
||||||
|
|
||||||
|
re_lora = re.compile("<lora:([^:]+):")
|
||||||
|
|
||||||
|
|
||||||
|
def infotext_pasted(infotext, d):
|
||||||
|
hashes = d.get("Lora hashes")
|
||||||
|
if not hashes:
|
||||||
|
return
|
||||||
|
|
||||||
|
hashes = [x.strip().split(':', 1) for x in hashes.split(",")]
|
||||||
|
hashes = {x[0].strip().replace(",", ""): x[1].strip() for x in hashes}
|
||||||
|
|
||||||
|
def network_replacement(m):
|
||||||
|
alias = m.group(1)
|
||||||
|
shorthash = hashes.get(alias)
|
||||||
|
if shorthash is None:
|
||||||
|
return m.group(0)
|
||||||
|
|
||||||
|
network_on_disk = networks.available_network_hash_lookup.get(shorthash)
|
||||||
|
if network_on_disk is None:
|
||||||
|
return m.group(0)
|
||||||
|
|
||||||
|
return f'<lora:{network_on_disk.get_alias()}:'
|
||||||
|
|
||||||
|
d["Prompt"] = re.sub(re_lora, network_replacement, d["Prompt"])
|
||||||
|
|
||||||
|
|
||||||
|
script_callbacks.on_infotext_pasted(infotext_pasted)
|
||||||
|
|
||||||
|
shared.opts.onchange("lora_in_memory_limit", networks.purge_networks_from_memory)
|
226
extensions-builtin/Lora/ui_edit_user_metadata.py
Normal file
226
extensions-builtin/Lora/ui_edit_user_metadata.py
Normal file
@ -0,0 +1,226 @@
|
|||||||
|
import datetime
|
||||||
|
import html
|
||||||
|
import random
|
||||||
|
|
||||||
|
import gradio as gr
|
||||||
|
import re
|
||||||
|
|
||||||
|
from modules import ui_extra_networks_user_metadata
|
||||||
|
|
||||||
|
|
||||||
|
def is_non_comma_tagset(tags):
|
||||||
|
average_tag_length = sum(len(x) for x in tags.keys()) / len(tags)
|
||||||
|
|
||||||
|
return average_tag_length >= 16
|
||||||
|
|
||||||
|
|
||||||
|
re_word = re.compile(r"[-_\w']+")
|
||||||
|
re_comma = re.compile(r" *, *")
|
||||||
|
|
||||||
|
|
||||||
|
def build_tags(metadata):
|
||||||
|
tags = {}
|
||||||
|
|
||||||
|
ss_tag_frequency = metadata.get("ss_tag_frequency", {})
|
||||||
|
if ss_tag_frequency is not None and hasattr(ss_tag_frequency, 'items'):
|
||||||
|
for _, tags_dict in ss_tag_frequency.items():
|
||||||
|
for tag, tag_count in tags_dict.items():
|
||||||
|
tag = tag.strip()
|
||||||
|
tags[tag] = tags.get(tag, 0) + int(tag_count)
|
||||||
|
|
||||||
|
if tags and is_non_comma_tagset(tags):
|
||||||
|
new_tags = {}
|
||||||
|
|
||||||
|
for text, text_count in tags.items():
|
||||||
|
for word in re.findall(re_word, text):
|
||||||
|
if len(word) < 3:
|
||||||
|
continue
|
||||||
|
|
||||||
|
new_tags[word] = new_tags.get(word, 0) + text_count
|
||||||
|
|
||||||
|
tags = new_tags
|
||||||
|
|
||||||
|
ordered_tags = sorted(tags.keys(), key=tags.get, reverse=True)
|
||||||
|
|
||||||
|
return [(tag, tags[tag]) for tag in ordered_tags]
|
||||||
|
|
||||||
|
|
||||||
|
class LoraUserMetadataEditor(ui_extra_networks_user_metadata.UserMetadataEditor):
|
||||||
|
def __init__(self, ui, tabname, page):
|
||||||
|
super().__init__(ui, tabname, page)
|
||||||
|
|
||||||
|
self.select_sd_version = None
|
||||||
|
|
||||||
|
self.taginfo = None
|
||||||
|
self.edit_activation_text = None
|
||||||
|
self.slider_preferred_weight = None
|
||||||
|
self.edit_notes = None
|
||||||
|
|
||||||
|
def save_lora_user_metadata(self, name, desc, sd_version, activation_text, preferred_weight, negative_text, notes):
|
||||||
|
user_metadata = self.get_user_metadata(name)
|
||||||
|
user_metadata["description"] = desc
|
||||||
|
user_metadata["sd version"] = sd_version
|
||||||
|
user_metadata["activation text"] = activation_text
|
||||||
|
user_metadata["preferred weight"] = preferred_weight
|
||||||
|
user_metadata["negative text"] = negative_text
|
||||||
|
user_metadata["notes"] = notes
|
||||||
|
|
||||||
|
self.write_user_metadata(name, user_metadata)
|
||||||
|
|
||||||
|
def get_metadata_table(self, name):
|
||||||
|
table = super().get_metadata_table(name)
|
||||||
|
item = self.page.items.get(name, {})
|
||||||
|
metadata = item.get("metadata") or {}
|
||||||
|
|
||||||
|
keys = {
|
||||||
|
'ss_output_name': "Output name:",
|
||||||
|
'ss_sd_model_name': "Model:",
|
||||||
|
'ss_clip_skip': "Clip skip:",
|
||||||
|
'ss_network_module': "Kohya module:",
|
||||||
|
}
|
||||||
|
|
||||||
|
for key, label in keys.items():
|
||||||
|
value = metadata.get(key, None)
|
||||||
|
if value is not None and str(value) != "None":
|
||||||
|
table.append((label, html.escape(value)))
|
||||||
|
|
||||||
|
ss_training_started_at = metadata.get('ss_training_started_at')
|
||||||
|
if ss_training_started_at:
|
||||||
|
table.append(("Date trained:", datetime.datetime.utcfromtimestamp(float(ss_training_started_at)).strftime('%Y-%m-%d %H:%M')))
|
||||||
|
|
||||||
|
ss_bucket_info = metadata.get("ss_bucket_info")
|
||||||
|
if ss_bucket_info and "buckets" in ss_bucket_info:
|
||||||
|
resolutions = {}
|
||||||
|
for _, bucket in ss_bucket_info["buckets"].items():
|
||||||
|
resolution = bucket["resolution"]
|
||||||
|
resolution = f'{resolution[1]}x{resolution[0]}'
|
||||||
|
|
||||||
|
resolutions[resolution] = resolutions.get(resolution, 0) + int(bucket["count"])
|
||||||
|
|
||||||
|
resolutions_list = sorted(resolutions.keys(), key=resolutions.get, reverse=True)
|
||||||
|
resolutions_text = html.escape(", ".join(resolutions_list[0:4]))
|
||||||
|
if len(resolutions) > 4:
|
||||||
|
resolutions_text += ", ..."
|
||||||
|
resolutions_text = f"<span title='{html.escape(', '.join(resolutions_list))}'>{resolutions_text}</span>"
|
||||||
|
|
||||||
|
table.append(('Resolutions:' if len(resolutions_list) > 1 else 'Resolution:', resolutions_text))
|
||||||
|
|
||||||
|
image_count = 0
|
||||||
|
for _, params in metadata.get("ss_dataset_dirs", {}).items():
|
||||||
|
image_count += int(params.get("img_count", 0))
|
||||||
|
|
||||||
|
if image_count:
|
||||||
|
table.append(("Dataset size:", image_count))
|
||||||
|
|
||||||
|
return table
|
||||||
|
|
||||||
|
def put_values_into_components(self, name):
|
||||||
|
user_metadata = self.get_user_metadata(name)
|
||||||
|
values = super().put_values_into_components(name)
|
||||||
|
|
||||||
|
item = self.page.items.get(name, {})
|
||||||
|
metadata = item.get("metadata") or {}
|
||||||
|
|
||||||
|
tags = build_tags(metadata)
|
||||||
|
gradio_tags = [(tag, str(count)) for tag, count in tags[0:24]]
|
||||||
|
|
||||||
|
return [
|
||||||
|
*values[0:5],
|
||||||
|
item.get("sd_version", "Unknown"),
|
||||||
|
gr.HighlightedText.update(value=gradio_tags, visible=True if tags else False),
|
||||||
|
user_metadata.get('activation text', ''),
|
||||||
|
float(user_metadata.get('preferred weight', 0.0)),
|
||||||
|
user_metadata.get('negative text', ''),
|
||||||
|
gr.update(visible=True if tags else False),
|
||||||
|
gr.update(value=self.generate_random_prompt_from_tags(tags), visible=True if tags else False),
|
||||||
|
]
|
||||||
|
|
||||||
|
def generate_random_prompt(self, name):
|
||||||
|
item = self.page.items.get(name, {})
|
||||||
|
metadata = item.get("metadata") or {}
|
||||||
|
tags = build_tags(metadata)
|
||||||
|
|
||||||
|
return self.generate_random_prompt_from_tags(tags)
|
||||||
|
|
||||||
|
def generate_random_prompt_from_tags(self, tags):
|
||||||
|
max_count = None
|
||||||
|
res = []
|
||||||
|
for tag, count in tags:
|
||||||
|
if not max_count:
|
||||||
|
max_count = count
|
||||||
|
|
||||||
|
v = random.random() * max_count
|
||||||
|
if count > v:
|
||||||
|
for x in "({[]})":
|
||||||
|
tag = tag.replace(x, '\\' + x)
|
||||||
|
res.append(tag)
|
||||||
|
|
||||||
|
return ", ".join(sorted(res))
|
||||||
|
|
||||||
|
def create_extra_default_items_in_left_column(self):
|
||||||
|
|
||||||
|
# this would be a lot better as gr.Radio but I can't make it work
|
||||||
|
self.select_sd_version = gr.Dropdown(['SD1', 'SD2', 'SDXL', 'Unknown'], value='Unknown', label='Stable Diffusion version', interactive=True)
|
||||||
|
|
||||||
|
def create_editor(self):
|
||||||
|
self.create_default_editor_elems()
|
||||||
|
|
||||||
|
self.taginfo = gr.HighlightedText(label="Training dataset tags")
|
||||||
|
self.edit_activation_text = gr.Text(label='Activation text', info="Will be added to prompt along with Lora")
|
||||||
|
self.slider_preferred_weight = gr.Slider(label='Preferred weight', info="Set to 0 to disable", minimum=0.0, maximum=2.0, step=0.01)
|
||||||
|
self.edit_negative_text = gr.Text(label='Negative prompt', info="Will be added to negative prompts")
|
||||||
|
with gr.Row() as row_random_prompt:
|
||||||
|
with gr.Column(scale=8):
|
||||||
|
random_prompt = gr.Textbox(label='Random prompt', lines=4, max_lines=4, interactive=False)
|
||||||
|
|
||||||
|
with gr.Column(scale=1, min_width=120):
|
||||||
|
generate_random_prompt = gr.Button('Generate', size="lg", scale=1)
|
||||||
|
|
||||||
|
self.edit_notes = gr.TextArea(label='Notes', lines=4)
|
||||||
|
|
||||||
|
generate_random_prompt.click(fn=self.generate_random_prompt, inputs=[self.edit_name_input], outputs=[random_prompt], show_progress=False)
|
||||||
|
|
||||||
|
def select_tag(activation_text, evt: gr.SelectData):
|
||||||
|
tag = evt.value[0]
|
||||||
|
|
||||||
|
words = re.split(re_comma, activation_text)
|
||||||
|
if tag in words:
|
||||||
|
words = [x for x in words if x != tag and x.strip()]
|
||||||
|
return ", ".join(words)
|
||||||
|
|
||||||
|
return activation_text + ", " + tag if activation_text else tag
|
||||||
|
|
||||||
|
self.taginfo.select(fn=select_tag, inputs=[self.edit_activation_text], outputs=[self.edit_activation_text], show_progress=False)
|
||||||
|
|
||||||
|
self.create_default_buttons()
|
||||||
|
|
||||||
|
viewed_components = [
|
||||||
|
self.edit_name,
|
||||||
|
self.edit_description,
|
||||||
|
self.html_filedata,
|
||||||
|
self.html_preview,
|
||||||
|
self.edit_notes,
|
||||||
|
self.select_sd_version,
|
||||||
|
self.taginfo,
|
||||||
|
self.edit_activation_text,
|
||||||
|
self.slider_preferred_weight,
|
||||||
|
self.edit_negative_text,
|
||||||
|
row_random_prompt,
|
||||||
|
random_prompt,
|
||||||
|
]
|
||||||
|
|
||||||
|
self.button_edit\
|
||||||
|
.click(fn=self.put_values_into_components, inputs=[self.edit_name_input], outputs=viewed_components)\
|
||||||
|
.then(fn=lambda: gr.update(visible=True), inputs=[], outputs=[self.box])
|
||||||
|
|
||||||
|
edited_components = [
|
||||||
|
self.edit_description,
|
||||||
|
self.select_sd_version,
|
||||||
|
self.edit_activation_text,
|
||||||
|
self.slider_preferred_weight,
|
||||||
|
self.edit_negative_text,
|
||||||
|
self.edit_notes,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
self.setup_save_handler(self.button_save, self.save_lora_user_metadata, edited_components)
|
90
extensions-builtin/Lora/ui_extra_networks_lora.py
Normal file
90
extensions-builtin/Lora/ui_extra_networks_lora.py
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
import network
|
||||||
|
import networks
|
||||||
|
|
||||||
|
from modules import shared, ui_extra_networks
|
||||||
|
from modules.ui_extra_networks import quote_js
|
||||||
|
from ui_edit_user_metadata import LoraUserMetadataEditor
|
||||||
|
|
||||||
|
|
||||||
|
class ExtraNetworksPageLora(ui_extra_networks.ExtraNetworksPage):
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__('Lora')
|
||||||
|
|
||||||
|
def refresh(self):
|
||||||
|
networks.list_available_networks()
|
||||||
|
|
||||||
|
def create_item(self, name, index=None, enable_filter=True):
|
||||||
|
lora_on_disk = networks.available_networks.get(name)
|
||||||
|
if lora_on_disk is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
path, ext = os.path.splitext(lora_on_disk.filename)
|
||||||
|
|
||||||
|
alias = lora_on_disk.get_alias()
|
||||||
|
|
||||||
|
search_terms = [self.search_terms_from_path(lora_on_disk.filename)]
|
||||||
|
if lora_on_disk.hash:
|
||||||
|
search_terms.append(lora_on_disk.hash)
|
||||||
|
item = {
|
||||||
|
"name": name,
|
||||||
|
"filename": lora_on_disk.filename,
|
||||||
|
"shorthash": lora_on_disk.shorthash,
|
||||||
|
"preview": self.find_preview(path) or self.find_embedded_preview(path, name, lora_on_disk.metadata),
|
||||||
|
"description": self.find_description(path),
|
||||||
|
"search_terms": search_terms,
|
||||||
|
"local_preview": f"{path}.{shared.opts.samples_format}",
|
||||||
|
"metadata": lora_on_disk.metadata,
|
||||||
|
"sort_keys": {'default': index, **self.get_sort_keys(lora_on_disk.filename)},
|
||||||
|
"sd_version": lora_on_disk.sd_version.name,
|
||||||
|
}
|
||||||
|
|
||||||
|
self.read_user_metadata(item)
|
||||||
|
activation_text = item["user_metadata"].get("activation text")
|
||||||
|
preferred_weight = item["user_metadata"].get("preferred weight", 0.0)
|
||||||
|
item["prompt"] = quote_js(f"<lora:{alias}:") + " + " + (str(preferred_weight) if preferred_weight else "opts.extra_networks_default_multiplier") + " + " + quote_js(">")
|
||||||
|
|
||||||
|
if activation_text:
|
||||||
|
item["prompt"] += " + " + quote_js(" " + activation_text)
|
||||||
|
|
||||||
|
negative_prompt = item["user_metadata"].get("negative text")
|
||||||
|
item["negative_prompt"] = quote_js("")
|
||||||
|
if negative_prompt:
|
||||||
|
item["negative_prompt"] = quote_js('(' + negative_prompt + ':1)')
|
||||||
|
|
||||||
|
sd_version = item["user_metadata"].get("sd version")
|
||||||
|
if sd_version in network.SdVersion.__members__:
|
||||||
|
item["sd_version"] = sd_version
|
||||||
|
sd_version = network.SdVersion[sd_version]
|
||||||
|
else:
|
||||||
|
sd_version = lora_on_disk.sd_version
|
||||||
|
|
||||||
|
if shared.opts.lora_show_all or not enable_filter or not shared.sd_model:
|
||||||
|
pass
|
||||||
|
elif sd_version == network.SdVersion.Unknown:
|
||||||
|
model_version = network.SdVersion.SDXL if shared.sd_model.is_sdxl else network.SdVersion.SD2 if shared.sd_model.is_sd2 else network.SdVersion.SD1
|
||||||
|
if model_version.name in shared.opts.lora_hide_unknown_for_versions:
|
||||||
|
return None
|
||||||
|
elif shared.sd_model.is_sdxl and sd_version != network.SdVersion.SDXL:
|
||||||
|
return None
|
||||||
|
elif shared.sd_model.is_sd2 and sd_version != network.SdVersion.SD2:
|
||||||
|
return None
|
||||||
|
elif shared.sd_model.is_sd1 and sd_version != network.SdVersion.SD1:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return item
|
||||||
|
|
||||||
|
def list_items(self):
|
||||||
|
# instantiate a list to protect against concurrent modification
|
||||||
|
names = list(networks.available_networks)
|
||||||
|
for index, name in enumerate(names):
|
||||||
|
item = self.create_item(name, index)
|
||||||
|
if item is not None:
|
||||||
|
yield item
|
||||||
|
|
||||||
|
def allowed_directories_for_previews(self):
|
||||||
|
return [shared.cmd_opts.lora_dir, shared.cmd_opts.lyco_dir_backcompat]
|
||||||
|
|
||||||
|
def create_user_metadata_editor(self, ui, tabname):
|
||||||
|
return LoraUserMetadataEditor(ui, tabname, self)
|
6
extensions-builtin/ScuNET/preload.py
Normal file
6
extensions-builtin/ScuNET/preload.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
import os
|
||||||
|
from modules import paths
|
||||||
|
|
||||||
|
|
||||||
|
def preload(parser):
|
||||||
|
parser.add_argument("--scunet-models-path", type=str, help="Path to directory with ScuNET model file(s).", default=os.path.join(paths.models_path, 'ScuNET'))
|
74
extensions-builtin/ScuNET/scripts/scunet_model.py
Normal file
74
extensions-builtin/ScuNET/scripts/scunet_model.py
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
import sys
|
||||||
|
|
||||||
|
import PIL.Image
|
||||||
|
|
||||||
|
import modules.upscaler
|
||||||
|
from modules import devices, errors, modelloader, script_callbacks, shared, upscaler_utils
|
||||||
|
|
||||||
|
|
||||||
|
class UpscalerScuNET(modules.upscaler.Upscaler):
|
||||||
|
def __init__(self, dirname):
|
||||||
|
self.name = "ScuNET"
|
||||||
|
self.model_name = "ScuNET GAN"
|
||||||
|
self.model_name2 = "ScuNET PSNR"
|
||||||
|
self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/scunet_color_real_gan.pth"
|
||||||
|
self.model_url2 = "https://github.com/cszn/KAIR/releases/download/v1.0/scunet_color_real_psnr.pth"
|
||||||
|
self.user_path = dirname
|
||||||
|
super().__init__()
|
||||||
|
model_paths = self.find_models(ext_filter=[".pth"])
|
||||||
|
scalers = []
|
||||||
|
add_model2 = True
|
||||||
|
for file in model_paths:
|
||||||
|
if file.startswith("http"):
|
||||||
|
name = self.model_name
|
||||||
|
else:
|
||||||
|
name = modelloader.friendly_name(file)
|
||||||
|
if name == self.model_name2 or file == self.model_url2:
|
||||||
|
add_model2 = False
|
||||||
|
try:
|
||||||
|
scaler_data = modules.upscaler.UpscalerData(name, file, self, 4)
|
||||||
|
scalers.append(scaler_data)
|
||||||
|
except Exception:
|
||||||
|
errors.report(f"Error loading ScuNET model: {file}", exc_info=True)
|
||||||
|
if add_model2:
|
||||||
|
scaler_data2 = modules.upscaler.UpscalerData(self.model_name2, self.model_url2, self)
|
||||||
|
scalers.append(scaler_data2)
|
||||||
|
self.scalers = scalers
|
||||||
|
|
||||||
|
def do_upscale(self, img: PIL.Image.Image, selected_file):
|
||||||
|
devices.torch_gc()
|
||||||
|
try:
|
||||||
|
model = self.load_model(selected_file)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"ScuNET: Unable to load model from {selected_file}: {e}", file=sys.stderr)
|
||||||
|
return img
|
||||||
|
|
||||||
|
img = upscaler_utils.upscale_2(
|
||||||
|
img,
|
||||||
|
model,
|
||||||
|
tile_size=shared.opts.SCUNET_tile,
|
||||||
|
tile_overlap=shared.opts.SCUNET_tile_overlap,
|
||||||
|
scale=1, # ScuNET is a denoising model, not an upscaler
|
||||||
|
desc='ScuNET',
|
||||||
|
)
|
||||||
|
devices.torch_gc()
|
||||||
|
return img
|
||||||
|
|
||||||
|
def load_model(self, path: str):
|
||||||
|
device = devices.get_device_for('scunet')
|
||||||
|
if path.startswith("http"):
|
||||||
|
# TODO: this doesn't use `path` at all?
|
||||||
|
filename = modelloader.load_file_from_url(self.model_url, model_dir=self.model_download_path, file_name=f"{self.name}.pth")
|
||||||
|
else:
|
||||||
|
filename = path
|
||||||
|
return modelloader.load_spandrel_model(filename, device=device, expected_architecture='SCUNet')
|
||||||
|
|
||||||
|
|
||||||
|
def on_ui_settings():
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
shared.opts.add_option("SCUNET_tile", shared.OptionInfo(256, "Tile size for SCUNET upscalers.", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")).info("0 = no tiling"))
|
||||||
|
shared.opts.add_option("SCUNET_tile_overlap", shared.OptionInfo(8, "Tile overlap for SCUNET upscalers.", gr.Slider, {"minimum": 0, "maximum": 64, "step": 1}, section=('upscaling', "Upscaling")).info("Low values = visible seam"))
|
||||||
|
|
||||||
|
|
||||||
|
script_callbacks.on_ui_settings(on_ui_settings)
|
6
extensions-builtin/SwinIR/preload.py
Normal file
6
extensions-builtin/SwinIR/preload.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
import os
|
||||||
|
from modules import paths
|
||||||
|
|
||||||
|
|
||||||
|
def preload(parser):
|
||||||
|
parser.add_argument("--swinir-models-path", type=str, help="Path to directory with SwinIR model file(s).", default=os.path.join(paths.models_path, 'SwinIR'))
|
95
extensions-builtin/SwinIR/scripts/swinir_model.py
Normal file
95
extensions-builtin/SwinIR/scripts/swinir_model.py
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
|
||||||
|
from modules.upscaler import Upscaler, UpscalerData
|
||||||
|
|
||||||
|
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth"
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class UpscalerSwinIR(Upscaler):
|
||||||
|
def __init__(self, dirname):
|
||||||
|
self._cached_model = None # keep the model when SWIN_torch_compile is on to prevent re-compile every runs
|
||||||
|
self._cached_model_config = None # to clear '_cached_model' when changing model (v1/v2) or settings
|
||||||
|
self.name = "SwinIR"
|
||||||
|
self.model_url = SWINIR_MODEL_URL
|
||||||
|
self.model_name = "SwinIR 4x"
|
||||||
|
self.user_path = dirname
|
||||||
|
super().__init__()
|
||||||
|
scalers = []
|
||||||
|
model_files = self.find_models(ext_filter=[".pt", ".pth"])
|
||||||
|
for model in model_files:
|
||||||
|
if model.startswith("http"):
|
||||||
|
name = self.model_name
|
||||||
|
else:
|
||||||
|
name = modelloader.friendly_name(model)
|
||||||
|
model_data = UpscalerData(name, model, self)
|
||||||
|
scalers.append(model_data)
|
||||||
|
self.scalers = scalers
|
||||||
|
|
||||||
|
def do_upscale(self, img: Image.Image, model_file: str) -> Image.Image:
|
||||||
|
current_config = (model_file, shared.opts.SWIN_tile)
|
||||||
|
|
||||||
|
if self._cached_model_config == current_config:
|
||||||
|
model = self._cached_model
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
model = self.load_model(model_file)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Failed loading SwinIR model {model_file}: {e}", file=sys.stderr)
|
||||||
|
return img
|
||||||
|
self._cached_model = model
|
||||||
|
self._cached_model_config = current_config
|
||||||
|
|
||||||
|
img = upscaler_utils.upscale_2(
|
||||||
|
img,
|
||||||
|
model,
|
||||||
|
tile_size=shared.opts.SWIN_tile,
|
||||||
|
tile_overlap=shared.opts.SWIN_tile_overlap,
|
||||||
|
scale=model.scale,
|
||||||
|
desc="SwinIR",
|
||||||
|
)
|
||||||
|
devices.torch_gc()
|
||||||
|
return img
|
||||||
|
|
||||||
|
def load_model(self, path, scale=4):
|
||||||
|
if path.startswith("http"):
|
||||||
|
filename = modelloader.load_file_from_url(
|
||||||
|
url=path,
|
||||||
|
model_dir=self.model_download_path,
|
||||||
|
file_name=f"{self.model_name.replace(' ', '_')}.pth",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
filename = path
|
||||||
|
|
||||||
|
model_descriptor = modelloader.load_spandrel_model(
|
||||||
|
filename,
|
||||||
|
device=self._get_device(),
|
||||||
|
prefer_half=(devices.dtype == torch.float16),
|
||||||
|
expected_architecture="SwinIR",
|
||||||
|
)
|
||||||
|
if getattr(shared.opts, 'SWIN_torch_compile', False):
|
||||||
|
try:
|
||||||
|
model_descriptor.model.compile()
|
||||||
|
except Exception:
|
||||||
|
logger.warning("Failed to compile SwinIR model, fallback to JIT", exc_info=True)
|
||||||
|
return model_descriptor
|
||||||
|
|
||||||
|
def _get_device(self):
|
||||||
|
return devices.get_device_for('swinir')
|
||||||
|
|
||||||
|
|
||||||
|
def on_ui_settings():
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
shared.opts.add_option("SWIN_tile", shared.OptionInfo(192, "Tile size for all SwinIR.", gr.Slider, {"minimum": 16, "maximum": 512, "step": 16}, section=('upscaling', "Upscaling")))
|
||||||
|
shared.opts.add_option("SWIN_tile_overlap", shared.OptionInfo(8, "Tile overlap, in pixels for SwinIR. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}, section=('upscaling', "Upscaling")))
|
||||||
|
shared.opts.add_option("SWIN_torch_compile", shared.OptionInfo(False, "Use torch.compile to accelerate SwinIR.", gr.Checkbox, {"interactive": True}, section=('upscaling', "Upscaling")).info("Takes longer on first run"))
|
||||||
|
|
||||||
|
|
||||||
|
script_callbacks.on_ui_settings(on_ui_settings)
|
995
extensions-builtin/canvas-zoom-and-pan/javascript/zoom.js
Normal file
995
extensions-builtin/canvas-zoom-and-pan/javascript/zoom.js
Normal file
@ -0,0 +1,995 @@
|
|||||||
|
onUiLoaded(async() => {
|
||||||
|
const elementIDs = {
|
||||||
|
img2imgTabs: "#mode_img2img .tab-nav",
|
||||||
|
inpaint: "#img2maskimg",
|
||||||
|
inpaintSketch: "#inpaint_sketch",
|
||||||
|
rangeGroup: "#img2img_column_size",
|
||||||
|
sketch: "#img2img_sketch"
|
||||||
|
};
|
||||||
|
const tabNameToElementId = {
|
||||||
|
"Inpaint sketch": elementIDs.inpaintSketch,
|
||||||
|
"Inpaint": elementIDs.inpaint,
|
||||||
|
"Sketch": elementIDs.sketch
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// Helper functions
|
||||||
|
// Get active tab
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Waits for an element to be present in the DOM.
|
||||||
|
*/
|
||||||
|
const waitForElement = (id) => new Promise(resolve => {
|
||||||
|
const checkForElement = () => {
|
||||||
|
const element = document.querySelector(id);
|
||||||
|
if (element) return resolve(element);
|
||||||
|
setTimeout(checkForElement, 100);
|
||||||
|
};
|
||||||
|
checkForElement();
|
||||||
|
});
|
||||||
|
|
||||||
|
function getActiveTab(elements, all = false) {
|
||||||
|
if (!elements.img2imgTabs) return null;
|
||||||
|
const tabs = elements.img2imgTabs.querySelectorAll("button");
|
||||||
|
|
||||||
|
if (all) return tabs;
|
||||||
|
|
||||||
|
for (let tab of tabs) {
|
||||||
|
if (tab.classList.contains("selected")) {
|
||||||
|
return tab;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get tab ID
|
||||||
|
function getTabId(elements) {
|
||||||
|
const activeTab = getActiveTab(elements);
|
||||||
|
if (!activeTab) return null;
|
||||||
|
return tabNameToElementId[activeTab.innerText];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait until opts loaded
|
||||||
|
async function waitForOpts() {
|
||||||
|
for (; ;) {
|
||||||
|
if (window.opts && Object.keys(window.opts).length) {
|
||||||
|
return window.opts;
|
||||||
|
}
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect whether the element has a horizontal scroll bar
|
||||||
|
function hasHorizontalScrollbar(element) {
|
||||||
|
return element.scrollWidth > element.clientWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function for defining the "Ctrl", "Shift" and "Alt" keys
|
||||||
|
function isModifierKey(event, key) {
|
||||||
|
switch (key) {
|
||||||
|
case "Ctrl":
|
||||||
|
return event.ctrlKey;
|
||||||
|
case "Shift":
|
||||||
|
return event.shiftKey;
|
||||||
|
case "Alt":
|
||||||
|
return event.altKey;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if hotkey is valid
|
||||||
|
function isValidHotkey(value) {
|
||||||
|
const specialKeys = ["Ctrl", "Alt", "Shift", "Disable"];
|
||||||
|
return (
|
||||||
|
(typeof value === "string" &&
|
||||||
|
value.length === 1 &&
|
||||||
|
/[a-z]/i.test(value)) ||
|
||||||
|
specialKeys.includes(value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize hotkey
|
||||||
|
function normalizeHotkey(hotkey) {
|
||||||
|
return hotkey.length === 1 ? "Key" + hotkey.toUpperCase() : hotkey;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format hotkey for display
|
||||||
|
function formatHotkeyForDisplay(hotkey) {
|
||||||
|
return hotkey.startsWith("Key") ? hotkey.slice(3) : hotkey;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create hotkey configuration with the provided options
|
||||||
|
function createHotkeyConfig(defaultHotkeysConfig, hotkeysConfigOpts) {
|
||||||
|
const result = {}; // Resulting hotkey configuration
|
||||||
|
const usedKeys = new Set(); // Set of used hotkeys
|
||||||
|
|
||||||
|
// Iterate through defaultHotkeysConfig keys
|
||||||
|
for (const key in defaultHotkeysConfig) {
|
||||||
|
const userValue = hotkeysConfigOpts[key]; // User-provided hotkey value
|
||||||
|
const defaultValue = defaultHotkeysConfig[key]; // Default hotkey value
|
||||||
|
|
||||||
|
// Apply appropriate value for undefined, boolean, or object userValue
|
||||||
|
if (
|
||||||
|
userValue === undefined ||
|
||||||
|
typeof userValue === "boolean" ||
|
||||||
|
typeof userValue === "object" ||
|
||||||
|
userValue === "disable"
|
||||||
|
) {
|
||||||
|
result[key] =
|
||||||
|
userValue === undefined ? defaultValue : userValue;
|
||||||
|
} else if (isValidHotkey(userValue)) {
|
||||||
|
const normalizedUserValue = normalizeHotkey(userValue);
|
||||||
|
|
||||||
|
// Check for conflicting hotkeys
|
||||||
|
if (!usedKeys.has(normalizedUserValue)) {
|
||||||
|
usedKeys.add(normalizedUserValue);
|
||||||
|
result[key] = normalizedUserValue;
|
||||||
|
} else {
|
||||||
|
console.error(
|
||||||
|
`Hotkey: ${formatHotkeyForDisplay(
|
||||||
|
userValue
|
||||||
|
)} for ${key} is repeated and conflicts with another hotkey. The default hotkey is used: ${formatHotkeyForDisplay(
|
||||||
|
defaultValue
|
||||||
|
)}`
|
||||||
|
);
|
||||||
|
result[key] = defaultValue;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error(
|
||||||
|
`Hotkey: ${formatHotkeyForDisplay(
|
||||||
|
userValue
|
||||||
|
)} for ${key} is not valid. The default hotkey is used: ${formatHotkeyForDisplay(
|
||||||
|
defaultValue
|
||||||
|
)}`
|
||||||
|
);
|
||||||
|
result[key] = defaultValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disables functions in the config object based on the provided list of function names
|
||||||
|
function disableFunctions(config, disabledFunctions) {
|
||||||
|
// Bind the hasOwnProperty method to the functionMap object to avoid errors
|
||||||
|
const hasOwnProperty =
|
||||||
|
Object.prototype.hasOwnProperty.bind(functionMap);
|
||||||
|
|
||||||
|
// Loop through the disabledFunctions array and disable the corresponding functions in the config object
|
||||||
|
disabledFunctions.forEach(funcName => {
|
||||||
|
if (hasOwnProperty(funcName)) {
|
||||||
|
const key = functionMap[funcName];
|
||||||
|
config[key] = "disable";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return the updated config object
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The restoreImgRedMask function displays a red mask around an image to indicate the aspect ratio.
|
||||||
|
* If the image display property is set to 'none', the mask breaks. To fix this, the function
|
||||||
|
* temporarily sets the display property to 'block' and then hides the mask again after 300 milliseconds
|
||||||
|
* to avoid breaking the canvas. Additionally, the function adjusts the mask to work correctly on
|
||||||
|
* very long images.
|
||||||
|
*/
|
||||||
|
function restoreImgRedMask(elements) {
|
||||||
|
const mainTabId = getTabId(elements);
|
||||||
|
|
||||||
|
if (!mainTabId) return;
|
||||||
|
|
||||||
|
const mainTab = gradioApp().querySelector(mainTabId);
|
||||||
|
const img = mainTab.querySelector("img");
|
||||||
|
const imageARPreview = gradioApp().querySelector("#imageARPreview");
|
||||||
|
|
||||||
|
if (!img || !imageARPreview) return;
|
||||||
|
|
||||||
|
imageARPreview.style.transform = "";
|
||||||
|
if (parseFloat(mainTab.style.width) > 865) {
|
||||||
|
const transformString = mainTab.style.transform;
|
||||||
|
const scaleMatch = transformString.match(
|
||||||
|
/scale\(([-+]?[0-9]*\.?[0-9]+)\)/
|
||||||
|
);
|
||||||
|
let zoom = 1; // default zoom
|
||||||
|
|
||||||
|
if (scaleMatch && scaleMatch[1]) {
|
||||||
|
zoom = Number(scaleMatch[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
imageARPreview.style.transformOrigin = "0 0";
|
||||||
|
imageARPreview.style.transform = `scale(${zoom})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (img.style.display !== "none") return;
|
||||||
|
|
||||||
|
img.style.display = "block";
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
img.style.display = "none";
|
||||||
|
}, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const hotkeysConfigOpts = await waitForOpts();
|
||||||
|
|
||||||
|
// Default config
|
||||||
|
const defaultHotkeysConfig = {
|
||||||
|
canvas_hotkey_zoom: "Alt",
|
||||||
|
canvas_hotkey_adjust: "Ctrl",
|
||||||
|
canvas_hotkey_reset: "KeyR",
|
||||||
|
canvas_hotkey_fullscreen: "KeyS",
|
||||||
|
canvas_hotkey_move: "KeyF",
|
||||||
|
canvas_hotkey_overlap: "KeyO",
|
||||||
|
canvas_hotkey_shrink_brush: "KeyQ",
|
||||||
|
canvas_hotkey_grow_brush: "KeyW",
|
||||||
|
canvas_disabled_functions: [],
|
||||||
|
canvas_show_tooltip: true,
|
||||||
|
canvas_auto_expand: true,
|
||||||
|
canvas_blur_prompt: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const functionMap = {
|
||||||
|
"Zoom": "canvas_hotkey_zoom",
|
||||||
|
"Adjust brush size": "canvas_hotkey_adjust",
|
||||||
|
"Hotkey shrink brush": "canvas_hotkey_shrink_brush",
|
||||||
|
"Hotkey enlarge brush": "canvas_hotkey_grow_brush",
|
||||||
|
"Moving canvas": "canvas_hotkey_move",
|
||||||
|
"Fullscreen": "canvas_hotkey_fullscreen",
|
||||||
|
"Reset Zoom": "canvas_hotkey_reset",
|
||||||
|
"Overlap": "canvas_hotkey_overlap"
|
||||||
|
};
|
||||||
|
|
||||||
|
// Loading the configuration from opts
|
||||||
|
const preHotkeysConfig = createHotkeyConfig(
|
||||||
|
defaultHotkeysConfig,
|
||||||
|
hotkeysConfigOpts
|
||||||
|
);
|
||||||
|
|
||||||
|
// Disable functions that are not needed by the user
|
||||||
|
const hotkeysConfig = disableFunctions(
|
||||||
|
preHotkeysConfig,
|
||||||
|
preHotkeysConfig.canvas_disabled_functions
|
||||||
|
);
|
||||||
|
|
||||||
|
let isMoving = false;
|
||||||
|
let mouseX, mouseY;
|
||||||
|
let activeElement;
|
||||||
|
let interactedWithAltKey = false;
|
||||||
|
|
||||||
|
const elements = Object.fromEntries(
|
||||||
|
Object.keys(elementIDs).map(id => [
|
||||||
|
id,
|
||||||
|
gradioApp().querySelector(elementIDs[id])
|
||||||
|
])
|
||||||
|
);
|
||||||
|
const elemData = {};
|
||||||
|
|
||||||
|
// Apply functionality to the range inputs. Restore redmask and correct for long images.
|
||||||
|
const rangeInputs = elements.rangeGroup ?
|
||||||
|
Array.from(elements.rangeGroup.querySelectorAll("input")) :
|
||||||
|
[
|
||||||
|
gradioApp().querySelector("#img2img_width input[type='range']"),
|
||||||
|
gradioApp().querySelector("#img2img_height input[type='range']")
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const input of rangeInputs) {
|
||||||
|
input?.addEventListener("input", () => restoreImgRedMask(elements));
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyZoomAndPan(elemId, isExtension = true) {
|
||||||
|
const targetElement = gradioApp().querySelector(elemId);
|
||||||
|
|
||||||
|
if (!targetElement) {
|
||||||
|
console.log("Element not found", elemId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.style.transformOrigin = "0 0";
|
||||||
|
|
||||||
|
elemData[elemId] = {
|
||||||
|
zoom: 1,
|
||||||
|
panX: 0,
|
||||||
|
panY: 0
|
||||||
|
};
|
||||||
|
let fullScreenMode = false;
|
||||||
|
|
||||||
|
// Create tooltip
|
||||||
|
function createTooltip() {
|
||||||
|
const toolTipElement =
|
||||||
|
targetElement.querySelector(".image-container");
|
||||||
|
const tooltip = document.createElement("div");
|
||||||
|
tooltip.className = "canvas-tooltip";
|
||||||
|
|
||||||
|
// Creating an item of information
|
||||||
|
const info = document.createElement("i");
|
||||||
|
info.className = "canvas-tooltip-info";
|
||||||
|
info.textContent = "";
|
||||||
|
|
||||||
|
// Create a container for the contents of the tooltip
|
||||||
|
const tooltipContent = document.createElement("div");
|
||||||
|
tooltipContent.className = "canvas-tooltip-content";
|
||||||
|
|
||||||
|
// Define an array with hotkey information and their actions
|
||||||
|
const hotkeysInfo = [
|
||||||
|
{
|
||||||
|
configKey: "canvas_hotkey_zoom",
|
||||||
|
action: "Zoom canvas",
|
||||||
|
keySuffix: " + wheel"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
configKey: "canvas_hotkey_adjust",
|
||||||
|
action: "Adjust brush size",
|
||||||
|
keySuffix: " + wheel"
|
||||||
|
},
|
||||||
|
{configKey: "canvas_hotkey_reset", action: "Reset zoom"},
|
||||||
|
{
|
||||||
|
configKey: "canvas_hotkey_fullscreen",
|
||||||
|
action: "Fullscreen mode"
|
||||||
|
},
|
||||||
|
{configKey: "canvas_hotkey_move", action: "Move canvas"},
|
||||||
|
{configKey: "canvas_hotkey_overlap", action: "Overlap"}
|
||||||
|
];
|
||||||
|
|
||||||
|
// Create hotkeys array with disabled property based on the config values
|
||||||
|
const hotkeys = hotkeysInfo.map(info => {
|
||||||
|
const configValue = hotkeysConfig[info.configKey];
|
||||||
|
const key = info.keySuffix ?
|
||||||
|
`${configValue}${info.keySuffix}` :
|
||||||
|
configValue.charAt(configValue.length - 1);
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
action: info.action,
|
||||||
|
disabled: configValue === "disable"
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const hotkey of hotkeys) {
|
||||||
|
if (hotkey.disabled) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const p = document.createElement("p");
|
||||||
|
p.innerHTML = `<b>${hotkey.key}</b> - ${hotkey.action}`;
|
||||||
|
tooltipContent.appendChild(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add information and content elements to the tooltip element
|
||||||
|
tooltip.appendChild(info);
|
||||||
|
tooltip.appendChild(tooltipContent);
|
||||||
|
|
||||||
|
// Add a hint element to the target element
|
||||||
|
toolTipElement.appendChild(tooltip);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Show tool tip if setting enable
|
||||||
|
if (hotkeysConfig.canvas_show_tooltip) {
|
||||||
|
createTooltip();
|
||||||
|
}
|
||||||
|
|
||||||
|
// In the course of research, it was found that the tag img is very harmful when zooming and creates white canvases. This hack allows you to almost never think about this problem, it has no effect on webui.
|
||||||
|
function fixCanvas() {
|
||||||
|
const activeTab = getActiveTab(elements)?.textContent.trim();
|
||||||
|
|
||||||
|
if (activeTab && activeTab !== "img2img") {
|
||||||
|
const img = targetElement.querySelector(`${elemId} img`);
|
||||||
|
|
||||||
|
if (img && img.style.display !== "none") {
|
||||||
|
img.style.display = "none";
|
||||||
|
img.style.visibility = "hidden";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset the zoom level and pan position of the target element to their initial values
|
||||||
|
function resetZoom() {
|
||||||
|
elemData[elemId] = {
|
||||||
|
zoomLevel: 1,
|
||||||
|
panX: 0,
|
||||||
|
panY: 0
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.style.overflow = "hidden";
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.isZoomed = false;
|
||||||
|
|
||||||
|
fixCanvas();
|
||||||
|
targetElement.style.transform = `scale(${elemData[elemId].zoomLevel}) translate(${elemData[elemId].panX}px, ${elemData[elemId].panY}px)`;
|
||||||
|
|
||||||
|
const canvas = gradioApp().querySelector(
|
||||||
|
`${elemId} canvas[key="interface"]`
|
||||||
|
);
|
||||||
|
|
||||||
|
toggleOverlap("off");
|
||||||
|
fullScreenMode = false;
|
||||||
|
|
||||||
|
const closeBtn = targetElement.querySelector("button[aria-label='Remove Image']");
|
||||||
|
if (closeBtn) {
|
||||||
|
closeBtn.addEventListener("click", resetZoom);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (canvas && isExtension) {
|
||||||
|
const parentElement = targetElement.closest('[id^="component-"]');
|
||||||
|
if (
|
||||||
|
canvas &&
|
||||||
|
parseFloat(canvas.style.width) > parentElement.offsetWidth &&
|
||||||
|
parseFloat(targetElement.style.width) > parentElement.offsetWidth
|
||||||
|
) {
|
||||||
|
fitToElement();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
canvas &&
|
||||||
|
!isExtension &&
|
||||||
|
parseFloat(canvas.style.width) > 865 &&
|
||||||
|
parseFloat(targetElement.style.width) > 865
|
||||||
|
) {
|
||||||
|
fitToElement();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.style.width = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toggle the zIndex of the target element between two values, allowing it to overlap or be overlapped by other elements
|
||||||
|
function toggleOverlap(forced = "") {
|
||||||
|
const zIndex1 = "0";
|
||||||
|
const zIndex2 = "998";
|
||||||
|
|
||||||
|
targetElement.style.zIndex =
|
||||||
|
targetElement.style.zIndex !== zIndex2 ? zIndex2 : zIndex1;
|
||||||
|
|
||||||
|
if (forced === "off") {
|
||||||
|
targetElement.style.zIndex = zIndex1;
|
||||||
|
} else if (forced === "on") {
|
||||||
|
targetElement.style.zIndex = zIndex2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adjust the brush size based on the deltaY value from a mouse wheel event
|
||||||
|
function adjustBrushSize(
|
||||||
|
elemId,
|
||||||
|
deltaY,
|
||||||
|
withoutValue = false,
|
||||||
|
percentage = 5
|
||||||
|
) {
|
||||||
|
const input =
|
||||||
|
gradioApp().querySelector(
|
||||||
|
`${elemId} input[aria-label='Brush radius']`
|
||||||
|
) ||
|
||||||
|
gradioApp().querySelector(
|
||||||
|
`${elemId} button[aria-label="Use brush"]`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (input) {
|
||||||
|
input.click();
|
||||||
|
if (!withoutValue) {
|
||||||
|
const maxValue =
|
||||||
|
parseFloat(input.getAttribute("max")) || 100;
|
||||||
|
const changeAmount = maxValue * (percentage / 100);
|
||||||
|
const newValue =
|
||||||
|
parseFloat(input.value) +
|
||||||
|
(deltaY > 0 ? -changeAmount : changeAmount);
|
||||||
|
input.value = Math.min(Math.max(newValue, 0), maxValue);
|
||||||
|
input.dispatchEvent(new Event("change"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset zoom when uploading a new image
|
||||||
|
const fileInput = gradioApp().querySelector(
|
||||||
|
`${elemId} input[type="file"][accept="image/*"].svelte-116rqfv`
|
||||||
|
);
|
||||||
|
fileInput.addEventListener("click", resetZoom);
|
||||||
|
|
||||||
|
// Update the zoom level and pan position of the target element based on the values of the zoomLevel, panX and panY variables
|
||||||
|
function updateZoom(newZoomLevel, mouseX, mouseY) {
|
||||||
|
newZoomLevel = Math.max(0.1, Math.min(newZoomLevel, 15));
|
||||||
|
|
||||||
|
elemData[elemId].panX +=
|
||||||
|
mouseX - (mouseX * newZoomLevel) / elemData[elemId].zoomLevel;
|
||||||
|
elemData[elemId].panY +=
|
||||||
|
mouseY - (mouseY * newZoomLevel) / elemData[elemId].zoomLevel;
|
||||||
|
|
||||||
|
targetElement.style.transformOrigin = "0 0";
|
||||||
|
targetElement.style.transform = `translate(${elemData[elemId].panX}px, ${elemData[elemId].panY}px) scale(${newZoomLevel})`;
|
||||||
|
|
||||||
|
toggleOverlap("on");
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.style.overflow = "visible";
|
||||||
|
}
|
||||||
|
|
||||||
|
return newZoomLevel;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Change the zoom level based on user interaction
|
||||||
|
function changeZoomLevel(operation, e) {
|
||||||
|
if (isModifierKey(e, hotkeysConfig.canvas_hotkey_zoom)) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (hotkeysConfig.canvas_hotkey_zoom === "Alt") {
|
||||||
|
interactedWithAltKey = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let zoomPosX, zoomPosY;
|
||||||
|
let delta = 0.2;
|
||||||
|
if (elemData[elemId].zoomLevel > 7) {
|
||||||
|
delta = 0.9;
|
||||||
|
} else if (elemData[elemId].zoomLevel > 2) {
|
||||||
|
delta = 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
zoomPosX = e.clientX;
|
||||||
|
zoomPosY = e.clientY;
|
||||||
|
|
||||||
|
fullScreenMode = false;
|
||||||
|
elemData[elemId].zoomLevel = updateZoom(
|
||||||
|
elemData[elemId].zoomLevel +
|
||||||
|
(operation === "+" ? delta : -delta),
|
||||||
|
zoomPosX - targetElement.getBoundingClientRect().left,
|
||||||
|
zoomPosY - targetElement.getBoundingClientRect().top
|
||||||
|
);
|
||||||
|
|
||||||
|
targetElement.isZoomed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function fits the target element to the screen by calculating
|
||||||
|
* the required scale and offsets. It also updates the global variables
|
||||||
|
* zoomLevel, panX, and panY to reflect the new state.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function fitToElement() {
|
||||||
|
//Reset Zoom
|
||||||
|
targetElement.style.transform = `translate(${0}px, ${0}px) scale(${1})`;
|
||||||
|
|
||||||
|
let parentElement;
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
parentElement = targetElement.closest('[id^="component-"]');
|
||||||
|
} else {
|
||||||
|
parentElement = targetElement.parentElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Get element and screen dimensions
|
||||||
|
const elementWidth = targetElement.offsetWidth;
|
||||||
|
const elementHeight = targetElement.offsetHeight;
|
||||||
|
|
||||||
|
const screenWidth = parentElement.clientWidth;
|
||||||
|
const screenHeight = parentElement.clientHeight;
|
||||||
|
|
||||||
|
// Get element's coordinates relative to the parent element
|
||||||
|
const elementRect = targetElement.getBoundingClientRect();
|
||||||
|
const parentRect = parentElement.getBoundingClientRect();
|
||||||
|
const elementX = elementRect.x - parentRect.x;
|
||||||
|
|
||||||
|
// Calculate scale and offsets
|
||||||
|
const scaleX = screenWidth / elementWidth;
|
||||||
|
const scaleY = screenHeight / elementHeight;
|
||||||
|
const scale = Math.min(scaleX, scaleY);
|
||||||
|
|
||||||
|
const transformOrigin =
|
||||||
|
window.getComputedStyle(targetElement).transformOrigin;
|
||||||
|
const [originX, originY] = transformOrigin.split(" ");
|
||||||
|
const originXValue = parseFloat(originX);
|
||||||
|
const originYValue = parseFloat(originY);
|
||||||
|
|
||||||
|
const offsetX =
|
||||||
|
(screenWidth - elementWidth * scale) / 2 -
|
||||||
|
originXValue * (1 - scale);
|
||||||
|
const offsetY =
|
||||||
|
(screenHeight - elementHeight * scale) / 2.5 -
|
||||||
|
originYValue * (1 - scale);
|
||||||
|
|
||||||
|
// Apply scale and offsets to the element
|
||||||
|
targetElement.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`;
|
||||||
|
|
||||||
|
// Update global variables
|
||||||
|
elemData[elemId].zoomLevel = scale;
|
||||||
|
elemData[elemId].panX = offsetX;
|
||||||
|
elemData[elemId].panY = offsetY;
|
||||||
|
|
||||||
|
fullScreenMode = false;
|
||||||
|
toggleOverlap("off");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function fits the target element to the screen by calculating
|
||||||
|
* the required scale and offsets. It also updates the global variables
|
||||||
|
* zoomLevel, panX, and panY to reflect the new state.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Fullscreen mode
|
||||||
|
function fitToScreen() {
|
||||||
|
const canvas = gradioApp().querySelector(
|
||||||
|
`${elemId} canvas[key="interface"]`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!canvas) return;
|
||||||
|
|
||||||
|
if (canvas.offsetWidth > 862 || isExtension) {
|
||||||
|
targetElement.style.width = (canvas.offsetWidth + 2) + "px";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.style.overflow = "visible";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fullScreenMode) {
|
||||||
|
resetZoom();
|
||||||
|
fullScreenMode = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Reset Zoom
|
||||||
|
targetElement.style.transform = `translate(${0}px, ${0}px) scale(${1})`;
|
||||||
|
|
||||||
|
// Get scrollbar width to right-align the image
|
||||||
|
const scrollbarWidth =
|
||||||
|
window.innerWidth - document.documentElement.clientWidth;
|
||||||
|
|
||||||
|
// Get element and screen dimensions
|
||||||
|
const elementWidth = targetElement.offsetWidth;
|
||||||
|
const elementHeight = targetElement.offsetHeight;
|
||||||
|
const screenWidth = window.innerWidth - scrollbarWidth;
|
||||||
|
const screenHeight = window.innerHeight;
|
||||||
|
|
||||||
|
// Get element's coordinates relative to the page
|
||||||
|
const elementRect = targetElement.getBoundingClientRect();
|
||||||
|
const elementY = elementRect.y;
|
||||||
|
const elementX = elementRect.x;
|
||||||
|
|
||||||
|
// Calculate scale and offsets
|
||||||
|
const scaleX = screenWidth / elementWidth;
|
||||||
|
const scaleY = screenHeight / elementHeight;
|
||||||
|
const scale = Math.min(scaleX, scaleY);
|
||||||
|
|
||||||
|
// Get the current transformOrigin
|
||||||
|
const computedStyle = window.getComputedStyle(targetElement);
|
||||||
|
const transformOrigin = computedStyle.transformOrigin;
|
||||||
|
const [originX, originY] = transformOrigin.split(" ");
|
||||||
|
const originXValue = parseFloat(originX);
|
||||||
|
const originYValue = parseFloat(originY);
|
||||||
|
|
||||||
|
// Calculate offsets with respect to the transformOrigin
|
||||||
|
const offsetX =
|
||||||
|
(screenWidth - elementWidth * scale) / 2 -
|
||||||
|
elementX -
|
||||||
|
originXValue * (1 - scale);
|
||||||
|
const offsetY =
|
||||||
|
(screenHeight - elementHeight * scale) / 2 -
|
||||||
|
elementY -
|
||||||
|
originYValue * (1 - scale);
|
||||||
|
|
||||||
|
// Apply scale and offsets to the element
|
||||||
|
targetElement.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`;
|
||||||
|
|
||||||
|
// Update global variables
|
||||||
|
elemData[elemId].zoomLevel = scale;
|
||||||
|
elemData[elemId].panX = offsetX;
|
||||||
|
elemData[elemId].panY = offsetY;
|
||||||
|
|
||||||
|
fullScreenMode = true;
|
||||||
|
toggleOverlap("on");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle keydown events
|
||||||
|
function handleKeyDown(event) {
|
||||||
|
// Disable key locks to make pasting from the buffer work correctly
|
||||||
|
if ((event.ctrlKey && event.code === 'KeyV') || (event.ctrlKey && event.code === 'KeyC') || event.code === "F5") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// before activating shortcut, ensure user is not actively typing in an input field
|
||||||
|
if (!hotkeysConfig.canvas_blur_prompt) {
|
||||||
|
if (event.target.nodeName === 'TEXTAREA' || event.target.nodeName === 'INPUT') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const hotkeyActions = {
|
||||||
|
[hotkeysConfig.canvas_hotkey_reset]: resetZoom,
|
||||||
|
[hotkeysConfig.canvas_hotkey_overlap]: toggleOverlap,
|
||||||
|
[hotkeysConfig.canvas_hotkey_fullscreen]: fitToScreen,
|
||||||
|
[hotkeysConfig.canvas_hotkey_shrink_brush]: () => adjustBrushSize(elemId, 10),
|
||||||
|
[hotkeysConfig.canvas_hotkey_grow_brush]: () => adjustBrushSize(elemId, -10)
|
||||||
|
};
|
||||||
|
|
||||||
|
const action = hotkeyActions[event.code];
|
||||||
|
if (action) {
|
||||||
|
event.preventDefault();
|
||||||
|
action(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
isModifierKey(event, hotkeysConfig.canvas_hotkey_zoom) ||
|
||||||
|
isModifierKey(event, hotkeysConfig.canvas_hotkey_adjust)
|
||||||
|
) {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get Mouse position
|
||||||
|
function getMousePosition(e) {
|
||||||
|
mouseX = e.offsetX;
|
||||||
|
mouseY = e.offsetY;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simulation of the function to put a long image into the screen.
|
||||||
|
// We detect if an image has a scroll bar or not, make a fullscreen to reveal the image, then reduce it to fit into the element.
|
||||||
|
// We hide the image and show it to the user when it is ready.
|
||||||
|
|
||||||
|
targetElement.isExpanded = false;
|
||||||
|
function autoExpand() {
|
||||||
|
const canvas = document.querySelector(`${elemId} canvas[key="interface"]`);
|
||||||
|
if (canvas) {
|
||||||
|
if (hasHorizontalScrollbar(targetElement) && targetElement.isExpanded === false) {
|
||||||
|
targetElement.style.visibility = "hidden";
|
||||||
|
setTimeout(() => {
|
||||||
|
fitToScreen();
|
||||||
|
resetZoom();
|
||||||
|
targetElement.style.visibility = "visible";
|
||||||
|
targetElement.isExpanded = true;
|
||||||
|
}, 10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.addEventListener("mousemove", getMousePosition);
|
||||||
|
|
||||||
|
//observers
|
||||||
|
// Creating an observer with a callback function to handle DOM changes
|
||||||
|
const observer = new MutationObserver((mutationsList, observer) => {
|
||||||
|
for (let mutation of mutationsList) {
|
||||||
|
// If the style attribute of the canvas has changed, by observation it happens only when the picture changes
|
||||||
|
if (mutation.type === 'attributes' && mutation.attributeName === 'style' &&
|
||||||
|
mutation.target.tagName.toLowerCase() === 'canvas') {
|
||||||
|
targetElement.isExpanded = false;
|
||||||
|
setTimeout(resetZoom, 10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Apply auto expand if enabled
|
||||||
|
if (hotkeysConfig.canvas_auto_expand) {
|
||||||
|
targetElement.addEventListener("mousemove", autoExpand);
|
||||||
|
// Set up an observer to track attribute changes
|
||||||
|
observer.observe(targetElement, {attributes: true, childList: true, subtree: true});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle events only inside the targetElement
|
||||||
|
let isKeyDownHandlerAttached = false;
|
||||||
|
|
||||||
|
function handleMouseMove() {
|
||||||
|
if (!isKeyDownHandlerAttached) {
|
||||||
|
document.addEventListener("keydown", handleKeyDown);
|
||||||
|
isKeyDownHandlerAttached = true;
|
||||||
|
|
||||||
|
activeElement = elemId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMouseLeave() {
|
||||||
|
if (isKeyDownHandlerAttached) {
|
||||||
|
document.removeEventListener("keydown", handleKeyDown);
|
||||||
|
isKeyDownHandlerAttached = false;
|
||||||
|
|
||||||
|
activeElement = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add mouse event handlers
|
||||||
|
targetElement.addEventListener("mousemove", handleMouseMove);
|
||||||
|
targetElement.addEventListener("mouseleave", handleMouseLeave);
|
||||||
|
|
||||||
|
// Reset zoom when click on another tab
|
||||||
|
if (elements.img2imgTabs) {
|
||||||
|
elements.img2imgTabs.addEventListener("click", resetZoom);
|
||||||
|
elements.img2imgTabs.addEventListener("click", () => {
|
||||||
|
// targetElement.style.width = "";
|
||||||
|
if (parseInt(targetElement.style.width) > 865) {
|
||||||
|
setTimeout(fitToElement, 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
targetElement.addEventListener("wheel", e => {
|
||||||
|
// change zoom level
|
||||||
|
const operation = (e.deltaY || -e.wheelDelta) > 0 ? "-" : "+";
|
||||||
|
changeZoomLevel(operation, e);
|
||||||
|
|
||||||
|
// Handle brush size adjustment with ctrl key pressed
|
||||||
|
if (isModifierKey(e, hotkeysConfig.canvas_hotkey_adjust)) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (hotkeysConfig.canvas_hotkey_adjust === "Alt") {
|
||||||
|
interactedWithAltKey = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Increase or decrease brush size based on scroll direction
|
||||||
|
adjustBrushSize(elemId, e.deltaY);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle the move event for pan functionality. Updates the panX and panY variables and applies the new transform to the target element.
|
||||||
|
function handleMoveKeyDown(e) {
|
||||||
|
|
||||||
|
// Disable key locks to make pasting from the buffer work correctly
|
||||||
|
if ((e.ctrlKey && e.code === 'KeyV') || (e.ctrlKey && event.code === 'KeyC') || e.code === "F5") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// before activating shortcut, ensure user is not actively typing in an input field
|
||||||
|
if (!hotkeysConfig.canvas_blur_prompt) {
|
||||||
|
if (e.target.nodeName === 'TEXTAREA' || e.target.nodeName === 'INPUT') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (e.code === hotkeysConfig.canvas_hotkey_move) {
|
||||||
|
if (!e.ctrlKey && !e.metaKey && isKeyDownHandlerAttached) {
|
||||||
|
e.preventDefault();
|
||||||
|
document.activeElement.blur();
|
||||||
|
isMoving = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMoveKeyUp(e) {
|
||||||
|
if (e.code === hotkeysConfig.canvas_hotkey_move) {
|
||||||
|
isMoving = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("keydown", handleMoveKeyDown);
|
||||||
|
document.addEventListener("keyup", handleMoveKeyUp);
|
||||||
|
|
||||||
|
|
||||||
|
// Prevent firefox from opening main menu when alt is used as a hotkey for zoom or brush size
|
||||||
|
function handleAltKeyUp(e) {
|
||||||
|
if (e.key !== "Alt" || !interactedWithAltKey) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
e.preventDefault();
|
||||||
|
interactedWithAltKey = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("keyup", handleAltKeyUp);
|
||||||
|
|
||||||
|
|
||||||
|
// Detect zoom level and update the pan speed.
|
||||||
|
function updatePanPosition(movementX, movementY) {
|
||||||
|
let panSpeed = 2;
|
||||||
|
|
||||||
|
if (elemData[elemId].zoomLevel > 8) {
|
||||||
|
panSpeed = 3.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
elemData[elemId].panX += movementX * panSpeed;
|
||||||
|
elemData[elemId].panY += movementY * panSpeed;
|
||||||
|
|
||||||
|
// Delayed redraw of an element
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
targetElement.style.transform = `translate(${elemData[elemId].panX}px, ${elemData[elemId].panY}px) scale(${elemData[elemId].zoomLevel})`;
|
||||||
|
toggleOverlap("on");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMoveByKey(e) {
|
||||||
|
if (isMoving && elemId === activeElement) {
|
||||||
|
updatePanPosition(e.movementX, e.movementY);
|
||||||
|
targetElement.style.pointerEvents = "none";
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.style.overflow = "visible";
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
targetElement.style.pointerEvents = "auto";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prevents sticking to the mouse
|
||||||
|
window.onblur = function() {
|
||||||
|
isMoving = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Checks for extension
|
||||||
|
function checkForOutBox() {
|
||||||
|
const parentElement = targetElement.closest('[id^="component-"]');
|
||||||
|
if (parentElement.offsetWidth < targetElement.offsetWidth && !targetElement.isExpanded) {
|
||||||
|
resetZoom();
|
||||||
|
targetElement.isExpanded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parentElement.offsetWidth < targetElement.offsetWidth && elemData[elemId].zoomLevel == 1) {
|
||||||
|
resetZoom();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parentElement.offsetWidth < targetElement.offsetWidth && targetElement.offsetWidth * elemData[elemId].zoomLevel > parentElement.offsetWidth && elemData[elemId].zoomLevel < 1 && !targetElement.isZoomed) {
|
||||||
|
resetZoom();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.addEventListener("mousemove", checkForOutBox);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
window.addEventListener('resize', (e) => {
|
||||||
|
resetZoom();
|
||||||
|
|
||||||
|
if (isExtension) {
|
||||||
|
targetElement.isExpanded = false;
|
||||||
|
targetElement.isZoomed = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
gradioApp().addEventListener("mousemove", handleMoveByKey);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
applyZoomAndPan(elementIDs.sketch, false);
|
||||||
|
applyZoomAndPan(elementIDs.inpaint, false);
|
||||||
|
applyZoomAndPan(elementIDs.inpaintSketch, false);
|
||||||
|
|
||||||
|
// Make the function global so that other extensions can take advantage of this solution
|
||||||
|
const applyZoomAndPanIntegration = async(id, elementIDs) => {
|
||||||
|
const mainEl = document.querySelector(id);
|
||||||
|
if (id.toLocaleLowerCase() === "none") {
|
||||||
|
for (const elementID of elementIDs) {
|
||||||
|
const el = await waitForElement(elementID);
|
||||||
|
if (!el) break;
|
||||||
|
applyZoomAndPan(elementID);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mainEl) return;
|
||||||
|
mainEl.addEventListener("click", async() => {
|
||||||
|
for (const elementID of elementIDs) {
|
||||||
|
const el = await waitForElement(elementID);
|
||||||
|
if (!el) break;
|
||||||
|
applyZoomAndPan(elementID);
|
||||||
|
}
|
||||||
|
}, {once: true});
|
||||||
|
};
|
||||||
|
|
||||||
|
window.applyZoomAndPan = applyZoomAndPan; // Only 1 elements, argument elementID, for example applyZoomAndPan("#txt2img_controlnet_ControlNet_input_image")
|
||||||
|
|
||||||
|
window.applyZoomAndPanIntegration = applyZoomAndPanIntegration; // for any extension
|
||||||
|
|
||||||
|
/*
|
||||||
|
The function `applyZoomAndPanIntegration` takes two arguments:
|
||||||
|
|
||||||
|
1. `id`: A string identifier for the element to which zoom and pan functionality will be applied on click.
|
||||||
|
If the `id` value is "none", the functionality will be applied to all elements specified in the second argument without a click event.
|
||||||
|
|
||||||
|
2. `elementIDs`: An array of string identifiers for elements. Zoom and pan functionality will be applied to each of these elements on click of the element specified by the first argument.
|
||||||
|
If "none" is specified in the first argument, the functionality will be applied to each of these elements without a click event.
|
||||||
|
|
||||||
|
Example usage:
|
||||||
|
applyZoomAndPanIntegration("#txt2img_controlnet", ["#txt2img_controlnet_ControlNet_input_image"]);
|
||||||
|
In this example, zoom and pan functionality will be applied to the element with the identifier "txt2img_controlnet_ControlNet_input_image" upon clicking the element with the identifier "txt2img_controlnet".
|
||||||
|
*/
|
||||||
|
|
||||||
|
// More examples
|
||||||
|
// Add integration with ControlNet txt2img One TAB
|
||||||
|
// applyZoomAndPanIntegration("#txt2img_controlnet", ["#txt2img_controlnet_ControlNet_input_image"]);
|
||||||
|
|
||||||
|
// Add integration with ControlNet txt2img Tabs
|
||||||
|
// applyZoomAndPanIntegration("#txt2img_controlnet",Array.from({ length: 10 }, (_, i) => `#txt2img_controlnet_ControlNet-${i}_input_image`));
|
||||||
|
|
||||||
|
// Add integration with Inpaint Anything
|
||||||
|
// applyZoomAndPanIntegration("None", ["#ia_sam_image", "#ia_sel_mask"]);
|
||||||
|
});
|
@ -0,0 +1,17 @@
|
|||||||
|
import gradio as gr
|
||||||
|
from modules import shared
|
||||||
|
|
||||||
|
shared.options_templates.update(shared.options_section(('canvas_hotkey', "Canvas Hotkeys"), {
|
||||||
|
"canvas_hotkey_zoom": shared.OptionInfo("Alt", "Zoom canvas", gr.Radio, {"choices": ["Shift","Ctrl", "Alt"]}).info("If you choose 'Shift' you cannot scroll horizontally, 'Alt' can cause a little trouble in firefox"),
|
||||||
|
"canvas_hotkey_adjust": shared.OptionInfo("Ctrl", "Adjust brush size", gr.Radio, {"choices": ["Shift","Ctrl", "Alt"]}).info("If you choose 'Shift' you cannot scroll horizontally, 'Alt' can cause a little trouble in firefox"),
|
||||||
|
"canvas_hotkey_shrink_brush": shared.OptionInfo("Q", "Shrink the brush size"),
|
||||||
|
"canvas_hotkey_grow_brush": shared.OptionInfo("W", "Enlarge the brush size"),
|
||||||
|
"canvas_hotkey_move": shared.OptionInfo("F", "Moving the canvas").info("To work correctly in firefox, turn off 'Automatically search the page text when typing' in the browser settings"),
|
||||||
|
"canvas_hotkey_fullscreen": shared.OptionInfo("S", "Fullscreen Mode, maximizes the picture so that it fits into the screen and stretches it to its full width "),
|
||||||
|
"canvas_hotkey_reset": shared.OptionInfo("R", "Reset zoom and canvas position"),
|
||||||
|
"canvas_hotkey_overlap": shared.OptionInfo("O", "Toggle overlap").info("Technical button, needed for testing"),
|
||||||
|
"canvas_show_tooltip": shared.OptionInfo(True, "Enable tooltip on the canvas"),
|
||||||
|
"canvas_auto_expand": shared.OptionInfo(True, "Automatically expands an image that does not fit completely in the canvas area, similar to manually pressing the S and R buttons"),
|
||||||
|
"canvas_blur_prompt": shared.OptionInfo(False, "Take the focus off the prompt when working with a canvas"),
|
||||||
|
"canvas_disabled_functions": shared.OptionInfo(["Overlap"], "Disable function that you don't use", gr.CheckboxGroup, {"choices": ["Zoom","Adjust brush size","Hotkey enlarge brush","Hotkey shrink brush","Moving canvas","Fullscreen","Reset Zoom","Overlap"]}),
|
||||||
|
}))
|
66
extensions-builtin/canvas-zoom-and-pan/style.css
Normal file
66
extensions-builtin/canvas-zoom-and-pan/style.css
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
.canvas-tooltip-info {
|
||||||
|
position: absolute;
|
||||||
|
top: 10px;
|
||||||
|
left: 10px;
|
||||||
|
cursor: help;
|
||||||
|
background-color: rgba(0, 0, 0, 0.3);
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
border-radius: 50%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
.canvas-tooltip-info::after {
|
||||||
|
content: '';
|
||||||
|
display: block;
|
||||||
|
width: 2px;
|
||||||
|
height: 7px;
|
||||||
|
background-color: white;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.canvas-tooltip-info::before {
|
||||||
|
content: '';
|
||||||
|
display: block;
|
||||||
|
width: 2px;
|
||||||
|
height: 2px;
|
||||||
|
background-color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.canvas-tooltip-content {
|
||||||
|
display: none;
|
||||||
|
background-color: #f9f9f9;
|
||||||
|
color: #333;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
padding: 15px;
|
||||||
|
position: absolute;
|
||||||
|
top: 40px;
|
||||||
|
left: 10px;
|
||||||
|
width: 250px;
|
||||||
|
font-size: 16px;
|
||||||
|
opacity: 0;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
|
||||||
|
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
.canvas-tooltip:hover .canvas-tooltip-content {
|
||||||
|
display: block;
|
||||||
|
animation: fadeIn 0.5s;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes fadeIn {
|
||||||
|
from {opacity: 0;}
|
||||||
|
to {opacity: 1;}
|
||||||
|
}
|
||||||
|
|
||||||
|
.styler {
|
||||||
|
overflow:inherit !important;
|
||||||
|
}
|
@ -0,0 +1,82 @@
|
|||||||
|
import math
|
||||||
|
|
||||||
|
import gradio as gr
|
||||||
|
from modules import scripts, shared, ui_components, ui_settings, infotext_utils, errors
|
||||||
|
from modules.ui_components import FormColumn
|
||||||
|
|
||||||
|
|
||||||
|
class ExtraOptionsSection(scripts.Script):
|
||||||
|
section = "extra_options"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.comps = None
|
||||||
|
self.setting_names = None
|
||||||
|
|
||||||
|
def title(self):
|
||||||
|
return "Extra options"
|
||||||
|
|
||||||
|
def show(self, is_img2img):
|
||||||
|
return scripts.AlwaysVisible
|
||||||
|
|
||||||
|
def ui(self, is_img2img):
|
||||||
|
self.comps = []
|
||||||
|
self.setting_names = []
|
||||||
|
self.infotext_fields = []
|
||||||
|
extra_options = shared.opts.extra_options_img2img if is_img2img else shared.opts.extra_options_txt2img
|
||||||
|
elem_id_tabname = "extra_options_" + ("img2img" if is_img2img else "txt2img")
|
||||||
|
|
||||||
|
mapping = {k: v for v, k in infotext_utils.infotext_to_setting_name_mapping}
|
||||||
|
|
||||||
|
with gr.Blocks() as interface:
|
||||||
|
with gr.Accordion("Options", open=False, elem_id=elem_id_tabname) if shared.opts.extra_options_accordion and extra_options else gr.Group(elem_id=elem_id_tabname):
|
||||||
|
|
||||||
|
row_count = math.ceil(len(extra_options) / shared.opts.extra_options_cols)
|
||||||
|
|
||||||
|
for row in range(row_count):
|
||||||
|
with gr.Row():
|
||||||
|
for col in range(shared.opts.extra_options_cols):
|
||||||
|
index = row * shared.opts.extra_options_cols + col
|
||||||
|
if index >= len(extra_options):
|
||||||
|
break
|
||||||
|
|
||||||
|
setting_name = extra_options[index]
|
||||||
|
|
||||||
|
with FormColumn():
|
||||||
|
try:
|
||||||
|
comp = ui_settings.create_setting_component(setting_name)
|
||||||
|
except KeyError:
|
||||||
|
errors.report(f"Can't add extra options for {setting_name} in ui")
|
||||||
|
continue
|
||||||
|
|
||||||
|
self.comps.append(comp)
|
||||||
|
self.setting_names.append(setting_name)
|
||||||
|
|
||||||
|
setting_infotext_name = mapping.get(setting_name)
|
||||||
|
if setting_infotext_name is not None:
|
||||||
|
self.infotext_fields.append((comp, setting_infotext_name))
|
||||||
|
|
||||||
|
def get_settings_values():
|
||||||
|
res = [ui_settings.get_value_for_setting(key) for key in self.setting_names]
|
||||||
|
return res[0] if len(res) == 1 else res
|
||||||
|
|
||||||
|
interface.load(fn=get_settings_values, inputs=[], outputs=self.comps, queue=False, show_progress=False)
|
||||||
|
|
||||||
|
return self.comps
|
||||||
|
|
||||||
|
def before_process(self, p, *args):
|
||||||
|
for name, value in zip(self.setting_names, args):
|
||||||
|
if name not in p.override_settings:
|
||||||
|
p.override_settings[name] = value
|
||||||
|
|
||||||
|
|
||||||
|
shared.options_templates.update(shared.options_section(('settings_in_ui', "Settings in UI", "ui"), {
|
||||||
|
"settings_in_ui": shared.OptionHTML("""
|
||||||
|
This page allows you to add some settings to the main interface of txt2img and img2img tabs.
|
||||||
|
"""),
|
||||||
|
"extra_options_txt2img": shared.OptionInfo([], "Settings for txt2img", ui_components.DropdownMulti, lambda: {"choices": list(shared.opts.data_labels.keys())}).js("info", "settingsHintsShowQuicksettings").info("setting entries that also appear in txt2img interfaces").needs_reload_ui(),
|
||||||
|
"extra_options_img2img": shared.OptionInfo([], "Settings for img2img", ui_components.DropdownMulti, lambda: {"choices": list(shared.opts.data_labels.keys())}).js("info", "settingsHintsShowQuicksettings").info("setting entries that also appear in img2img interfaces").needs_reload_ui(),
|
||||||
|
"extra_options_cols": shared.OptionInfo(1, "Number of columns for added settings", gr.Slider, {"step": 1, "minimum": 1, "maximum": 20}).info("displayed amount will depend on the actual browser window width").needs_reload_ui(),
|
||||||
|
"extra_options_accordion": shared.OptionInfo(False, "Place added settings into an accordion").needs_reload_ui()
|
||||||
|
}))
|
||||||
|
|
||||||
|
|
351
extensions-builtin/hypertile/hypertile.py
Normal file
351
extensions-builtin/hypertile/hypertile.py
Normal file
@ -0,0 +1,351 @@
|
|||||||
|
"""
|
||||||
|
Hypertile module for splitting attention layers in SD-1.5 U-Net and SD-1.5 VAE
|
||||||
|
Warn: The patch works well only if the input image has a width and height that are multiples of 128
|
||||||
|
Original author: @tfernd Github: https://github.com/tfernd/HyperTile
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from functools import wraps, cache
|
||||||
|
|
||||||
|
import math
|
||||||
|
import torch.nn as nn
|
||||||
|
import random
|
||||||
|
|
||||||
|
from einops import rearrange
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class HypertileParams:
|
||||||
|
depth = 0
|
||||||
|
layer_name = ""
|
||||||
|
tile_size: int = 0
|
||||||
|
swap_size: int = 0
|
||||||
|
aspect_ratio: float = 1.0
|
||||||
|
forward = None
|
||||||
|
enabled = False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# TODO add SD-XL layers
|
||||||
|
DEPTH_LAYERS = {
|
||||||
|
0: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"down_blocks.0.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"down_blocks.0.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.1.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.2.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.9.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.10.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.11.1.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 VAE
|
||||||
|
"decoder.mid_block.attentions.0",
|
||||||
|
"decoder.mid.attn_1",
|
||||||
|
],
|
||||||
|
1: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"down_blocks.1.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"down_blocks.1.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.2.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.2.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.2.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.4.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.5.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.6.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.7.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.8.1.transformer_blocks.0.attn1",
|
||||||
|
],
|
||||||
|
2: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"down_blocks.2.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"down_blocks.2.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.1.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.1.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.1.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.7.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.3.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.4.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.5.1.transformer_blocks.0.attn1",
|
||||||
|
],
|
||||||
|
3: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"mid_block.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"middle_block.1.transformer_blocks.0.attn1",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
# XL layers, thanks for GitHub@gel-crabs for the help
|
||||||
|
DEPTH_LAYERS_XL = {
|
||||||
|
0: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"down_blocks.0.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"down_blocks.0.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
"up_blocks.3.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.4.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.5.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.3.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.4.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.5.1.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 VAE
|
||||||
|
"decoder.mid_block.attentions.0",
|
||||||
|
"decoder.mid.attn_1",
|
||||||
|
],
|
||||||
|
1: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
#"down_blocks.1.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
#"down_blocks.1.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
#"up_blocks.2.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
#"up_blocks.2.attentions.1.transformer_blocks.0.attn1",
|
||||||
|
#"up_blocks.2.attentions.2.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"input_blocks.4.1.transformer_blocks.1.attn1",
|
||||||
|
"input_blocks.5.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.3.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.4.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.5.1.transformer_blocks.1.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.0.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.0.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.1.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.1.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.1.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.2.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.2.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.2.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.2.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.2.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.3.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.3.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.3.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.3.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.3.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.4.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.4.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.4.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.4.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.4.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.5.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.5.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.5.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.5.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.5.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.6.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.6.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.6.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.6.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.6.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.7.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.7.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.7.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.7.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.7.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.8.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.8.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.8.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.8.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.8.attn1",
|
||||||
|
"input_blocks.7.1.transformer_blocks.9.attn1",
|
||||||
|
"input_blocks.8.1.transformer_blocks.9.attn1",
|
||||||
|
"output_blocks.0.1.transformer_blocks.9.attn1",
|
||||||
|
"output_blocks.1.1.transformer_blocks.9.attn1",
|
||||||
|
"output_blocks.2.1.transformer_blocks.9.attn1",
|
||||||
|
],
|
||||||
|
2: [
|
||||||
|
# SD 1.5 U-Net (diffusers)
|
||||||
|
"mid_block.attentions.0.transformer_blocks.0.attn1",
|
||||||
|
# SD 1.5 U-Net (ldm)
|
||||||
|
"middle_block.1.transformer_blocks.0.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.1.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.2.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.3.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.4.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.5.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.6.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.7.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.8.attn1",
|
||||||
|
"middle_block.1.transformer_blocks.9.attn1",
|
||||||
|
],
|
||||||
|
3 : [] # TODO - separate layers for SD-XL
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
RNG_INSTANCE = random.Random()
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def get_divisors(value: int, min_value: int, /, max_options: int = 1) -> list[int]:
|
||||||
|
"""
|
||||||
|
Returns divisors of value that
|
||||||
|
x * min_value <= value
|
||||||
|
in big -> small order, amount of divisors is limited by max_options
|
||||||
|
"""
|
||||||
|
max_options = max(1, max_options) # at least 1 option should be returned
|
||||||
|
min_value = min(min_value, value)
|
||||||
|
divisors = [i for i in range(min_value, value + 1) if value % i == 0] # divisors in small -> big order
|
||||||
|
ns = [value // i for i in divisors[:max_options]] # has at least 1 element # big -> small order
|
||||||
|
return ns
|
||||||
|
|
||||||
|
|
||||||
|
def random_divisor(value: int, min_value: int, /, max_options: int = 1) -> int:
|
||||||
|
"""
|
||||||
|
Returns a random divisor of value that
|
||||||
|
x * min_value <= value
|
||||||
|
if max_options is 1, the behavior is deterministic
|
||||||
|
"""
|
||||||
|
ns = get_divisors(value, min_value, max_options=max_options) # get cached divisors
|
||||||
|
idx = RNG_INSTANCE.randint(0, len(ns) - 1)
|
||||||
|
|
||||||
|
return ns[idx]
|
||||||
|
|
||||||
|
|
||||||
|
def set_hypertile_seed(seed: int) -> None:
|
||||||
|
RNG_INSTANCE.seed(seed)
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def largest_tile_size_available(width: int, height: int) -> int:
|
||||||
|
"""
|
||||||
|
Calculates the largest tile size available for a given width and height
|
||||||
|
Tile size is always a power of 2
|
||||||
|
"""
|
||||||
|
gcd = math.gcd(width, height)
|
||||||
|
largest_tile_size_available = 1
|
||||||
|
while gcd % (largest_tile_size_available * 2) == 0:
|
||||||
|
largest_tile_size_available *= 2
|
||||||
|
return largest_tile_size_available
|
||||||
|
|
||||||
|
|
||||||
|
def iterative_closest_divisors(hw:int, aspect_ratio:float) -> tuple[int, int]:
|
||||||
|
"""
|
||||||
|
Finds h and w such that h*w = hw and h/w = aspect_ratio
|
||||||
|
We check all possible divisors of hw and return the closest to the aspect ratio
|
||||||
|
"""
|
||||||
|
divisors = [i for i in range(2, hw + 1) if hw % i == 0] # all divisors of hw
|
||||||
|
pairs = [(i, hw // i) for i in divisors] # all pairs of divisors of hw
|
||||||
|
ratios = [w/h for h, w in pairs] # all ratios of pairs of divisors of hw
|
||||||
|
closest_ratio = min(ratios, key=lambda x: abs(x - aspect_ratio)) # closest ratio to aspect_ratio
|
||||||
|
closest_pair = pairs[ratios.index(closest_ratio)] # closest pair of divisors to aspect_ratio
|
||||||
|
return closest_pair
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def find_hw_candidates(hw:int, aspect_ratio:float) -> tuple[int, int]:
|
||||||
|
"""
|
||||||
|
Finds h and w such that h*w = hw and h/w = aspect_ratio
|
||||||
|
"""
|
||||||
|
h, w = round(math.sqrt(hw * aspect_ratio)), round(math.sqrt(hw / aspect_ratio))
|
||||||
|
# find h and w such that h*w = hw and h/w = aspect_ratio
|
||||||
|
if h * w != hw:
|
||||||
|
w_candidate = hw / h
|
||||||
|
# check if w is an integer
|
||||||
|
if not w_candidate.is_integer():
|
||||||
|
h_candidate = hw / w
|
||||||
|
# check if h is an integer
|
||||||
|
if not h_candidate.is_integer():
|
||||||
|
return iterative_closest_divisors(hw, aspect_ratio)
|
||||||
|
else:
|
||||||
|
h = int(h_candidate)
|
||||||
|
else:
|
||||||
|
w = int(w_candidate)
|
||||||
|
return h, w
|
||||||
|
|
||||||
|
|
||||||
|
def self_attn_forward(params: HypertileParams, scale_depth=True) -> Callable:
|
||||||
|
|
||||||
|
@wraps(params.forward)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
if not params.enabled:
|
||||||
|
return params.forward(*args, **kwargs)
|
||||||
|
|
||||||
|
latent_tile_size = max(128, params.tile_size) // 8
|
||||||
|
x = args[0]
|
||||||
|
|
||||||
|
# VAE
|
||||||
|
if x.ndim == 4:
|
||||||
|
b, c, h, w = x.shape
|
||||||
|
|
||||||
|
nh = random_divisor(h, latent_tile_size, params.swap_size)
|
||||||
|
nw = random_divisor(w, latent_tile_size, params.swap_size)
|
||||||
|
|
||||||
|
if nh * nw > 1:
|
||||||
|
x = rearrange(x, "b c (nh h) (nw w) -> (b nh nw) c h w", nh=nh, nw=nw) # split into nh * nw tiles
|
||||||
|
|
||||||
|
out = params.forward(x, *args[1:], **kwargs)
|
||||||
|
|
||||||
|
if nh * nw > 1:
|
||||||
|
out = rearrange(out, "(b nh nw) c h w -> b c (nh h) (nw w)", nh=nh, nw=nw)
|
||||||
|
|
||||||
|
# U-Net
|
||||||
|
else:
|
||||||
|
hw: int = x.size(1)
|
||||||
|
h, w = find_hw_candidates(hw, params.aspect_ratio)
|
||||||
|
assert h * w == hw, f"Invalid aspect ratio {params.aspect_ratio} for input of shape {x.shape}, hw={hw}, h={h}, w={w}"
|
||||||
|
|
||||||
|
factor = 2 ** params.depth if scale_depth else 1
|
||||||
|
nh = random_divisor(h, latent_tile_size * factor, params.swap_size)
|
||||||
|
nw = random_divisor(w, latent_tile_size * factor, params.swap_size)
|
||||||
|
|
||||||
|
if nh * nw > 1:
|
||||||
|
x = rearrange(x, "b (nh h nw w) c -> (b nh nw) (h w) c", h=h // nh, w=w // nw, nh=nh, nw=nw)
|
||||||
|
|
||||||
|
out = params.forward(x, *args[1:], **kwargs)
|
||||||
|
|
||||||
|
if nh * nw > 1:
|
||||||
|
out = rearrange(out, "(b nh nw) hw c -> b nh nw hw c", nh=nh, nw=nw)
|
||||||
|
out = rearrange(out, "b nh nw (h w) c -> b (nh h nw w) c", h=h // nh, w=w // nw)
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
def hypertile_hook_model(model: nn.Module, width, height, *, enable=False, tile_size_max=128, swap_size=1, max_depth=3, is_sdxl=False):
|
||||||
|
hypertile_layers = getattr(model, "__webui_hypertile_layers", None)
|
||||||
|
if hypertile_layers is None:
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
hypertile_layers = {}
|
||||||
|
layers = DEPTH_LAYERS_XL if is_sdxl else DEPTH_LAYERS
|
||||||
|
|
||||||
|
for depth in range(4):
|
||||||
|
for layer_name, module in model.named_modules():
|
||||||
|
if any(layer_name.endswith(try_name) for try_name in layers[depth]):
|
||||||
|
params = HypertileParams()
|
||||||
|
module.__webui_hypertile_params = params
|
||||||
|
params.forward = module.forward
|
||||||
|
params.depth = depth
|
||||||
|
params.layer_name = layer_name
|
||||||
|
module.forward = self_attn_forward(params)
|
||||||
|
|
||||||
|
hypertile_layers[layer_name] = 1
|
||||||
|
|
||||||
|
model.__webui_hypertile_layers = hypertile_layers
|
||||||
|
|
||||||
|
aspect_ratio = width / height
|
||||||
|
tile_size = min(largest_tile_size_available(width, height), tile_size_max)
|
||||||
|
|
||||||
|
for layer_name, module in model.named_modules():
|
||||||
|
if layer_name in hypertile_layers:
|
||||||
|
params = module.__webui_hypertile_params
|
||||||
|
|
||||||
|
params.tile_size = tile_size
|
||||||
|
params.swap_size = swap_size
|
||||||
|
params.aspect_ratio = aspect_ratio
|
||||||
|
params.enabled = enable and params.depth <= max_depth
|
122
extensions-builtin/hypertile/scripts/hypertile_script.py
Normal file
122
extensions-builtin/hypertile/scripts/hypertile_script.py
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
import hypertile
|
||||||
|
from modules import scripts, script_callbacks, shared
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptHypertile(scripts.Script):
|
||||||
|
name = "Hypertile"
|
||||||
|
|
||||||
|
def title(self):
|
||||||
|
return self.name
|
||||||
|
|
||||||
|
def show(self, is_img2img):
|
||||||
|
return scripts.AlwaysVisible
|
||||||
|
|
||||||
|
def process(self, p, *args):
|
||||||
|
hypertile.set_hypertile_seed(p.all_seeds[0])
|
||||||
|
|
||||||
|
configure_hypertile(p.width, p.height, enable_unet=shared.opts.hypertile_enable_unet)
|
||||||
|
|
||||||
|
self.add_infotext(p)
|
||||||
|
|
||||||
|
def before_hr(self, p, *args):
|
||||||
|
|
||||||
|
enable = shared.opts.hypertile_enable_unet_secondpass or shared.opts.hypertile_enable_unet
|
||||||
|
|
||||||
|
# exclusive hypertile seed for the second pass
|
||||||
|
if enable:
|
||||||
|
hypertile.set_hypertile_seed(p.all_seeds[0])
|
||||||
|
|
||||||
|
configure_hypertile(p.hr_upscale_to_x, p.hr_upscale_to_y, enable_unet=enable)
|
||||||
|
|
||||||
|
if enable and not shared.opts.hypertile_enable_unet:
|
||||||
|
p.extra_generation_params["Hypertile U-Net second pass"] = True
|
||||||
|
|
||||||
|
self.add_infotext(p, add_unet_params=True)
|
||||||
|
|
||||||
|
def add_infotext(self, p, add_unet_params=False):
|
||||||
|
def option(name):
|
||||||
|
value = getattr(shared.opts, name)
|
||||||
|
default_value = shared.opts.get_default(name)
|
||||||
|
return None if value == default_value else value
|
||||||
|
|
||||||
|
if shared.opts.hypertile_enable_unet:
|
||||||
|
p.extra_generation_params["Hypertile U-Net"] = True
|
||||||
|
|
||||||
|
if shared.opts.hypertile_enable_unet or add_unet_params:
|
||||||
|
p.extra_generation_params["Hypertile U-Net max depth"] = option('hypertile_max_depth_unet')
|
||||||
|
p.extra_generation_params["Hypertile U-Net max tile size"] = option('hypertile_max_tile_unet')
|
||||||
|
p.extra_generation_params["Hypertile U-Net swap size"] = option('hypertile_swap_size_unet')
|
||||||
|
|
||||||
|
if shared.opts.hypertile_enable_vae:
|
||||||
|
p.extra_generation_params["Hypertile VAE"] = True
|
||||||
|
p.extra_generation_params["Hypertile VAE max depth"] = option('hypertile_max_depth_vae')
|
||||||
|
p.extra_generation_params["Hypertile VAE max tile size"] = option('hypertile_max_tile_vae')
|
||||||
|
p.extra_generation_params["Hypertile VAE swap size"] = option('hypertile_swap_size_vae')
|
||||||
|
|
||||||
|
|
||||||
|
def configure_hypertile(width, height, enable_unet=True):
|
||||||
|
hypertile.hypertile_hook_model(
|
||||||
|
shared.sd_model.first_stage_model,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
swap_size=shared.opts.hypertile_swap_size_vae,
|
||||||
|
max_depth=shared.opts.hypertile_max_depth_vae,
|
||||||
|
tile_size_max=shared.opts.hypertile_max_tile_vae,
|
||||||
|
enable=shared.opts.hypertile_enable_vae,
|
||||||
|
)
|
||||||
|
|
||||||
|
hypertile.hypertile_hook_model(
|
||||||
|
shared.sd_model.model,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
swap_size=shared.opts.hypertile_swap_size_unet,
|
||||||
|
max_depth=shared.opts.hypertile_max_depth_unet,
|
||||||
|
tile_size_max=shared.opts.hypertile_max_tile_unet,
|
||||||
|
enable=enable_unet,
|
||||||
|
is_sdxl=shared.sd_model.is_sdxl
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def on_ui_settings():
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
options = {
|
||||||
|
"hypertile_explanation": shared.OptionHTML("""
|
||||||
|
<a href='https://github.com/tfernd/HyperTile'>Hypertile</a> optimizes the self-attention layer within U-Net and VAE models,
|
||||||
|
resulting in a reduction in computation time ranging from 1 to 4 times. The larger the generated image is, the greater the
|
||||||
|
benefit.
|
||||||
|
"""),
|
||||||
|
|
||||||
|
"hypertile_enable_unet": shared.OptionInfo(False, "Enable Hypertile U-Net", infotext="Hypertile U-Net").info("enables hypertile for all modes, including hires fix second pass; noticeable change in details of the generated picture"),
|
||||||
|
"hypertile_enable_unet_secondpass": shared.OptionInfo(False, "Enable Hypertile U-Net for hires fix second pass", infotext="Hypertile U-Net second pass").info("enables hypertile just for hires fix second pass - regardless of whether the above setting is enabled"),
|
||||||
|
"hypertile_max_depth_unet": shared.OptionInfo(3, "Hypertile U-Net max depth", gr.Slider, {"minimum": 0, "maximum": 3, "step": 1}, infotext="Hypertile U-Net max depth").info("larger = more neural network layers affected; minor effect on performance"),
|
||||||
|
"hypertile_max_tile_unet": shared.OptionInfo(256, "Hypertile U-Net max tile size", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}, infotext="Hypertile U-Net max tile size").info("larger = worse performance"),
|
||||||
|
"hypertile_swap_size_unet": shared.OptionInfo(3, "Hypertile U-Net swap size", gr.Slider, {"minimum": 0, "maximum": 64, "step": 1}, infotext="Hypertile U-Net swap size"),
|
||||||
|
"hypertile_enable_vae": shared.OptionInfo(False, "Enable Hypertile VAE", infotext="Hypertile VAE").info("minimal change in the generated picture"),
|
||||||
|
"hypertile_max_depth_vae": shared.OptionInfo(3, "Hypertile VAE max depth", gr.Slider, {"minimum": 0, "maximum": 3, "step": 1}, infotext="Hypertile VAE max depth"),
|
||||||
|
"hypertile_max_tile_vae": shared.OptionInfo(128, "Hypertile VAE max tile size", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}, infotext="Hypertile VAE max tile size"),
|
||||||
|
"hypertile_swap_size_vae": shared.OptionInfo(3, "Hypertile VAE swap size ", gr.Slider, {"minimum": 0, "maximum": 64, "step": 1}, infotext="Hypertile VAE swap size"),
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, opt in options.items():
|
||||||
|
opt.section = ('hypertile', "Hypertile")
|
||||||
|
shared.opts.add_option(name, opt)
|
||||||
|
|
||||||
|
|
||||||
|
def add_axis_options():
|
||||||
|
xyz_grid = [x for x in scripts.scripts_data if x.script_class.__module__ == "xyz_grid.py"][0].module
|
||||||
|
xyz_grid.axis_options.extend([
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet First pass Enabled", str, xyz_grid.apply_override('hypertile_enable_unet', boolean=True), choices=xyz_grid.boolean_choice(reverse=True)),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet Second pass Enabled", str, xyz_grid.apply_override('hypertile_enable_unet_secondpass', boolean=True), choices=xyz_grid.boolean_choice(reverse=True)),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet Max Depth", int, xyz_grid.apply_override("hypertile_max_depth_unet"), confirm=xyz_grid.confirm_range(0, 3, '[Hypertile] Unet Max Depth'), choices=lambda: [str(x) for x in range(4)]),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet Max Tile Size", int, xyz_grid.apply_override("hypertile_max_tile_unet"), confirm=xyz_grid.confirm_range(0, 512, '[Hypertile] Unet Max Tile Size')),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] Unet Swap Size", int, xyz_grid.apply_override("hypertile_swap_size_unet"), confirm=xyz_grid.confirm_range(0, 64, '[Hypertile] Unet Swap Size')),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] VAE Enabled", str, xyz_grid.apply_override('hypertile_enable_vae', boolean=True), choices=xyz_grid.boolean_choice(reverse=True)),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] VAE Max Depth", int, xyz_grid.apply_override("hypertile_max_depth_vae"), confirm=xyz_grid.confirm_range(0, 3, '[Hypertile] VAE Max Depth'), choices=lambda: [str(x) for x in range(4)]),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] VAE Max Tile Size", int, xyz_grid.apply_override("hypertile_max_tile_vae"), confirm=xyz_grid.confirm_range(0, 512, '[Hypertile] VAE Max Tile Size')),
|
||||||
|
xyz_grid.AxisOption("[Hypertile] VAE Swap Size", int, xyz_grid.apply_override("hypertile_swap_size_vae"), confirm=xyz_grid.confirm_range(0, 64, '[Hypertile] VAE Swap Size')),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
script_callbacks.on_ui_settings(on_ui_settings)
|
||||||
|
script_callbacks.on_before_ui(add_axis_options)
|
34
extensions-builtin/mobile/javascript/mobile.js
Normal file
34
extensions-builtin/mobile/javascript/mobile.js
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
var isSetupForMobile = false;
|
||||||
|
|
||||||
|
function isMobile() {
|
||||||
|
for (var tab of ["txt2img", "img2img"]) {
|
||||||
|
var imageTab = gradioApp().getElementById(tab + '_results');
|
||||||
|
if (imageTab && imageTab.offsetParent && imageTab.offsetLeft == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportWindowSize() {
|
||||||
|
if (gradioApp().querySelector('.toprow-compact-tools')) return; // not applicable for compact prompt layout
|
||||||
|
|
||||||
|
var currentlyMobile = isMobile();
|
||||||
|
if (currentlyMobile == isSetupForMobile) return;
|
||||||
|
isSetupForMobile = currentlyMobile;
|
||||||
|
|
||||||
|
for (var tab of ["txt2img", "img2img"]) {
|
||||||
|
var button = gradioApp().getElementById(tab + '_generate_box');
|
||||||
|
var target = gradioApp().getElementById(currentlyMobile ? tab + '_results' : tab + '_actions_column');
|
||||||
|
target.insertBefore(button, target.firstElementChild);
|
||||||
|
|
||||||
|
gradioApp().getElementById(tab + '_results').classList.toggle('mobile', currentlyMobile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("resize", reportWindowSize);
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
reportWindowSize();
|
||||||
|
});
|
@ -0,0 +1,64 @@
|
|||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from modules import scripts_postprocessing, ui_components
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
|
||||||
|
def center_crop(image: Image, w: int, h: int):
|
||||||
|
iw, ih = image.size
|
||||||
|
if ih / h < iw / w:
|
||||||
|
sw = w * ih / h
|
||||||
|
box = (iw - sw) / 2, 0, iw - (iw - sw) / 2, ih
|
||||||
|
else:
|
||||||
|
sh = h * iw / w
|
||||||
|
box = 0, (ih - sh) / 2, iw, ih - (ih - sh) / 2
|
||||||
|
return image.resize((w, h), Image.Resampling.LANCZOS, box)
|
||||||
|
|
||||||
|
|
||||||
|
def multicrop_pic(image: Image, mindim, maxdim, minarea, maxarea, objective, threshold):
|
||||||
|
iw, ih = image.size
|
||||||
|
err = lambda w, h: 1 - (lambda x: x if x < 1 else 1 / x)(iw / ih / (w / h))
|
||||||
|
wh = max(((w, h) for w in range(mindim, maxdim + 1, 64) for h in range(mindim, maxdim + 1, 64)
|
||||||
|
if minarea <= w * h <= maxarea and err(w, h) <= threshold),
|
||||||
|
key=lambda wh: (wh[0] * wh[1], -err(*wh))[::1 if objective == 'Maximize area' else -1],
|
||||||
|
default=None
|
||||||
|
)
|
||||||
|
return wh and center_crop(image, *wh)
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingAutosizedCrop(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Auto-sized crop"
|
||||||
|
order = 4020
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Auto-sized crop") as enable:
|
||||||
|
gr.Markdown('Each image is center-cropped with an automatically chosen width and height.')
|
||||||
|
with gr.Row():
|
||||||
|
mindim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension lower bound", value=384, elem_id="postprocess_multicrop_mindim")
|
||||||
|
maxdim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension upper bound", value=768, elem_id="postprocess_multicrop_maxdim")
|
||||||
|
with gr.Row():
|
||||||
|
minarea = gr.Slider(minimum=64 * 64, maximum=2048 * 2048, step=1, label="Area lower bound", value=64 * 64, elem_id="postprocess_multicrop_minarea")
|
||||||
|
maxarea = gr.Slider(minimum=64 * 64, maximum=2048 * 2048, step=1, label="Area upper bound", value=640 * 640, elem_id="postprocess_multicrop_maxarea")
|
||||||
|
with gr.Row():
|
||||||
|
objective = gr.Radio(["Maximize area", "Minimize error"], value="Maximize area", label="Resizing objective", elem_id="postprocess_multicrop_objective")
|
||||||
|
threshold = gr.Slider(minimum=0, maximum=1, step=0.01, label="Error threshold", value=0.1, elem_id="postprocess_multicrop_threshold")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"mindim": mindim,
|
||||||
|
"maxdim": maxdim,
|
||||||
|
"minarea": minarea,
|
||||||
|
"maxarea": maxarea,
|
||||||
|
"objective": objective,
|
||||||
|
"threshold": threshold,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, mindim, maxdim, minarea, maxarea, objective, threshold):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
cropped = multicrop_pic(pp.image, mindim, maxdim, minarea, maxarea, objective, threshold)
|
||||||
|
if cropped is not None:
|
||||||
|
pp.image = cropped
|
||||||
|
else:
|
||||||
|
print(f"skipped {pp.image.width}x{pp.image.height} image (can't find suitable size within error threshold)")
|
@ -0,0 +1,30 @@
|
|||||||
|
from modules import scripts_postprocessing, ui_components, deepbooru, shared
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingCeption(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Caption"
|
||||||
|
order = 4040
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Caption") as enable:
|
||||||
|
option = gr.CheckboxGroup(value=["Deepbooru"], choices=["Deepbooru", "BLIP"], show_label=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"option": option,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, option):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
captions = [pp.caption]
|
||||||
|
|
||||||
|
if "Deepbooru" in option:
|
||||||
|
captions.append(deepbooru.model.tag(pp.image))
|
||||||
|
|
||||||
|
if "BLIP" in option:
|
||||||
|
captions.append(shared.interrogator.interrogate(pp.image.convert("RGB")))
|
||||||
|
|
||||||
|
pp.caption = ", ".join([x for x in captions if x])
|
@ -0,0 +1,32 @@
|
|||||||
|
from PIL import ImageOps, Image
|
||||||
|
|
||||||
|
from modules import scripts_postprocessing, ui_components
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingCreateFlippedCopies(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Create flipped copies"
|
||||||
|
order = 4030
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Create flipped copies") as enable:
|
||||||
|
with gr.Row():
|
||||||
|
option = gr.CheckboxGroup(value=["Horizontal"], choices=["Horizontal", "Vertical", "Both"], show_label=False)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"option": option,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, option):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
if "Horizontal" in option:
|
||||||
|
pp.extra_images.append(ImageOps.mirror(pp.image))
|
||||||
|
|
||||||
|
if "Vertical" in option:
|
||||||
|
pp.extra_images.append(pp.image.transpose(Image.Transpose.FLIP_TOP_BOTTOM))
|
||||||
|
|
||||||
|
if "Both" in option:
|
||||||
|
pp.extra_images.append(pp.image.transpose(Image.Transpose.FLIP_TOP_BOTTOM).transpose(Image.Transpose.FLIP_LEFT_RIGHT))
|
@ -0,0 +1,54 @@
|
|||||||
|
|
||||||
|
from modules import scripts_postprocessing, ui_components, errors
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
from modules.textual_inversion import autocrop
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingFocalCrop(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Auto focal point crop"
|
||||||
|
order = 4010
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Auto focal point crop") as enable:
|
||||||
|
face_weight = gr.Slider(label='Focal point face weight', value=0.9, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_focal_crop_face_weight")
|
||||||
|
entropy_weight = gr.Slider(label='Focal point entropy weight', value=0.15, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_focal_crop_entropy_weight")
|
||||||
|
edges_weight = gr.Slider(label='Focal point edges weight', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_focal_crop_edges_weight")
|
||||||
|
debug = gr.Checkbox(label='Create debug image', elem_id="train_process_focal_crop_debug")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"face_weight": face_weight,
|
||||||
|
"entropy_weight": entropy_weight,
|
||||||
|
"edges_weight": edges_weight,
|
||||||
|
"debug": debug,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, face_weight, entropy_weight, edges_weight, debug):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not pp.shared.target_width or not pp.shared.target_height:
|
||||||
|
return
|
||||||
|
|
||||||
|
dnn_model_path = None
|
||||||
|
try:
|
||||||
|
dnn_model_path = autocrop.download_and_cache_models()
|
||||||
|
except Exception:
|
||||||
|
errors.report("Unable to load face detection model for auto crop selection. Falling back to lower quality haar method.", exc_info=True)
|
||||||
|
|
||||||
|
autocrop_settings = autocrop.Settings(
|
||||||
|
crop_width=pp.shared.target_width,
|
||||||
|
crop_height=pp.shared.target_height,
|
||||||
|
face_points_weight=face_weight,
|
||||||
|
entropy_points_weight=entropy_weight,
|
||||||
|
corner_points_weight=edges_weight,
|
||||||
|
annotate_image=debug,
|
||||||
|
dnn_model_path=dnn_model_path,
|
||||||
|
)
|
||||||
|
|
||||||
|
result, *others = autocrop.crop_image(pp.image, autocrop_settings)
|
||||||
|
|
||||||
|
pp.image = result
|
||||||
|
pp.extra_images = [pp.create_copy(x, nametags=["focal-crop-debug"], disable_processing=True) for x in others]
|
||||||
|
|
@ -0,0 +1,71 @@
|
|||||||
|
import math
|
||||||
|
|
||||||
|
from modules import scripts_postprocessing, ui_components
|
||||||
|
import gradio as gr
|
||||||
|
|
||||||
|
|
||||||
|
def split_pic(image, inverse_xy, width, height, overlap_ratio):
|
||||||
|
if inverse_xy:
|
||||||
|
from_w, from_h = image.height, image.width
|
||||||
|
to_w, to_h = height, width
|
||||||
|
else:
|
||||||
|
from_w, from_h = image.width, image.height
|
||||||
|
to_w, to_h = width, height
|
||||||
|
h = from_h * to_w // from_w
|
||||||
|
if inverse_xy:
|
||||||
|
image = image.resize((h, to_w))
|
||||||
|
else:
|
||||||
|
image = image.resize((to_w, h))
|
||||||
|
|
||||||
|
split_count = math.ceil((h - to_h * overlap_ratio) / (to_h * (1.0 - overlap_ratio)))
|
||||||
|
y_step = (h - to_h) / (split_count - 1)
|
||||||
|
for i in range(split_count):
|
||||||
|
y = int(y_step * i)
|
||||||
|
if inverse_xy:
|
||||||
|
splitted = image.crop((y, 0, y + to_h, to_w))
|
||||||
|
else:
|
||||||
|
splitted = image.crop((0, y, to_w, y + to_h))
|
||||||
|
yield splitted
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):
|
||||||
|
name = "Split oversized images"
|
||||||
|
order = 4000
|
||||||
|
|
||||||
|
def ui(self):
|
||||||
|
with ui_components.InputAccordion(False, label="Split oversized images") as enable:
|
||||||
|
with gr.Row():
|
||||||
|
split_threshold = gr.Slider(label='Threshold', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_split_threshold")
|
||||||
|
overlap_ratio = gr.Slider(label='Overlap ratio', value=0.2, minimum=0.0, maximum=0.9, step=0.05, elem_id="postprocess_overlap_ratio")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"enable": enable,
|
||||||
|
"split_threshold": split_threshold,
|
||||||
|
"overlap_ratio": overlap_ratio,
|
||||||
|
}
|
||||||
|
|
||||||
|
def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, split_threshold, overlap_ratio):
|
||||||
|
if not enable:
|
||||||
|
return
|
||||||
|
|
||||||
|
width = pp.shared.target_width
|
||||||
|
height = pp.shared.target_height
|
||||||
|
|
||||||
|
if not width or not height:
|
||||||
|
return
|
||||||
|
|
||||||
|
if pp.image.height > pp.image.width:
|
||||||
|
ratio = (pp.image.width * height) / (pp.image.height * width)
|
||||||
|
inverse_xy = False
|
||||||
|
else:
|
||||||
|
ratio = (pp.image.height * width) / (pp.image.width * height)
|
||||||
|
inverse_xy = True
|
||||||
|
|
||||||
|
if ratio >= 1.0 or ratio > split_threshold:
|
||||||
|
return
|
||||||
|
|
||||||
|
result, *others = split_pic(pp.image, inverse_xy, width, height, overlap_ratio)
|
||||||
|
|
||||||
|
pp.image = result
|
||||||
|
pp.extra_images = [pp.create_copy(x) for x in others]
|
||||||
|
|
@ -0,0 +1,42 @@
|
|||||||
|
// Stable Diffusion WebUI - Bracket checker
|
||||||
|
// By Hingashi no Florin/Bwin4L & @akx
|
||||||
|
// Counts open and closed brackets (round, square, curly) in the prompt and negative prompt text boxes in the txt2img and img2img tabs.
|
||||||
|
// If there's a mismatch, the keyword counter turns red and if you hover on it, a tooltip tells you what's wrong.
|
||||||
|
|
||||||
|
function checkBrackets(textArea, counterElt) {
|
||||||
|
var counts = {};
|
||||||
|
(textArea.value.match(/[(){}[\]]/g) || []).forEach(bracket => {
|
||||||
|
counts[bracket] = (counts[bracket] || 0) + 1;
|
||||||
|
});
|
||||||
|
var errors = [];
|
||||||
|
|
||||||
|
function checkPair(open, close, kind) {
|
||||||
|
if (counts[open] !== counts[close]) {
|
||||||
|
errors.push(
|
||||||
|
`${open}...${close} - Detected ${counts[open] || 0} opening and ${counts[close] || 0} closing ${kind}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
checkPair('(', ')', 'round brackets');
|
||||||
|
checkPair('[', ']', 'square brackets');
|
||||||
|
checkPair('{', '}', 'curly brackets');
|
||||||
|
counterElt.title = errors.join('\n');
|
||||||
|
counterElt.classList.toggle('error', errors.length !== 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupBracketChecking(id_prompt, id_counter) {
|
||||||
|
var textarea = gradioApp().querySelector("#" + id_prompt + " > label > textarea");
|
||||||
|
var counter = gradioApp().getElementById(id_counter);
|
||||||
|
|
||||||
|
if (textarea && counter) {
|
||||||
|
textarea.addEventListener("input", () => checkBrackets(textarea, counter));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
setupBracketChecking('txt2img_prompt', 'txt2img_token_counter');
|
||||||
|
setupBracketChecking('txt2img_neg_prompt', 'txt2img_negative_token_counter');
|
||||||
|
setupBracketChecking('img2img_prompt', 'img2img_token_counter');
|
||||||
|
setupBracketChecking('img2img_neg_prompt', 'img2img_negative_token_counter');
|
||||||
|
});
|
760
extensions-builtin/soft-inpainting/scripts/soft_inpainting.py
Normal file
760
extensions-builtin/soft-inpainting/scripts/soft_inpainting.py
Normal file
@ -0,0 +1,760 @@
|
|||||||
|
import numpy as np
|
||||||
|
import gradio as gr
|
||||||
|
import math
|
||||||
|
from modules.ui_components import InputAccordion
|
||||||
|
import modules.scripts as scripts
|
||||||
|
from modules.torch_utils import float64
|
||||||
|
|
||||||
|
|
||||||
|
class SoftInpaintingSettings:
|
||||||
|
def __init__(self,
|
||||||
|
mask_blend_power,
|
||||||
|
mask_blend_scale,
|
||||||
|
inpaint_detail_preservation,
|
||||||
|
composite_mask_influence,
|
||||||
|
composite_difference_threshold,
|
||||||
|
composite_difference_contrast):
|
||||||
|
self.mask_blend_power = mask_blend_power
|
||||||
|
self.mask_blend_scale = mask_blend_scale
|
||||||
|
self.inpaint_detail_preservation = inpaint_detail_preservation
|
||||||
|
self.composite_mask_influence = composite_mask_influence
|
||||||
|
self.composite_difference_threshold = composite_difference_threshold
|
||||||
|
self.composite_difference_contrast = composite_difference_contrast
|
||||||
|
|
||||||
|
def add_generation_params(self, dest):
|
||||||
|
dest[enabled_gen_param_label] = True
|
||||||
|
dest[gen_param_labels.mask_blend_power] = self.mask_blend_power
|
||||||
|
dest[gen_param_labels.mask_blend_scale] = self.mask_blend_scale
|
||||||
|
dest[gen_param_labels.inpaint_detail_preservation] = self.inpaint_detail_preservation
|
||||||
|
dest[gen_param_labels.composite_mask_influence] = self.composite_mask_influence
|
||||||
|
dest[gen_param_labels.composite_difference_threshold] = self.composite_difference_threshold
|
||||||
|
dest[gen_param_labels.composite_difference_contrast] = self.composite_difference_contrast
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------- Methods -------------------
|
||||||
|
|
||||||
|
def processing_uses_inpainting(p):
|
||||||
|
# TODO: Figure out a better way to determine if inpainting is being used by p
|
||||||
|
if getattr(p, "image_mask", None) is not None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if getattr(p, "mask", None) is not None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if getattr(p, "nmask", None) is not None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def latent_blend(settings, a, b, t):
|
||||||
|
"""
|
||||||
|
Interpolates two latent image representations according to the parameter t,
|
||||||
|
where the interpolated vectors' magnitudes are also interpolated separately.
|
||||||
|
The "detail_preservation" factor biases the magnitude interpolation towards
|
||||||
|
the larger of the two magnitudes.
|
||||||
|
"""
|
||||||
|
import torch
|
||||||
|
|
||||||
|
# NOTE: We use inplace operations wherever possible.
|
||||||
|
|
||||||
|
if len(t.shape) == 3:
|
||||||
|
# [4][w][h] to [1][4][w][h]
|
||||||
|
t2 = t.unsqueeze(0)
|
||||||
|
# [4][w][h] to [1][1][w][h] - the [4] seem redundant.
|
||||||
|
t3 = t[0].unsqueeze(0).unsqueeze(0)
|
||||||
|
else:
|
||||||
|
t2 = t
|
||||||
|
t3 = t[:, 0][:, None]
|
||||||
|
|
||||||
|
one_minus_t2 = 1 - t2
|
||||||
|
one_minus_t3 = 1 - t3
|
||||||
|
|
||||||
|
# Linearly interpolate the image vectors.
|
||||||
|
a_scaled = a * one_minus_t2
|
||||||
|
b_scaled = b * t2
|
||||||
|
image_interp = a_scaled
|
||||||
|
image_interp.add_(b_scaled)
|
||||||
|
result_type = image_interp.dtype
|
||||||
|
del a_scaled, b_scaled, t2, one_minus_t2
|
||||||
|
|
||||||
|
# Calculate the magnitude of the interpolated vectors. (We will remove this magnitude.)
|
||||||
|
# 64-bit operations are used here to allow large exponents.
|
||||||
|
current_magnitude = torch.norm(image_interp, p=2, dim=1, keepdim=True).to(float64(image_interp)).add_(0.00001)
|
||||||
|
|
||||||
|
# Interpolate the powered magnitudes, then un-power them (bring them back to a power of 1).
|
||||||
|
a_magnitude = torch.norm(a, p=2, dim=1, keepdim=True).to(float64(a)).pow_(settings.inpaint_detail_preservation) * one_minus_t3
|
||||||
|
b_magnitude = torch.norm(b, p=2, dim=1, keepdim=True).to(float64(b)).pow_(settings.inpaint_detail_preservation) * t3
|
||||||
|
desired_magnitude = a_magnitude
|
||||||
|
desired_magnitude.add_(b_magnitude).pow_(1 / settings.inpaint_detail_preservation)
|
||||||
|
del a_magnitude, b_magnitude, t3, one_minus_t3
|
||||||
|
|
||||||
|
# Change the linearly interpolated image vectors' magnitudes to the value we want.
|
||||||
|
# This is the last 64-bit operation.
|
||||||
|
image_interp_scaling_factor = desired_magnitude
|
||||||
|
image_interp_scaling_factor.div_(current_magnitude)
|
||||||
|
image_interp_scaling_factor = image_interp_scaling_factor.to(result_type)
|
||||||
|
image_interp_scaled = image_interp
|
||||||
|
image_interp_scaled.mul_(image_interp_scaling_factor)
|
||||||
|
del current_magnitude
|
||||||
|
del desired_magnitude
|
||||||
|
del image_interp
|
||||||
|
del image_interp_scaling_factor
|
||||||
|
del result_type
|
||||||
|
|
||||||
|
return image_interp_scaled
|
||||||
|
|
||||||
|
|
||||||
|
def get_modified_nmask(settings, nmask, sigma):
|
||||||
|
"""
|
||||||
|
Converts a negative mask representing the transparency of the original latent vectors being overlaid
|
||||||
|
to a mask that is scaled according to the denoising strength for this step.
|
||||||
|
|
||||||
|
Where:
|
||||||
|
0 = fully opaque, infinite density, fully masked
|
||||||
|
1 = fully transparent, zero density, fully unmasked
|
||||||
|
|
||||||
|
We bring this transparency to a power, as this allows one to simulate N number of blending operations
|
||||||
|
where N can be any positive real value. Using this one can control the balance of influence between
|
||||||
|
the denoiser and the original latents according to the sigma value.
|
||||||
|
|
||||||
|
NOTE: "mask" is not used
|
||||||
|
"""
|
||||||
|
import torch
|
||||||
|
return torch.pow(nmask, (sigma ** settings.mask_blend_power) * settings.mask_blend_scale)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_adaptive_masks(
|
||||||
|
settings: SoftInpaintingSettings,
|
||||||
|
nmask,
|
||||||
|
latent_orig,
|
||||||
|
latent_processed,
|
||||||
|
overlay_images,
|
||||||
|
width, height,
|
||||||
|
paste_to):
|
||||||
|
import torch
|
||||||
|
import modules.processing as proc
|
||||||
|
import modules.images as images
|
||||||
|
from PIL import Image, ImageOps, ImageFilter
|
||||||
|
|
||||||
|
# TODO: Bias the blending according to the latent mask, add adjustable parameter for bias control.
|
||||||
|
if len(nmask.shape) == 3:
|
||||||
|
latent_mask = nmask[0].float()
|
||||||
|
else:
|
||||||
|
latent_mask = nmask[:, 0].float()
|
||||||
|
# convert the original mask into a form we use to scale distances for thresholding
|
||||||
|
mask_scalar = 1 - (torch.clamp(latent_mask, min=0, max=1) ** (settings.mask_blend_scale / 2))
|
||||||
|
mask_scalar = (0.5 * (1 - settings.composite_mask_influence)
|
||||||
|
+ mask_scalar * settings.composite_mask_influence)
|
||||||
|
mask_scalar = mask_scalar / (1.00001 - mask_scalar)
|
||||||
|
mask_scalar = mask_scalar.cpu().numpy()
|
||||||
|
|
||||||
|
latent_distance = torch.norm(latent_processed - latent_orig, p=2, dim=1)
|
||||||
|
|
||||||
|
kernel, kernel_center = get_gaussian_kernel(stddev_radius=1.5, max_radius=2)
|
||||||
|
|
||||||
|
masks_for_overlay = []
|
||||||
|
|
||||||
|
for i, (distance_map, overlay_image) in enumerate(zip(latent_distance, overlay_images)):
|
||||||
|
converted_mask = distance_map.float().cpu().numpy()
|
||||||
|
converted_mask = weighted_histogram_filter(converted_mask, kernel, kernel_center,
|
||||||
|
percentile_min=0.9, percentile_max=1, min_width=1)
|
||||||
|
converted_mask = weighted_histogram_filter(converted_mask, kernel, kernel_center,
|
||||||
|
percentile_min=0.25, percentile_max=0.75, min_width=1)
|
||||||
|
|
||||||
|
# The distance at which opacity of original decreases to 50%
|
||||||
|
if len(mask_scalar.shape) == 3:
|
||||||
|
if mask_scalar.shape[0] > i:
|
||||||
|
half_weighted_distance = settings.composite_difference_threshold * mask_scalar[i]
|
||||||
|
else:
|
||||||
|
half_weighted_distance = settings.composite_difference_threshold * mask_scalar[0]
|
||||||
|
else:
|
||||||
|
half_weighted_distance = settings.composite_difference_threshold * mask_scalar
|
||||||
|
|
||||||
|
converted_mask = converted_mask / half_weighted_distance
|
||||||
|
|
||||||
|
converted_mask = 1 / (1 + converted_mask ** settings.composite_difference_contrast)
|
||||||
|
converted_mask = smootherstep(converted_mask)
|
||||||
|
converted_mask = 1 - converted_mask
|
||||||
|
converted_mask = 255. * converted_mask
|
||||||
|
converted_mask = converted_mask.astype(np.uint8)
|
||||||
|
converted_mask = Image.fromarray(converted_mask)
|
||||||
|
converted_mask = images.resize_image(2, converted_mask, width, height)
|
||||||
|
converted_mask = proc.create_binary_mask(converted_mask, round=False)
|
||||||
|
|
||||||
|
# Remove aliasing artifacts using a gaussian blur.
|
||||||
|
converted_mask = converted_mask.filter(ImageFilter.GaussianBlur(radius=4))
|
||||||
|
|
||||||
|
# Expand the mask to fit the whole image if needed.
|
||||||
|
if paste_to is not None:
|
||||||
|
converted_mask = proc.uncrop(converted_mask,
|
||||||
|
(overlay_image.width, overlay_image.height),
|
||||||
|
paste_to)
|
||||||
|
|
||||||
|
masks_for_overlay.append(converted_mask)
|
||||||
|
|
||||||
|
image_masked = Image.new('RGBa', (overlay_image.width, overlay_image.height))
|
||||||
|
image_masked.paste(overlay_image.convert("RGBA").convert("RGBa"),
|
||||||
|
mask=ImageOps.invert(converted_mask.convert('L')))
|
||||||
|
|
||||||
|
overlay_images[i] = image_masked.convert('RGBA')
|
||||||
|
|
||||||
|
return masks_for_overlay
|
||||||
|
|
||||||
|
|
||||||
|
def apply_masks(
|
||||||
|
settings,
|
||||||
|
nmask,
|
||||||
|
overlay_images,
|
||||||
|
width, height,
|
||||||
|
paste_to):
|
||||||
|
import torch
|
||||||
|
import modules.processing as proc
|
||||||
|
import modules.images as images
|
||||||
|
from PIL import Image, ImageOps, ImageFilter
|
||||||
|
|
||||||
|
converted_mask = nmask[0].float()
|
||||||
|
converted_mask = torch.clamp(converted_mask, min=0, max=1).pow_(settings.mask_blend_scale / 2)
|
||||||
|
converted_mask = 255. * converted_mask
|
||||||
|
converted_mask = converted_mask.cpu().numpy().astype(np.uint8)
|
||||||
|
converted_mask = Image.fromarray(converted_mask)
|
||||||
|
converted_mask = images.resize_image(2, converted_mask, width, height)
|
||||||
|
converted_mask = proc.create_binary_mask(converted_mask, round=False)
|
||||||
|
|
||||||
|
# Remove aliasing artifacts using a gaussian blur.
|
||||||
|
converted_mask = converted_mask.filter(ImageFilter.GaussianBlur(radius=4))
|
||||||
|
|
||||||
|
# Expand the mask to fit the whole image if needed.
|
||||||
|
if paste_to is not None:
|
||||||
|
converted_mask = proc.uncrop(converted_mask,
|
||||||
|
(width, height),
|
||||||
|
paste_to)
|
||||||
|
|
||||||
|
masks_for_overlay = []
|
||||||
|
|
||||||
|
for i, overlay_image in enumerate(overlay_images):
|
||||||
|
masks_for_overlay[i] = converted_mask
|
||||||
|
|
||||||
|
image_masked = Image.new('RGBa', (overlay_image.width, overlay_image.height))
|
||||||
|
image_masked.paste(overlay_image.convert("RGBA").convert("RGBa"),
|
||||||
|
mask=ImageOps.invert(converted_mask.convert('L')))
|
||||||
|
|
||||||
|
overlay_images[i] = image_masked.convert('RGBA')
|
||||||
|
|
||||||
|
return masks_for_overlay
|
||||||
|
|
||||||
|
|
||||||
|
def weighted_histogram_filter(img, kernel, kernel_center, percentile_min=0.0, percentile_max=1.0, min_width=1.0):
|
||||||
|
"""
|
||||||
|
Generalization convolution filter capable of applying
|
||||||
|
weighted mean, median, maximum, and minimum filters
|
||||||
|
parametrically using an arbitrary kernel.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
img (nparray):
|
||||||
|
The image, a 2-D array of floats, to which the filter is being applied.
|
||||||
|
kernel (nparray):
|
||||||
|
The kernel, a 2-D array of floats.
|
||||||
|
kernel_center (nparray):
|
||||||
|
The kernel center coordinate, a 1-D array with two elements.
|
||||||
|
percentile_min (float):
|
||||||
|
The lower bound of the histogram window used by the filter,
|
||||||
|
from 0 to 1.
|
||||||
|
percentile_max (float):
|
||||||
|
The upper bound of the histogram window used by the filter,
|
||||||
|
from 0 to 1.
|
||||||
|
min_width (float):
|
||||||
|
The minimum size of the histogram window bounds, in weight units.
|
||||||
|
Must be greater than 0.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(nparray): A filtered copy of the input image "img", a 2-D array of floats.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Converts an index tuple into a vector.
|
||||||
|
def vec(x):
|
||||||
|
return np.array(x)
|
||||||
|
|
||||||
|
kernel_min = -kernel_center
|
||||||
|
kernel_max = vec(kernel.shape) - kernel_center
|
||||||
|
|
||||||
|
def weighted_histogram_filter_single(idx):
|
||||||
|
idx = vec(idx)
|
||||||
|
min_index = np.maximum(0, idx + kernel_min)
|
||||||
|
max_index = np.minimum(vec(img.shape), idx + kernel_max)
|
||||||
|
window_shape = max_index - min_index
|
||||||
|
|
||||||
|
class WeightedElement:
|
||||||
|
"""
|
||||||
|
An element of the histogram, its weight
|
||||||
|
and bounds.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, value, weight):
|
||||||
|
self.value: float = value
|
||||||
|
self.weight: float = weight
|
||||||
|
self.window_min: float = 0.0
|
||||||
|
self.window_max: float = 1.0
|
||||||
|
|
||||||
|
# Collect the values in the image as WeightedElements,
|
||||||
|
# weighted by their corresponding kernel values.
|
||||||
|
values = []
|
||||||
|
for window_tup in np.ndindex(tuple(window_shape)):
|
||||||
|
window_index = vec(window_tup)
|
||||||
|
image_index = window_index + min_index
|
||||||
|
centered_kernel_index = image_index - idx
|
||||||
|
kernel_index = centered_kernel_index + kernel_center
|
||||||
|
element = WeightedElement(img[tuple(image_index)], kernel[tuple(kernel_index)])
|
||||||
|
values.append(element)
|
||||||
|
|
||||||
|
def sort_key(x: WeightedElement):
|
||||||
|
return x.value
|
||||||
|
|
||||||
|
values.sort(key=sort_key)
|
||||||
|
|
||||||
|
# Calculate the height of the stack (sum)
|
||||||
|
# and each sample's range they occupy in the stack
|
||||||
|
sum = 0
|
||||||
|
for i in range(len(values)):
|
||||||
|
values[i].window_min = sum
|
||||||
|
sum += values[i].weight
|
||||||
|
values[i].window_max = sum
|
||||||
|
|
||||||
|
# Calculate what range of this stack ("window")
|
||||||
|
# we want to get the weighted average across.
|
||||||
|
window_min = sum * percentile_min
|
||||||
|
window_max = sum * percentile_max
|
||||||
|
window_width = window_max - window_min
|
||||||
|
|
||||||
|
# Ensure the window is within the stack and at least a certain size.
|
||||||
|
if window_width < min_width:
|
||||||
|
window_center = (window_min + window_max) / 2
|
||||||
|
window_min = window_center - min_width / 2
|
||||||
|
window_max = window_center + min_width / 2
|
||||||
|
|
||||||
|
if window_max > sum:
|
||||||
|
window_max = sum
|
||||||
|
window_min = sum - min_width
|
||||||
|
|
||||||
|
if window_min < 0:
|
||||||
|
window_min = 0
|
||||||
|
window_max = min_width
|
||||||
|
|
||||||
|
value = 0
|
||||||
|
value_weight = 0
|
||||||
|
|
||||||
|
# Get the weighted average of all the samples
|
||||||
|
# that overlap with the window, weighted
|
||||||
|
# by the size of their overlap.
|
||||||
|
for i in range(len(values)):
|
||||||
|
if window_min >= values[i].window_max:
|
||||||
|
continue
|
||||||
|
if window_max <= values[i].window_min:
|
||||||
|
break
|
||||||
|
|
||||||
|
s = max(window_min, values[i].window_min)
|
||||||
|
e = min(window_max, values[i].window_max)
|
||||||
|
w = e - s
|
||||||
|
|
||||||
|
value += values[i].value * w
|
||||||
|
value_weight += w
|
||||||
|
|
||||||
|
return value / value_weight if value_weight != 0 else 0
|
||||||
|
|
||||||
|
img_out = img.copy()
|
||||||
|
|
||||||
|
# Apply the kernel operation over each pixel.
|
||||||
|
for index in np.ndindex(img.shape):
|
||||||
|
img_out[index] = weighted_histogram_filter_single(index)
|
||||||
|
|
||||||
|
return img_out
|
||||||
|
|
||||||
|
|
||||||
|
def smoothstep(x):
|
||||||
|
"""
|
||||||
|
The smoothstep function, input should be clamped to 0-1 range.
|
||||||
|
Turns a diagonal line (f(x) = x) into a sigmoid-like curve.
|
||||||
|
"""
|
||||||
|
return x * x * (3 - 2 * x)
|
||||||
|
|
||||||
|
|
||||||
|
def smootherstep(x):
|
||||||
|
"""
|
||||||
|
The smootherstep function, input should be clamped to 0-1 range.
|
||||||
|
Turns a diagonal line (f(x) = x) into a sigmoid-like curve.
|
||||||
|
"""
|
||||||
|
return x * x * x * (x * (6 * x - 15) + 10)
|
||||||
|
|
||||||
|
|
||||||
|
def get_gaussian_kernel(stddev_radius=1.0, max_radius=2):
|
||||||
|
"""
|
||||||
|
Creates a Gaussian kernel with thresholded edges.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stddev_radius (float):
|
||||||
|
Standard deviation of the gaussian kernel, in pixels.
|
||||||
|
max_radius (int):
|
||||||
|
The size of the filter kernel. The number of pixels is (max_radius*2+1) ** 2.
|
||||||
|
The kernel is thresholded so that any values one pixel beyond this radius
|
||||||
|
is weighted at 0.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(nparray, nparray): A kernel array (shape: (N, N)), its center coordinate (shape: (2))
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Evaluates a 0-1 normalized gaussian function for a given square distance from the mean.
|
||||||
|
def gaussian(sqr_mag):
|
||||||
|
return math.exp(-sqr_mag / (stddev_radius * stddev_radius))
|
||||||
|
|
||||||
|
# Helper function for converting a tuple to an array.
|
||||||
|
def vec(x):
|
||||||
|
return np.array(x)
|
||||||
|
|
||||||
|
"""
|
||||||
|
Since a gaussian is unbounded, we need to limit ourselves
|
||||||
|
to a finite range.
|
||||||
|
We taper the ends off at the end of that range so they equal zero
|
||||||
|
while preserving the maximum value of 1 at the mean.
|
||||||
|
"""
|
||||||
|
zero_radius = max_radius + 1.0
|
||||||
|
gauss_zero = gaussian(zero_radius * zero_radius)
|
||||||
|
gauss_kernel_scale = 1 / (1 - gauss_zero)
|
||||||
|
|
||||||
|
def gaussian_kernel_func(coordinate):
|
||||||
|
x = coordinate[0] ** 2.0 + coordinate[1] ** 2.0
|
||||||
|
x = gaussian(x)
|
||||||
|
x -= gauss_zero
|
||||||
|
x *= gauss_kernel_scale
|
||||||
|
x = max(0.0, x)
|
||||||
|
return x
|
||||||
|
|
||||||
|
size = max_radius * 2 + 1
|
||||||
|
kernel_center = max_radius
|
||||||
|
kernel = np.zeros((size, size))
|
||||||
|
|
||||||
|
for index in np.ndindex(kernel.shape):
|
||||||
|
kernel[index] = gaussian_kernel_func(vec(index) - kernel_center)
|
||||||
|
|
||||||
|
return kernel, kernel_center
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------- Constants -------------------
|
||||||
|
|
||||||
|
|
||||||
|
default = SoftInpaintingSettings(1, 0.5, 4, 0, 0.5, 2)
|
||||||
|
|
||||||
|
enabled_ui_label = "Soft inpainting"
|
||||||
|
enabled_gen_param_label = "Soft inpainting enabled"
|
||||||
|
enabled_el_id = "soft_inpainting_enabled"
|
||||||
|
|
||||||
|
ui_labels = SoftInpaintingSettings(
|
||||||
|
"Schedule bias",
|
||||||
|
"Preservation strength",
|
||||||
|
"Transition contrast boost",
|
||||||
|
"Mask influence",
|
||||||
|
"Difference threshold",
|
||||||
|
"Difference contrast")
|
||||||
|
|
||||||
|
ui_info = SoftInpaintingSettings(
|
||||||
|
"Shifts when preservation of original content occurs during denoising.",
|
||||||
|
"How strongly partially masked content should be preserved.",
|
||||||
|
"Amplifies the contrast that may be lost in partially masked regions.",
|
||||||
|
"How strongly the original mask should bias the difference threshold.",
|
||||||
|
"How much an image region can change before the original pixels are not blended in anymore.",
|
||||||
|
"How sharp the transition should be between blended and not blended.")
|
||||||
|
|
||||||
|
gen_param_labels = SoftInpaintingSettings(
|
||||||
|
"Soft inpainting schedule bias",
|
||||||
|
"Soft inpainting preservation strength",
|
||||||
|
"Soft inpainting transition contrast boost",
|
||||||
|
"Soft inpainting mask influence",
|
||||||
|
"Soft inpainting difference threshold",
|
||||||
|
"Soft inpainting difference contrast")
|
||||||
|
|
||||||
|
el_ids = SoftInpaintingSettings(
|
||||||
|
"mask_blend_power",
|
||||||
|
"mask_blend_scale",
|
||||||
|
"inpaint_detail_preservation",
|
||||||
|
"composite_mask_influence",
|
||||||
|
"composite_difference_threshold",
|
||||||
|
"composite_difference_contrast")
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------- Script -------------------
|
||||||
|
|
||||||
|
|
||||||
|
class Script(scripts.Script):
|
||||||
|
def __init__(self):
|
||||||
|
self.section = "inpaint"
|
||||||
|
self.masks_for_overlay = None
|
||||||
|
self.overlay_images = None
|
||||||
|
|
||||||
|
def title(self):
|
||||||
|
return "Soft Inpainting"
|
||||||
|
|
||||||
|
def show(self, is_img2img):
|
||||||
|
return scripts.AlwaysVisible if is_img2img else False
|
||||||
|
|
||||||
|
def ui(self, is_img2img):
|
||||||
|
if not is_img2img:
|
||||||
|
return
|
||||||
|
|
||||||
|
with InputAccordion(False, label=enabled_ui_label, elem_id=enabled_el_id) as soft_inpainting_enabled:
|
||||||
|
with gr.Group():
|
||||||
|
gr.Markdown(
|
||||||
|
"""
|
||||||
|
Soft inpainting allows you to **seamlessly blend original content with inpainted content** according to the mask opacity.
|
||||||
|
**High _Mask blur_** values are recommended!
|
||||||
|
""")
|
||||||
|
|
||||||
|
power = \
|
||||||
|
gr.Slider(label=ui_labels.mask_blend_power,
|
||||||
|
info=ui_info.mask_blend_power,
|
||||||
|
minimum=0,
|
||||||
|
maximum=8,
|
||||||
|
step=0.1,
|
||||||
|
value=default.mask_blend_power,
|
||||||
|
elem_id=el_ids.mask_blend_power)
|
||||||
|
scale = \
|
||||||
|
gr.Slider(label=ui_labels.mask_blend_scale,
|
||||||
|
info=ui_info.mask_blend_scale,
|
||||||
|
minimum=0,
|
||||||
|
maximum=8,
|
||||||
|
step=0.05,
|
||||||
|
value=default.mask_blend_scale,
|
||||||
|
elem_id=el_ids.mask_blend_scale)
|
||||||
|
detail = \
|
||||||
|
gr.Slider(label=ui_labels.inpaint_detail_preservation,
|
||||||
|
info=ui_info.inpaint_detail_preservation,
|
||||||
|
minimum=1,
|
||||||
|
maximum=32,
|
||||||
|
step=0.5,
|
||||||
|
value=default.inpaint_detail_preservation,
|
||||||
|
elem_id=el_ids.inpaint_detail_preservation)
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
"""
|
||||||
|
### Pixel Composite Settings
|
||||||
|
""")
|
||||||
|
|
||||||
|
mask_inf = \
|
||||||
|
gr.Slider(label=ui_labels.composite_mask_influence,
|
||||||
|
info=ui_info.composite_mask_influence,
|
||||||
|
minimum=0,
|
||||||
|
maximum=1,
|
||||||
|
step=0.05,
|
||||||
|
value=default.composite_mask_influence,
|
||||||
|
elem_id=el_ids.composite_mask_influence)
|
||||||
|
|
||||||
|
dif_thresh = \
|
||||||
|
gr.Slider(label=ui_labels.composite_difference_threshold,
|
||||||
|
info=ui_info.composite_difference_threshold,
|
||||||
|
minimum=0,
|
||||||
|
maximum=8,
|
||||||
|
step=0.25,
|
||||||
|
value=default.composite_difference_threshold,
|
||||||
|
elem_id=el_ids.composite_difference_threshold)
|
||||||
|
|
||||||
|
dif_contr = \
|
||||||
|
gr.Slider(label=ui_labels.composite_difference_contrast,
|
||||||
|
info=ui_info.composite_difference_contrast,
|
||||||
|
minimum=0,
|
||||||
|
maximum=8,
|
||||||
|
step=0.25,
|
||||||
|
value=default.composite_difference_contrast,
|
||||||
|
elem_id=el_ids.composite_difference_contrast)
|
||||||
|
|
||||||
|
with gr.Accordion("Help", open=False):
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.mask_blend_power}
|
||||||
|
|
||||||
|
The blending strength of original content is scaled proportionally with the decreasing noise level values at each step (sigmas).
|
||||||
|
This ensures that the influence of the denoiser and original content preservation is roughly balanced at each step.
|
||||||
|
This balance can be shifted using this parameter, controlling whether earlier or later steps have stronger preservation.
|
||||||
|
|
||||||
|
- **Below 1**: Stronger preservation near the end (with low sigma)
|
||||||
|
- **1**: Balanced (proportional to sigma)
|
||||||
|
- **Above 1**: Stronger preservation in the beginning (with high sigma)
|
||||||
|
""")
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.mask_blend_scale}
|
||||||
|
|
||||||
|
Skews whether partially masked image regions should be more likely to preserve the original content or favor inpainted content.
|
||||||
|
This may need to be adjusted depending on the {ui_labels.mask_blend_power}, CFG Scale, prompt and Denoising strength.
|
||||||
|
|
||||||
|
- **Low values**: Favors generated content.
|
||||||
|
- **High values**: Favors original content.
|
||||||
|
""")
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.inpaint_detail_preservation}
|
||||||
|
|
||||||
|
This parameter controls how the original latent vectors and denoised latent vectors are interpolated.
|
||||||
|
With higher values, the magnitude of the resulting blended vector will be closer to the maximum of the two interpolated vectors.
|
||||||
|
This can prevent the loss of contrast that occurs with linear interpolation.
|
||||||
|
|
||||||
|
- **Low values**: Softer blending, details may fade.
|
||||||
|
- **High values**: Stronger contrast, may over-saturate colors.
|
||||||
|
""")
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
"""
|
||||||
|
## Pixel Composite Settings
|
||||||
|
|
||||||
|
Masks are generated based on how much a part of the image changed after denoising.
|
||||||
|
These masks are used to blend the original and final images together.
|
||||||
|
If the difference is low, the original pixels are used instead of the pixels returned by the inpainting process.
|
||||||
|
""")
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.composite_mask_influence}
|
||||||
|
|
||||||
|
This parameter controls how much the mask should bias this sensitivity to difference.
|
||||||
|
|
||||||
|
- **0**: Ignore the mask, only consider differences in image content.
|
||||||
|
- **1**: Follow the mask closely despite image content changes.
|
||||||
|
""")
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.composite_difference_threshold}
|
||||||
|
|
||||||
|
This value represents the difference at which the original pixels will have less than 50% opacity.
|
||||||
|
|
||||||
|
- **Low values**: Two images patches must be almost the same in order to retain original pixels.
|
||||||
|
- **High values**: Two images patches can be very different and still retain original pixels.
|
||||||
|
""")
|
||||||
|
|
||||||
|
gr.Markdown(
|
||||||
|
f"""
|
||||||
|
### {ui_labels.composite_difference_contrast}
|
||||||
|
|
||||||
|
This value represents the contrast between the opacity of the original and inpainted content.
|
||||||
|
|
||||||
|
- **Low values**: The blend will be more gradual and have longer transitions, but may cause ghosting.
|
||||||
|
- **High values**: Ghosting will be less common, but transitions may be very sudden.
|
||||||
|
""")
|
||||||
|
|
||||||
|
self.infotext_fields = [(soft_inpainting_enabled, enabled_gen_param_label),
|
||||||
|
(power, gen_param_labels.mask_blend_power),
|
||||||
|
(scale, gen_param_labels.mask_blend_scale),
|
||||||
|
(detail, gen_param_labels.inpaint_detail_preservation),
|
||||||
|
(mask_inf, gen_param_labels.composite_mask_influence),
|
||||||
|
(dif_thresh, gen_param_labels.composite_difference_threshold),
|
||||||
|
(dif_contr, gen_param_labels.composite_difference_contrast)]
|
||||||
|
|
||||||
|
self.paste_field_names = []
|
||||||
|
for _, field_name in self.infotext_fields:
|
||||||
|
self.paste_field_names.append(field_name)
|
||||||
|
|
||||||
|
return [soft_inpainting_enabled,
|
||||||
|
power,
|
||||||
|
scale,
|
||||||
|
detail,
|
||||||
|
mask_inf,
|
||||||
|
dif_thresh,
|
||||||
|
dif_contr]
|
||||||
|
|
||||||
|
def process(self, p, enabled, power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr):
|
||||||
|
if not enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not processing_uses_inpainting(p):
|
||||||
|
return
|
||||||
|
|
||||||
|
# Shut off the rounding it normally does.
|
||||||
|
p.mask_round = False
|
||||||
|
|
||||||
|
settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
|
||||||
|
|
||||||
|
# p.extra_generation_params["Mask rounding"] = False
|
||||||
|
settings.add_generation_params(p.extra_generation_params)
|
||||||
|
|
||||||
|
def on_mask_blend(self, p, mba: scripts.MaskBlendArgs, enabled, power, scale, detail_preservation, mask_inf,
|
||||||
|
dif_thresh, dif_contr):
|
||||||
|
if not enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not processing_uses_inpainting(p):
|
||||||
|
return
|
||||||
|
|
||||||
|
if mba.is_final_blend:
|
||||||
|
mba.blended_latent = mba.current_latent
|
||||||
|
return
|
||||||
|
|
||||||
|
settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
|
||||||
|
|
||||||
|
# todo: Why is sigma 2D? Both values are the same.
|
||||||
|
mba.blended_latent = latent_blend(settings,
|
||||||
|
mba.init_latent,
|
||||||
|
mba.current_latent,
|
||||||
|
get_modified_nmask(settings, mba.nmask, mba.sigma[0]))
|
||||||
|
|
||||||
|
def post_sample(self, p, ps: scripts.PostSampleArgs, enabled, power, scale, detail_preservation, mask_inf,
|
||||||
|
dif_thresh, dif_contr):
|
||||||
|
if not enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not processing_uses_inpainting(p):
|
||||||
|
return
|
||||||
|
|
||||||
|
nmask = getattr(p, "nmask", None)
|
||||||
|
if nmask is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
from modules import images
|
||||||
|
from modules.shared import opts
|
||||||
|
|
||||||
|
settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
|
||||||
|
|
||||||
|
# since the original code puts holes in the existing overlay images,
|
||||||
|
# we have to rebuild them.
|
||||||
|
self.overlay_images = []
|
||||||
|
for img in p.init_images:
|
||||||
|
|
||||||
|
image = images.flatten(img, opts.img2img_background_color)
|
||||||
|
|
||||||
|
if p.paste_to is None and p.resize_mode != 3:
|
||||||
|
image = images.resize_image(p.resize_mode, image, p.width, p.height)
|
||||||
|
|
||||||
|
self.overlay_images.append(image.convert('RGBA'))
|
||||||
|
|
||||||
|
if len(p.init_images) == 1:
|
||||||
|
self.overlay_images = self.overlay_images * p.batch_size
|
||||||
|
|
||||||
|
if getattr(ps.samples, 'already_decoded', False):
|
||||||
|
self.masks_for_overlay = apply_masks(settings=settings,
|
||||||
|
nmask=nmask,
|
||||||
|
overlay_images=self.overlay_images,
|
||||||
|
width=p.width,
|
||||||
|
height=p.height,
|
||||||
|
paste_to=p.paste_to)
|
||||||
|
else:
|
||||||
|
self.masks_for_overlay = apply_adaptive_masks(settings=settings,
|
||||||
|
nmask=nmask,
|
||||||
|
latent_orig=p.init_latent,
|
||||||
|
latent_processed=ps.samples,
|
||||||
|
overlay_images=self.overlay_images,
|
||||||
|
width=p.width,
|
||||||
|
height=p.height,
|
||||||
|
paste_to=p.paste_to)
|
||||||
|
|
||||||
|
def postprocess_maskoverlay(self, p, ppmo: scripts.PostProcessMaskOverlayArgs, enabled, power, scale,
|
||||||
|
detail_preservation, mask_inf, dif_thresh, dif_contr):
|
||||||
|
if not enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not processing_uses_inpainting(p):
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.masks_for_overlay is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.overlay_images is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
ppmo.mask_for_overlay = self.masks_for_overlay[ppmo.index]
|
||||||
|
ppmo.overlay_image = self.overlay_images[ppmo.index]
|
BIN
html/card-no-preview.png
Normal file
BIN
html/card-no-preview.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 82 KiB |
9
html/extra-networks-card.html
Normal file
9
html/extra-networks-card.html
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
<div class="card" style="{style}" onclick="{card_clicked}" data-name="{name}" {sort_keys}>
|
||||||
|
{background_image}
|
||||||
|
<div class="button-row">{copy_path_button}{metadata_button}{edit_button}</div>
|
||||||
|
<div class="actions">
|
||||||
|
<div class="additional">{search_terms}</div>
|
||||||
|
<span class="name">{name}</span>
|
||||||
|
<span class="description">{description}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
5
html/extra-networks-copy-path-button.html
Normal file
5
html/extra-networks-copy-path-button.html
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<div class="copy-path-button card-button"
|
||||||
|
title="Copy path to clipboard"
|
||||||
|
onclick="extraNetworksCopyCardPath(event)"
|
||||||
|
data-clipboard-text="{filename}">
|
||||||
|
</div>
|
4
html/extra-networks-edit-item-button.html
Normal file
4
html/extra-networks-edit-item-button.html
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
<div class="edit-button card-button"
|
||||||
|
title="Edit metadata"
|
||||||
|
onclick="extraNetworksEditUserMetadata(event, '{tabname}', '{extra_networks_tabname}')">
|
||||||
|
</div>
|
4
html/extra-networks-metadata-button.html
Normal file
4
html/extra-networks-metadata-button.html
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
<div class="metadata-button card-button"
|
||||||
|
title="Show internal metadata"
|
||||||
|
onclick="extraNetworksRequestMetadata(event, '{extra_networks_tabname}')">
|
||||||
|
</div>
|
8
html/extra-networks-no-cards.html
Normal file
8
html/extra-networks-no-cards.html
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<div class='nocards'>
|
||||||
|
<h1>Nothing here. Add some content to the following directories:</h1>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
{dirs}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
8
html/extra-networks-pane-dirs.html
Normal file
8
html/extra-networks-pane-dirs.html
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<div class="extra-network-pane-content-dirs">
|
||||||
|
<div id='{tabname}_{extra_networks_tabname}_dirs' class='extra-network-dirs'>
|
||||||
|
{dirs_html}
|
||||||
|
</div>
|
||||||
|
<div id='{tabname}_{extra_networks_tabname}_cards' class='extra-network-cards'>
|
||||||
|
{items_html}
|
||||||
|
</div>
|
||||||
|
</div>
|
8
html/extra-networks-pane-tree.html
Normal file
8
html/extra-networks-pane-tree.html
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<div class="extra-network-pane-content-tree resize-handle-row">
|
||||||
|
<div id='{tabname}_{extra_networks_tabname}_tree' class='extra-network-tree' style='flex-basis: {extra_networks_tree_view_default_width}px'>
|
||||||
|
{tree_html}
|
||||||
|
</div>
|
||||||
|
<div id='{tabname}_{extra_networks_tabname}_cards' class='extra-network-cards' style='flex-grow: 1;'>
|
||||||
|
{items_html}
|
||||||
|
</div>
|
||||||
|
</div>
|
81
html/extra-networks-pane.html
Normal file
81
html/extra-networks-pane.html
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
<div id='{tabname}_{extra_networks_tabname}_pane' class='extra-network-pane {tree_view_div_default_display_class}'>
|
||||||
|
<div class="extra-network-control" id="{tabname}_{extra_networks_tabname}_controls" style="display:none" >
|
||||||
|
<div class="extra-network-control--search">
|
||||||
|
<input
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_search"
|
||||||
|
class="extra-network-control--search-text"
|
||||||
|
type="search"
|
||||||
|
placeholder="Search"
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<small>Sort: </small>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_path"
|
||||||
|
class="extra-network-control--sort{sort_path_active}"
|
||||||
|
data-sortkey="default"
|
||||||
|
title="Sort by path"
|
||||||
|
onclick="extraNetworksControlSortOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-icon"></i>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_name"
|
||||||
|
class="extra-network-control--sort{sort_name_active}"
|
||||||
|
data-sortkey="name"
|
||||||
|
title="Sort by name"
|
||||||
|
onclick="extraNetworksControlSortOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-icon"></i>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_date_created"
|
||||||
|
class="extra-network-control--sort{sort_date_created_active}"
|
||||||
|
data-sortkey="date_created"
|
||||||
|
title="Sort by date created"
|
||||||
|
onclick="extraNetworksControlSortOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-icon"></i>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_date_modified"
|
||||||
|
class="extra-network-control--sort{sort_date_modified_active}"
|
||||||
|
data-sortkey="date_modified"
|
||||||
|
title="Sort by date modified"
|
||||||
|
onclick="extraNetworksControlSortOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-icon"></i>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<small> </small>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_sort_dir"
|
||||||
|
class="extra-network-control--sort-dir"
|
||||||
|
data-sortdir="{data_sortdir}"
|
||||||
|
title="Sort ascending"
|
||||||
|
onclick="extraNetworksControlSortDirOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--sort-dir-icon"></i>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<small> </small>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_tree_view"
|
||||||
|
class="extra-network-control--tree-view {tree_view_btn_extra_class}"
|
||||||
|
title="Enable Tree View"
|
||||||
|
onclick="extraNetworksControlTreeViewOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--tree-view-icon"></i>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="{tabname}_{extra_networks_tabname}_extra_refresh"
|
||||||
|
class="extra-network-control--refresh"
|
||||||
|
title="Refresh page"
|
||||||
|
onclick="extraNetworksControlRefreshOnClick(event, '{tabname}', '{extra_networks_tabname}');"
|
||||||
|
>
|
||||||
|
<i class="extra-network-control--icon extra-network-control--refresh-icon"></i>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{pane_content}
|
||||||
|
</div>
|
23
html/extra-networks-tree-button.html
Normal file
23
html/extra-networks-tree-button.html
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
<span data-filterable-item-text hidden>{search_terms}</span>
|
||||||
|
<div class="tree-list-content {subclass}"
|
||||||
|
type="button"
|
||||||
|
onclick="extraNetworksTreeOnClick(event, '{tabname}', '{extra_networks_tabname}');{onclick_extra}"
|
||||||
|
data-path="{data_path}"
|
||||||
|
data-hash="{data_hash}"
|
||||||
|
>
|
||||||
|
<span class='tree-list-item-action tree-list-item-action--leading'>
|
||||||
|
{action_list_item_action_leading}
|
||||||
|
</span>
|
||||||
|
<span class="tree-list-item-visual tree-list-item-visual--leading">
|
||||||
|
{action_list_item_visual_leading}
|
||||||
|
</span>
|
||||||
|
<span class="tree-list-item-label tree-list-item-label--truncate">
|
||||||
|
{action_list_item_label}
|
||||||
|
</span>
|
||||||
|
<span class="tree-list-item-visual tree-list-item-visual--trailing">
|
||||||
|
{action_list_item_visual_trailing}
|
||||||
|
</span>
|
||||||
|
<span class="tree-list-item-action tree-list-item-action--trailing">
|
||||||
|
{action_list_item_action_trailing}
|
||||||
|
</span>
|
||||||
|
</div>
|
15
html/footer.html
Normal file
15
html/footer.html
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<div>
|
||||||
|
<a href="{api_docs}">API</a>
|
||||||
|
•
|
||||||
|
<a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui">Github</a>
|
||||||
|
•
|
||||||
|
<a href="https://gradio.app">Gradio</a>
|
||||||
|
•
|
||||||
|
<a href="#" onclick="showProfile('./internal/profile-startup'); return false;">Startup profile</a>
|
||||||
|
•
|
||||||
|
<a href="/" onclick="javascript:gradioApp().getElementById('settings_restart_gradio').click(); return false">Reload UI</a>
|
||||||
|
</div>
|
||||||
|
<br />
|
||||||
|
<div class="versions">
|
||||||
|
{versions}
|
||||||
|
</div>
|
382
html/licenses.html
Normal file
382
html/licenses.html
Normal file
@ -0,0 +1,382 @@
|
|||||||
|
<style>
|
||||||
|
#licenses h2 {font-size: 1.2em; font-weight: bold; margin-bottom: 0.2em;}
|
||||||
|
#licenses small {font-size: 0.95em; opacity: 0.85;}
|
||||||
|
#licenses pre { margin: 1em 0 2em 0;}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<h2><a href="https://github.com/invoke-ai/InvokeAI/blob/main/LICENSE">InvokeAI</a></h2>
|
||||||
|
<small>Some code for compatibility with OSX is taken from lstein's repository.</small>
|
||||||
|
<pre>
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2022 InvokeAI Team
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
</pre>
|
||||||
|
|
||||||
|
<h2><a href="https://github.com/Hafiidz/latent-diffusion/blob/main/LICENSE">LDSR</a></h2>
|
||||||
|
<small>Code added by contirubtors, most likely copied from this repository.</small>
|
||||||
|
<pre>
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2022 Machine Vision and Learning Group, LMU Munich
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
</pre>
|
||||||
|
|
||||||
|
<h2><a href="https://github.com/pharmapsychotic/clip-interrogator/blob/main/LICENSE">CLIP Interrogator</a></h2>
|
||||||
|
<small>Some small amounts of code borrowed and reworked.</small>
|
||||||
|
<pre>
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2022 pharmapsychotic
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
</pre>
|
||||||
|
|
||||||
|
<h2><a href="https://github.com/AminRezaei0x443/memory-efficient-attention/blob/main/LICENSE">Memory Efficient Attention</a></h2>
|
||||||
|
<small>The sub-quadratic cross attention optimization uses modified code from the Memory Efficient Attention package that Alex Birch optimized for 3D tensors. This license is updated to reflect that.</small>
|
||||||
|
<pre>
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2023 Alex Birch
|
||||||
|
Copyright (c) 2023 Amin Rezaei
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
</pre>
|
||||||
|
|
||||||
|
<h2><a href="https://github.com/huggingface/diffusers/blob/c7da8fd23359a22d0df2741688b5b4f33c26df21/LICENSE">Scaled Dot Product Attention</a></h2>
|
||||||
|
<small>Some small amounts of code borrowed and reworked.</small>
|
||||||
|
<pre>
|
||||||
|
Copyright 2023 The HuggingFace Team. All rights reserved.
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
</pre>
|
||||||
|
|
||||||
|
<h2><a href="https://github.com/explosion/curated-transformers/blob/main/LICENSE">Curated transformers</a></h2>
|
||||||
|
<small>The MPS workaround for nn.Linear on macOS 13.2.X is based on the MPS workaround for nn.Linear created by danieldk for Curated transformers</small>
|
||||||
|
<pre>
|
||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (C) 2021 ExplosionAI GmbH
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
</pre>
|
||||||
|
|
||||||
|
<h2><a href="https://github.com/madebyollin/taesd/blob/main/LICENSE">TAESD</a></h2>
|
||||||
|
<small>Tiny AutoEncoder for Stable Diffusion option for live previews</small>
|
||||||
|
<pre>
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2023 Ollin Boer Bohan
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
</pre>
|
113
javascript/aspectRatioOverlay.js
Normal file
113
javascript/aspectRatioOverlay.js
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
|
||||||
|
let currentWidth = null;
|
||||||
|
let currentHeight = null;
|
||||||
|
let arFrameTimeout = setTimeout(function() {}, 0);
|
||||||
|
|
||||||
|
function dimensionChange(e, is_width, is_height) {
|
||||||
|
|
||||||
|
if (is_width) {
|
||||||
|
currentWidth = e.target.value * 1.0;
|
||||||
|
}
|
||||||
|
if (is_height) {
|
||||||
|
currentHeight = e.target.value * 1.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var inImg2img = gradioApp().querySelector("#tab_img2img").style.display == "block";
|
||||||
|
|
||||||
|
if (!inImg2img) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var targetElement = null;
|
||||||
|
|
||||||
|
var tabIndex = get_tab_index('mode_img2img');
|
||||||
|
if (tabIndex == 0) { // img2img
|
||||||
|
targetElement = gradioApp().querySelector('#img2img_image div[data-testid=image] img');
|
||||||
|
} else if (tabIndex == 1) { //Sketch
|
||||||
|
targetElement = gradioApp().querySelector('#img2img_sketch div[data-testid=image] img');
|
||||||
|
} else if (tabIndex == 2) { // Inpaint
|
||||||
|
targetElement = gradioApp().querySelector('#img2maskimg div[data-testid=image] img');
|
||||||
|
} else if (tabIndex == 3) { // Inpaint sketch
|
||||||
|
targetElement = gradioApp().querySelector('#inpaint_sketch div[data-testid=image] img');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (targetElement) {
|
||||||
|
|
||||||
|
var arPreviewRect = gradioApp().querySelector('#imageARPreview');
|
||||||
|
if (!arPreviewRect) {
|
||||||
|
arPreviewRect = document.createElement('div');
|
||||||
|
arPreviewRect.id = "imageARPreview";
|
||||||
|
gradioApp().appendChild(arPreviewRect);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var viewportOffset = targetElement.getBoundingClientRect();
|
||||||
|
|
||||||
|
var viewportscale = Math.min(targetElement.clientWidth / targetElement.naturalWidth, targetElement.clientHeight / targetElement.naturalHeight);
|
||||||
|
|
||||||
|
var scaledx = targetElement.naturalWidth * viewportscale;
|
||||||
|
var scaledy = targetElement.naturalHeight * viewportscale;
|
||||||
|
|
||||||
|
var clientRectTop = (viewportOffset.top + window.scrollY);
|
||||||
|
var clientRectLeft = (viewportOffset.left + window.scrollX);
|
||||||
|
var clientRectCentreY = clientRectTop + (targetElement.clientHeight / 2);
|
||||||
|
var clientRectCentreX = clientRectLeft + (targetElement.clientWidth / 2);
|
||||||
|
|
||||||
|
var arscale = Math.min(scaledx / currentWidth, scaledy / currentHeight);
|
||||||
|
var arscaledx = currentWidth * arscale;
|
||||||
|
var arscaledy = currentHeight * arscale;
|
||||||
|
|
||||||
|
var arRectTop = clientRectCentreY - (arscaledy / 2);
|
||||||
|
var arRectLeft = clientRectCentreX - (arscaledx / 2);
|
||||||
|
var arRectWidth = arscaledx;
|
||||||
|
var arRectHeight = arscaledy;
|
||||||
|
|
||||||
|
arPreviewRect.style.top = arRectTop + 'px';
|
||||||
|
arPreviewRect.style.left = arRectLeft + 'px';
|
||||||
|
arPreviewRect.style.width = arRectWidth + 'px';
|
||||||
|
arPreviewRect.style.height = arRectHeight + 'px';
|
||||||
|
|
||||||
|
clearTimeout(arFrameTimeout);
|
||||||
|
arFrameTimeout = setTimeout(function() {
|
||||||
|
arPreviewRect.style.display = 'none';
|
||||||
|
}, 2000);
|
||||||
|
|
||||||
|
arPreviewRect.style.display = 'block';
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
onAfterUiUpdate(function() {
|
||||||
|
var arPreviewRect = gradioApp().querySelector('#imageARPreview');
|
||||||
|
if (arPreviewRect) {
|
||||||
|
arPreviewRect.style.display = 'none';
|
||||||
|
}
|
||||||
|
var tabImg2img = gradioApp().querySelector("#tab_img2img");
|
||||||
|
if (tabImg2img) {
|
||||||
|
var inImg2img = tabImg2img.style.display == "block";
|
||||||
|
if (inImg2img) {
|
||||||
|
let inputs = gradioApp().querySelectorAll('input');
|
||||||
|
inputs.forEach(function(e) {
|
||||||
|
var is_width = e.parentElement.id == "img2img_width";
|
||||||
|
var is_height = e.parentElement.id == "img2img_height";
|
||||||
|
|
||||||
|
if ((is_width || is_height) && !e.classList.contains('scrollwatch')) {
|
||||||
|
e.addEventListener('input', function(e) {
|
||||||
|
dimensionChange(e, is_width, is_height);
|
||||||
|
});
|
||||||
|
e.classList.add('scrollwatch');
|
||||||
|
}
|
||||||
|
if (is_width) {
|
||||||
|
currentWidth = e.value * 1.0;
|
||||||
|
}
|
||||||
|
if (is_height) {
|
||||||
|
currentHeight = e.value * 1.0;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
163
javascript/contextMenus.js
Normal file
163
javascript/contextMenus.js
Normal file
@ -0,0 +1,163 @@
|
|||||||
|
|
||||||
|
var contextMenuInit = function() {
|
||||||
|
let eventListenerApplied = false;
|
||||||
|
let menuSpecs = new Map();
|
||||||
|
|
||||||
|
const uid = function() {
|
||||||
|
return Date.now().toString(36) + Math.random().toString(36).substring(2);
|
||||||
|
};
|
||||||
|
|
||||||
|
function showContextMenu(event, element, menuEntries) {
|
||||||
|
let oldMenu = gradioApp().querySelector('#context-menu');
|
||||||
|
if (oldMenu) {
|
||||||
|
oldMenu.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
let baseStyle = window.getComputedStyle(uiCurrentTab);
|
||||||
|
|
||||||
|
const contextMenu = document.createElement('nav');
|
||||||
|
contextMenu.id = "context-menu";
|
||||||
|
contextMenu.style.background = baseStyle.background;
|
||||||
|
contextMenu.style.color = baseStyle.color;
|
||||||
|
contextMenu.style.fontFamily = baseStyle.fontFamily;
|
||||||
|
contextMenu.style.top = event.pageY + 'px';
|
||||||
|
contextMenu.style.left = event.pageX + 'px';
|
||||||
|
|
||||||
|
const contextMenuList = document.createElement('ul');
|
||||||
|
contextMenuList.className = 'context-menu-items';
|
||||||
|
contextMenu.append(contextMenuList);
|
||||||
|
|
||||||
|
menuEntries.forEach(function(entry) {
|
||||||
|
let contextMenuEntry = document.createElement('a');
|
||||||
|
contextMenuEntry.innerHTML = entry['name'];
|
||||||
|
contextMenuEntry.addEventListener("click", function() {
|
||||||
|
entry['func']();
|
||||||
|
});
|
||||||
|
contextMenuList.append(contextMenuEntry);
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
gradioApp().appendChild(contextMenu);
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendContextMenuOption(targetElementSelector, entryName, entryFunction) {
|
||||||
|
|
||||||
|
var currentItems = menuSpecs.get(targetElementSelector);
|
||||||
|
|
||||||
|
if (!currentItems) {
|
||||||
|
currentItems = [];
|
||||||
|
menuSpecs.set(targetElementSelector, currentItems);
|
||||||
|
}
|
||||||
|
let newItem = {
|
||||||
|
id: targetElementSelector + '_' + uid(),
|
||||||
|
name: entryName,
|
||||||
|
func: entryFunction,
|
||||||
|
isNew: true
|
||||||
|
};
|
||||||
|
|
||||||
|
currentItems.push(newItem);
|
||||||
|
return newItem['id'];
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeContextMenuOption(uid) {
|
||||||
|
menuSpecs.forEach(function(v) {
|
||||||
|
let index = -1;
|
||||||
|
v.forEach(function(e, ei) {
|
||||||
|
if (e['id'] == uid) {
|
||||||
|
index = ei;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (index >= 0) {
|
||||||
|
v.splice(index, 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function addContextMenuEventListener() {
|
||||||
|
if (eventListenerApplied) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
gradioApp().addEventListener("click", function(e) {
|
||||||
|
if (!e.isTrusted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let oldMenu = gradioApp().querySelector('#context-menu');
|
||||||
|
if (oldMenu) {
|
||||||
|
oldMenu.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
['contextmenu', 'touchstart'].forEach((eventType) => {
|
||||||
|
gradioApp().addEventListener(eventType, function(e) {
|
||||||
|
let ev = e;
|
||||||
|
if (eventType.startsWith('touch')) {
|
||||||
|
if (e.touches.length !== 2) return;
|
||||||
|
ev = e.touches[0];
|
||||||
|
}
|
||||||
|
let oldMenu = gradioApp().querySelector('#context-menu');
|
||||||
|
if (oldMenu) {
|
||||||
|
oldMenu.remove();
|
||||||
|
}
|
||||||
|
menuSpecs.forEach(function(v, k) {
|
||||||
|
if (e.composedPath()[0].matches(k)) {
|
||||||
|
showContextMenu(ev, e.composedPath()[0], v);
|
||||||
|
e.preventDefault();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
eventListenerApplied = true;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return [appendContextMenuOption, removeContextMenuOption, addContextMenuEventListener];
|
||||||
|
};
|
||||||
|
|
||||||
|
var initResponse = contextMenuInit();
|
||||||
|
var appendContextMenuOption = initResponse[0];
|
||||||
|
var removeContextMenuOption = initResponse[1];
|
||||||
|
var addContextMenuEventListener = initResponse[2];
|
||||||
|
|
||||||
|
(function() {
|
||||||
|
//Start example Context Menu Items
|
||||||
|
let generateOnRepeat = function(genbuttonid, interruptbuttonid) {
|
||||||
|
let genbutton = gradioApp().querySelector(genbuttonid);
|
||||||
|
let interruptbutton = gradioApp().querySelector(interruptbuttonid);
|
||||||
|
if (!interruptbutton.offsetParent) {
|
||||||
|
genbutton.click();
|
||||||
|
}
|
||||||
|
clearInterval(window.generateOnRepeatInterval);
|
||||||
|
window.generateOnRepeatInterval = setInterval(function() {
|
||||||
|
if (!interruptbutton.offsetParent) {
|
||||||
|
genbutton.click();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
500);
|
||||||
|
};
|
||||||
|
|
||||||
|
let generateOnRepeat_txt2img = function() {
|
||||||
|
generateOnRepeat('#txt2img_generate', '#txt2img_interrupt');
|
||||||
|
};
|
||||||
|
|
||||||
|
let generateOnRepeat_img2img = function() {
|
||||||
|
generateOnRepeat('#img2img_generate', '#img2img_interrupt');
|
||||||
|
};
|
||||||
|
|
||||||
|
appendContextMenuOption('#txt2img_generate', 'Generate forever', generateOnRepeat_txt2img);
|
||||||
|
appendContextMenuOption('#txt2img_interrupt', 'Generate forever', generateOnRepeat_txt2img);
|
||||||
|
appendContextMenuOption('#img2img_generate', 'Generate forever', generateOnRepeat_img2img);
|
||||||
|
appendContextMenuOption('#img2img_interrupt', 'Generate forever', generateOnRepeat_img2img);
|
||||||
|
|
||||||
|
let cancelGenerateForever = function() {
|
||||||
|
clearInterval(window.generateOnRepeatInterval);
|
||||||
|
};
|
||||||
|
|
||||||
|
appendContextMenuOption('#txt2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
|
||||||
|
appendContextMenuOption('#txt2img_generate', 'Cancel generate forever', cancelGenerateForever);
|
||||||
|
appendContextMenuOption('#img2img_interrupt', 'Cancel generate forever', cancelGenerateForever);
|
||||||
|
appendContextMenuOption('#img2img_generate', 'Cancel generate forever', cancelGenerateForever);
|
||||||
|
|
||||||
|
})();
|
||||||
|
//End example Context Menu Items
|
||||||
|
|
||||||
|
onAfterUiUpdate(addContextMenuEventListener);
|
156
javascript/dragdrop.js
vendored
Normal file
156
javascript/dragdrop.js
vendored
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
// allows drag-dropping files into gradio image elements, and also pasting images from clipboard
|
||||||
|
|
||||||
|
function isValidImageList(files) {
|
||||||
|
return files && files?.length === 1 && ['image/png', 'image/gif', 'image/jpeg'].includes(files[0].type);
|
||||||
|
}
|
||||||
|
|
||||||
|
function dropReplaceImage(imgWrap, files) {
|
||||||
|
if (!isValidImageList(files)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tmpFile = files[0];
|
||||||
|
|
||||||
|
imgWrap.querySelector('.modify-upload button + button, .touch-none + div button + button')?.click();
|
||||||
|
const callback = () => {
|
||||||
|
const fileInput = imgWrap.querySelector('input[type="file"]');
|
||||||
|
if (fileInput) {
|
||||||
|
if (files.length === 0) {
|
||||||
|
files = new DataTransfer();
|
||||||
|
files.items.add(tmpFile);
|
||||||
|
fileInput.files = files.files;
|
||||||
|
} else {
|
||||||
|
fileInput.files = files;
|
||||||
|
}
|
||||||
|
fileInput.dispatchEvent(new Event('change'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (imgWrap.closest('#pnginfo_image')) {
|
||||||
|
// special treatment for PNG Info tab, wait for fetch request to finish
|
||||||
|
const oldFetch = window.fetch;
|
||||||
|
window.fetch = async(input, options) => {
|
||||||
|
const response = await oldFetch(input, options);
|
||||||
|
if ('api/predict/' === input) {
|
||||||
|
const content = await response.text();
|
||||||
|
window.fetch = oldFetch;
|
||||||
|
window.requestAnimationFrame(() => callback());
|
||||||
|
return new Response(content, {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
headers: response.headers
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
window.requestAnimationFrame(() => callback());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function eventHasFiles(e) {
|
||||||
|
if (!e.dataTransfer || !e.dataTransfer.files) return false;
|
||||||
|
if (e.dataTransfer.files.length > 0) return true;
|
||||||
|
if (e.dataTransfer.items.length > 0 && e.dataTransfer.items[0].kind == "file") return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isURL(url) {
|
||||||
|
try {
|
||||||
|
const _ = new URL(url);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dragDropTargetIsPrompt(target) {
|
||||||
|
if (target?.placeholder && target?.placeholder.indexOf("Prompt") >= 0) return true;
|
||||||
|
if (target?.parentNode?.parentNode?.className?.indexOf("prompt") > 0) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.document.addEventListener('dragover', e => {
|
||||||
|
const target = e.composedPath()[0];
|
||||||
|
if (!eventHasFiles(e)) return;
|
||||||
|
|
||||||
|
var targetImage = target.closest('[data-testid="image"]');
|
||||||
|
if (!dragDropTargetIsPrompt(target) && !targetImage) return;
|
||||||
|
|
||||||
|
e.stopPropagation();
|
||||||
|
e.preventDefault();
|
||||||
|
e.dataTransfer.dropEffect = 'copy';
|
||||||
|
});
|
||||||
|
|
||||||
|
window.document.addEventListener('drop', async e => {
|
||||||
|
const target = e.composedPath()[0];
|
||||||
|
const url = e.dataTransfer.getData('text/uri-list') || e.dataTransfer.getData('text/plain');
|
||||||
|
if (!eventHasFiles(e) && !isURL(url)) return;
|
||||||
|
|
||||||
|
if (dragDropTargetIsPrompt(target)) {
|
||||||
|
e.stopPropagation();
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const isImg2img = get_tab_index('tabs') == 1;
|
||||||
|
let prompt_image_target = isImg2img ? "img2img_prompt_image" : "txt2img_prompt_image";
|
||||||
|
|
||||||
|
const imgParent = gradioApp().getElementById(prompt_image_target);
|
||||||
|
const files = e.dataTransfer.files;
|
||||||
|
const fileInput = imgParent.querySelector('input[type="file"]');
|
||||||
|
if (eventHasFiles(e) && fileInput) {
|
||||||
|
fileInput.files = files;
|
||||||
|
fileInput.dispatchEvent(new Event('change'));
|
||||||
|
} else if (url) {
|
||||||
|
try {
|
||||||
|
const request = await fetch(url);
|
||||||
|
if (!request.ok) {
|
||||||
|
console.error('Error fetching URL:', url, request.status);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = new DataTransfer();
|
||||||
|
data.items.add(new File([await request.blob()], 'image.png'));
|
||||||
|
fileInput.files = data.files;
|
||||||
|
fileInput.dispatchEvent(new Event('change'));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching URL:', url, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var targetImage = target.closest('[data-testid="image"]');
|
||||||
|
if (targetImage) {
|
||||||
|
e.stopPropagation();
|
||||||
|
e.preventDefault();
|
||||||
|
const files = e.dataTransfer.files;
|
||||||
|
dropReplaceImage(targetImage, files);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('paste', e => {
|
||||||
|
const files = e.clipboardData.files;
|
||||||
|
if (!isValidImageList(files)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const visibleImageFields = [...gradioApp().querySelectorAll('[data-testid="image"]')]
|
||||||
|
.filter(el => uiElementIsVisible(el))
|
||||||
|
.sort((a, b) => uiElementInSight(b) - uiElementInSight(a));
|
||||||
|
|
||||||
|
|
||||||
|
if (!visibleImageFields.length) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const firstFreeImageField = visibleImageFields
|
||||||
|
.filter(el => !el.querySelector('img'))?.[0];
|
||||||
|
|
||||||
|
dropReplaceImage(
|
||||||
|
firstFreeImageField ?
|
||||||
|
firstFreeImageField :
|
||||||
|
visibleImageFields[visibleImageFields.length - 1]
|
||||||
|
, files
|
||||||
|
);
|
||||||
|
});
|
156
javascript/edit-attention.js
Normal file
156
javascript/edit-attention.js
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
function keyupEditAttention(event) {
|
||||||
|
let target = event.originalTarget || event.composedPath()[0];
|
||||||
|
if (!target.matches("*:is([id*='_toprow'] [id*='_prompt'], .prompt) textarea")) return;
|
||||||
|
if (!(event.metaKey || event.ctrlKey)) return;
|
||||||
|
|
||||||
|
let isPlus = event.key == "ArrowUp";
|
||||||
|
let isMinus = event.key == "ArrowDown";
|
||||||
|
if (!isPlus && !isMinus) return;
|
||||||
|
|
||||||
|
let selectionStart = target.selectionStart;
|
||||||
|
let selectionEnd = target.selectionEnd;
|
||||||
|
let text = target.value;
|
||||||
|
|
||||||
|
function selectCurrentParenthesisBlock(OPEN, CLOSE) {
|
||||||
|
if (selectionStart !== selectionEnd) return false;
|
||||||
|
|
||||||
|
// Find opening parenthesis around current cursor
|
||||||
|
const before = text.substring(0, selectionStart);
|
||||||
|
let beforeParen = before.lastIndexOf(OPEN);
|
||||||
|
if (beforeParen == -1) return false;
|
||||||
|
|
||||||
|
let beforeClosingParen = before.lastIndexOf(CLOSE);
|
||||||
|
if (beforeClosingParen != -1 && beforeClosingParen > beforeParen) return false;
|
||||||
|
|
||||||
|
// Find closing parenthesis around current cursor
|
||||||
|
const after = text.substring(selectionStart);
|
||||||
|
let afterParen = after.indexOf(CLOSE);
|
||||||
|
if (afterParen == -1) return false;
|
||||||
|
|
||||||
|
let afterOpeningParen = after.indexOf(OPEN);
|
||||||
|
if (afterOpeningParen != -1 && afterOpeningParen < afterParen) return false;
|
||||||
|
|
||||||
|
// Set the selection to the text between the parenthesis
|
||||||
|
const parenContent = text.substring(beforeParen + 1, selectionStart + afterParen);
|
||||||
|
if (/.*:-?[\d.]+/s.test(parenContent)) {
|
||||||
|
const lastColon = parenContent.lastIndexOf(":");
|
||||||
|
selectionStart = beforeParen + 1;
|
||||||
|
selectionEnd = selectionStart + lastColon;
|
||||||
|
} else {
|
||||||
|
selectionStart = beforeParen + 1;
|
||||||
|
selectionEnd = selectionStart + parenContent.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
target.setSelectionRange(selectionStart, selectionEnd);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectCurrentWord() {
|
||||||
|
if (selectionStart !== selectionEnd) return false;
|
||||||
|
const whitespace_delimiters = {"Tab": "\t", "Carriage Return": "\r", "Line Feed": "\n"};
|
||||||
|
let delimiters = opts.keyedit_delimiters;
|
||||||
|
|
||||||
|
for (let i of opts.keyedit_delimiters_whitespace) {
|
||||||
|
delimiters += whitespace_delimiters[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
// seek backward to find beginning
|
||||||
|
while (!delimiters.includes(text[selectionStart - 1]) && selectionStart > 0) {
|
||||||
|
selectionStart--;
|
||||||
|
}
|
||||||
|
|
||||||
|
// seek forward to find end
|
||||||
|
while (!delimiters.includes(text[selectionEnd]) && selectionEnd < text.length) {
|
||||||
|
selectionEnd++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// deselect surrounding whitespace
|
||||||
|
while (text[selectionStart] == " " && selectionStart < selectionEnd) {
|
||||||
|
selectionStart++;
|
||||||
|
}
|
||||||
|
while (text[selectionEnd - 1] == " " && selectionEnd > selectionStart) {
|
||||||
|
selectionEnd--;
|
||||||
|
}
|
||||||
|
|
||||||
|
target.setSelectionRange(selectionStart, selectionEnd);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the user hasn't selected anything, let's select their current parenthesis block or word
|
||||||
|
if (!selectCurrentParenthesisBlock('<', '>') && !selectCurrentParenthesisBlock('(', ')') && !selectCurrentParenthesisBlock('[', ']')) {
|
||||||
|
selectCurrentWord();
|
||||||
|
}
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
var closeCharacter = ')';
|
||||||
|
var delta = opts.keyedit_precision_attention;
|
||||||
|
var start = selectionStart > 0 ? text[selectionStart - 1] : "";
|
||||||
|
var end = text[selectionEnd];
|
||||||
|
|
||||||
|
if (start == '<') {
|
||||||
|
closeCharacter = '>';
|
||||||
|
delta = opts.keyedit_precision_extra;
|
||||||
|
} else if (start == '(' && end == ')' || start == '[' && end == ']') { // convert old-style (((emphasis)))
|
||||||
|
let numParen = 0;
|
||||||
|
|
||||||
|
while (text[selectionStart - numParen - 1] == start && text[selectionEnd + numParen] == end) {
|
||||||
|
numParen++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start == "[") {
|
||||||
|
weight = (1 / 1.1) ** numParen;
|
||||||
|
} else {
|
||||||
|
weight = 1.1 ** numParen;
|
||||||
|
}
|
||||||
|
|
||||||
|
weight = Math.round(weight / opts.keyedit_precision_attention) * opts.keyedit_precision_attention;
|
||||||
|
|
||||||
|
text = text.slice(0, selectionStart - numParen) + "(" + text.slice(selectionStart, selectionEnd) + ":" + weight + ")" + text.slice(selectionEnd + numParen);
|
||||||
|
selectionStart -= numParen - 1;
|
||||||
|
selectionEnd -= numParen - 1;
|
||||||
|
} else if (start != '(') {
|
||||||
|
// do not include spaces at the end
|
||||||
|
while (selectionEnd > selectionStart && text[selectionEnd - 1] == ' ') {
|
||||||
|
selectionEnd--;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (selectionStart == selectionEnd) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
text = text.slice(0, selectionStart) + "(" + text.slice(selectionStart, selectionEnd) + ":1.0)" + text.slice(selectionEnd);
|
||||||
|
|
||||||
|
selectionStart++;
|
||||||
|
selectionEnd++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (text[selectionEnd] != ':') return;
|
||||||
|
var weightLength = text.slice(selectionEnd + 1).indexOf(closeCharacter) + 1;
|
||||||
|
var weight = parseFloat(text.slice(selectionEnd + 1, selectionEnd + weightLength));
|
||||||
|
if (isNaN(weight)) return;
|
||||||
|
|
||||||
|
weight += isPlus ? delta : -delta;
|
||||||
|
weight = parseFloat(weight.toPrecision(12));
|
||||||
|
if (Number.isInteger(weight)) weight += ".0";
|
||||||
|
|
||||||
|
if (closeCharacter == ')' && weight == 1) {
|
||||||
|
var endParenPos = text.substring(selectionEnd).indexOf(')');
|
||||||
|
text = text.slice(0, selectionStart - 1) + text.slice(selectionStart, selectionEnd) + text.slice(selectionEnd + endParenPos + 1);
|
||||||
|
selectionStart--;
|
||||||
|
selectionEnd--;
|
||||||
|
} else {
|
||||||
|
text = text.slice(0, selectionEnd + 1) + weight + text.slice(selectionEnd + weightLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
target.focus();
|
||||||
|
target.value = text;
|
||||||
|
target.selectionStart = selectionStart;
|
||||||
|
target.selectionEnd = selectionEnd;
|
||||||
|
|
||||||
|
updateInput(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
addEventListener('keydown', (event) => {
|
||||||
|
keyupEditAttention(event);
|
||||||
|
});
|
41
javascript/edit-order.js
Normal file
41
javascript/edit-order.js
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
/* alt+left/right moves text in prompt */
|
||||||
|
|
||||||
|
function keyupEditOrder(event) {
|
||||||
|
if (!opts.keyedit_move) return;
|
||||||
|
|
||||||
|
let target = event.originalTarget || event.composedPath()[0];
|
||||||
|
if (!target.matches("*:is([id*='_toprow'] [id*='_prompt'], .prompt) textarea")) return;
|
||||||
|
if (!event.altKey) return;
|
||||||
|
|
||||||
|
let isLeft = event.key == "ArrowLeft";
|
||||||
|
let isRight = event.key == "ArrowRight";
|
||||||
|
if (!isLeft && !isRight) return;
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
let selectionStart = target.selectionStart;
|
||||||
|
let selectionEnd = target.selectionEnd;
|
||||||
|
let text = target.value;
|
||||||
|
let items = text.split(",");
|
||||||
|
let indexStart = (text.slice(0, selectionStart).match(/,/g) || []).length;
|
||||||
|
let indexEnd = (text.slice(0, selectionEnd).match(/,/g) || []).length;
|
||||||
|
let range = indexEnd - indexStart + 1;
|
||||||
|
|
||||||
|
if (isLeft && indexStart > 0) {
|
||||||
|
items.splice(indexStart - 1, 0, ...items.splice(indexStart, range));
|
||||||
|
target.value = items.join();
|
||||||
|
target.selectionStart = items.slice(0, indexStart - 1).join().length + (indexStart == 1 ? 0 : 1);
|
||||||
|
target.selectionEnd = items.slice(0, indexEnd).join().length;
|
||||||
|
} else if (isRight && indexEnd < items.length - 1) {
|
||||||
|
items.splice(indexStart + 1, 0, ...items.splice(indexStart, range));
|
||||||
|
target.value = items.join();
|
||||||
|
target.selectionStart = items.slice(0, indexStart + 1).join().length + 1;
|
||||||
|
target.selectionEnd = items.slice(0, indexEnd + 2).join().length;
|
||||||
|
}
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
updateInput(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
addEventListener('keydown', (event) => {
|
||||||
|
keyupEditOrder(event);
|
||||||
|
});
|
95
javascript/extensions.js
Normal file
95
javascript/extensions.js
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
|
||||||
|
function extensions_apply(_disabled_list, _update_list, disable_all) {
|
||||||
|
var disable = [];
|
||||||
|
var update = [];
|
||||||
|
const extensions_input = gradioApp().querySelectorAll('#extensions input[type="checkbox"]');
|
||||||
|
if (extensions_input.length == 0) {
|
||||||
|
throw Error("Extensions page not yet loaded.");
|
||||||
|
}
|
||||||
|
extensions_input.forEach(function(x) {
|
||||||
|
if (x.name.startsWith("enable_") && !x.checked) {
|
||||||
|
disable.push(x.name.substring(7));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (x.name.startsWith("update_") && x.checked) {
|
||||||
|
update.push(x.name.substring(7));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
restart_reload();
|
||||||
|
|
||||||
|
return [JSON.stringify(disable), JSON.stringify(update), disable_all];
|
||||||
|
}
|
||||||
|
|
||||||
|
function extensions_check() {
|
||||||
|
var disable = [];
|
||||||
|
|
||||||
|
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x) {
|
||||||
|
if (x.name.startsWith("enable_") && !x.checked) {
|
||||||
|
disable.push(x.name.substring(7));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x) {
|
||||||
|
x.innerHTML = "Loading...";
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
var id = randomId();
|
||||||
|
requestProgress(id, gradioApp().getElementById('extensions_installed_html'), null, function() {
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
return [id, JSON.stringify(disable)];
|
||||||
|
}
|
||||||
|
|
||||||
|
function install_extension_from_index(button, url) {
|
||||||
|
button.disabled = "disabled";
|
||||||
|
button.value = "Installing...";
|
||||||
|
|
||||||
|
var textarea = gradioApp().querySelector('#extension_to_install textarea');
|
||||||
|
textarea.value = url;
|
||||||
|
updateInput(textarea);
|
||||||
|
|
||||||
|
gradioApp().querySelector('#install_extension_button').click();
|
||||||
|
}
|
||||||
|
|
||||||
|
function config_state_confirm_restore(_, config_state_name, config_restore_type) {
|
||||||
|
if (config_state_name == "Current") {
|
||||||
|
return [false, config_state_name, config_restore_type];
|
||||||
|
}
|
||||||
|
let restored = "";
|
||||||
|
if (config_restore_type == "extensions") {
|
||||||
|
restored = "all saved extension versions";
|
||||||
|
} else if (config_restore_type == "webui") {
|
||||||
|
restored = "the webui version";
|
||||||
|
} else {
|
||||||
|
restored = "the webui version and all saved extension versions";
|
||||||
|
}
|
||||||
|
let confirmed = confirm("Are you sure you want to restore from this state?\nThis will reset " + restored + ".");
|
||||||
|
if (confirmed) {
|
||||||
|
restart_reload();
|
||||||
|
gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x) {
|
||||||
|
x.innerHTML = "Loading...";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return [confirmed, config_state_name, config_restore_type];
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle_all_extensions(event) {
|
||||||
|
gradioApp().querySelectorAll('#extensions .extension_toggle').forEach(function(checkbox_el) {
|
||||||
|
checkbox_el.checked = event.target.checked;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle_extension() {
|
||||||
|
let all_extensions_toggled = true;
|
||||||
|
for (const checkbox_el of gradioApp().querySelectorAll('#extensions .extension_toggle')) {
|
||||||
|
if (!checkbox_el.checked) {
|
||||||
|
all_extensions_toggled = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
gradioApp().querySelector('#extensions .all_extensions_toggle').checked = all_extensions_toggled;
|
||||||
|
}
|
712
javascript/extraNetworks.js
Normal file
712
javascript/extraNetworks.js
Normal file
@ -0,0 +1,712 @@
|
|||||||
|
function toggleCss(key, css, enable) {
|
||||||
|
var style = document.getElementById(key);
|
||||||
|
if (enable && !style) {
|
||||||
|
style = document.createElement('style');
|
||||||
|
style.id = key;
|
||||||
|
style.type = 'text/css';
|
||||||
|
document.head.appendChild(style);
|
||||||
|
}
|
||||||
|
if (style && !enable) {
|
||||||
|
document.head.removeChild(style);
|
||||||
|
}
|
||||||
|
if (style) {
|
||||||
|
style.innerHTML == '';
|
||||||
|
style.appendChild(document.createTextNode(css));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupExtraNetworksForTab(tabname) {
|
||||||
|
function registerPrompt(tabname, id) {
|
||||||
|
var textarea = gradioApp().querySelector("#" + id + " > label > textarea");
|
||||||
|
|
||||||
|
if (!activePromptTextarea[tabname]) {
|
||||||
|
activePromptTextarea[tabname] = textarea;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea.addEventListener("focus", function() {
|
||||||
|
activePromptTextarea[tabname] = textarea;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var tabnav = gradioApp().querySelector('#' + tabname + '_extra_tabs > div.tab-nav');
|
||||||
|
var controlsDiv = document.createElement('DIV');
|
||||||
|
controlsDiv.classList.add('extra-networks-controls-div');
|
||||||
|
tabnav.appendChild(controlsDiv);
|
||||||
|
tabnav.insertBefore(controlsDiv, null);
|
||||||
|
|
||||||
|
var this_tab = gradioApp().querySelector('#' + tabname + '_extra_tabs');
|
||||||
|
this_tab.querySelectorAll(":scope > [id^='" + tabname + "_']").forEach(function(elem) {
|
||||||
|
// tabname_full = {tabname}_{extra_networks_tabname}
|
||||||
|
var tabname_full = elem.id;
|
||||||
|
var search = gradioApp().querySelector("#" + tabname_full + "_extra_search");
|
||||||
|
var sort_dir = gradioApp().querySelector("#" + tabname_full + "_extra_sort_dir");
|
||||||
|
var refresh = gradioApp().querySelector("#" + tabname_full + "_extra_refresh");
|
||||||
|
var currentSort = '';
|
||||||
|
|
||||||
|
// If any of the buttons above don't exist, we want to skip this iteration of the loop.
|
||||||
|
if (!search || !sort_dir || !refresh) {
|
||||||
|
return; // `return` is equivalent of `continue` but for forEach loops.
|
||||||
|
}
|
||||||
|
|
||||||
|
var applyFilter = function(force) {
|
||||||
|
var searchTerm = search.value.toLowerCase();
|
||||||
|
gradioApp().querySelectorAll('#' + tabname + '_extra_tabs div.card').forEach(function(elem) {
|
||||||
|
var searchOnly = elem.querySelector('.search_only');
|
||||||
|
var text = Array.prototype.map.call(elem.querySelectorAll('.search_terms, .description'), function(t) {
|
||||||
|
return t.textContent.toLowerCase();
|
||||||
|
}).join(" ");
|
||||||
|
|
||||||
|
var visible = text.indexOf(searchTerm) != -1;
|
||||||
|
if (searchOnly && searchTerm.length < 4) {
|
||||||
|
visible = false;
|
||||||
|
}
|
||||||
|
if (visible) {
|
||||||
|
elem.classList.remove("hidden");
|
||||||
|
} else {
|
||||||
|
elem.classList.add("hidden");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
applySort(force);
|
||||||
|
};
|
||||||
|
|
||||||
|
var applySort = function(force) {
|
||||||
|
var cards = gradioApp().querySelectorAll('#' + tabname_full + ' div.card');
|
||||||
|
var parent = gradioApp().querySelector('#' + tabname_full + "_cards");
|
||||||
|
var reverse = sort_dir.dataset.sortdir == "Descending";
|
||||||
|
var activeSearchElem = gradioApp().querySelector('#' + tabname_full + "_controls .extra-network-control--sort.extra-network-control--enabled");
|
||||||
|
var sortKey = activeSearchElem ? activeSearchElem.dataset.sortkey : "default";
|
||||||
|
var sortKeyDataField = "sort" + sortKey.charAt(0).toUpperCase() + sortKey.slice(1);
|
||||||
|
var sortKeyStore = sortKey + "-" + sort_dir.dataset.sortdir + "-" + cards.length;
|
||||||
|
|
||||||
|
if (sortKeyStore == currentSort && !force) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
currentSort = sortKeyStore;
|
||||||
|
|
||||||
|
var sortedCards = Array.from(cards);
|
||||||
|
sortedCards.sort(function(cardA, cardB) {
|
||||||
|
var a = cardA.dataset[sortKeyDataField];
|
||||||
|
var b = cardB.dataset[sortKeyDataField];
|
||||||
|
if (!isNaN(a) && !isNaN(b)) {
|
||||||
|
return parseInt(a) - parseInt(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (a < b ? -1 : (a > b ? 1 : 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
if (reverse) {
|
||||||
|
sortedCards.reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
parent.innerHTML = '';
|
||||||
|
|
||||||
|
var frag = document.createDocumentFragment();
|
||||||
|
sortedCards.forEach(function(card) {
|
||||||
|
frag.appendChild(card);
|
||||||
|
});
|
||||||
|
parent.appendChild(frag);
|
||||||
|
};
|
||||||
|
|
||||||
|
search.addEventListener("input", function() {
|
||||||
|
applyFilter();
|
||||||
|
});
|
||||||
|
applySort();
|
||||||
|
applyFilter();
|
||||||
|
extraNetworksApplySort[tabname_full] = applySort;
|
||||||
|
extraNetworksApplyFilter[tabname_full] = applyFilter;
|
||||||
|
|
||||||
|
var controls = gradioApp().querySelector("#" + tabname_full + "_controls");
|
||||||
|
controlsDiv.insertBefore(controls, null);
|
||||||
|
|
||||||
|
if (elem.style.display != "none") {
|
||||||
|
extraNetworksShowControlsForPage(tabname, tabname_full);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
registerPrompt(tabname, tabname + "_prompt");
|
||||||
|
registerPrompt(tabname, tabname + "_neg_prompt");
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksMovePromptToTab(tabname, id, showPrompt, showNegativePrompt) {
|
||||||
|
if (!gradioApp().querySelector('.toprow-compact-tools')) return; // only applicable for compact prompt layout
|
||||||
|
|
||||||
|
var promptContainer = gradioApp().getElementById(tabname + '_prompt_container');
|
||||||
|
var prompt = gradioApp().getElementById(tabname + '_prompt_row');
|
||||||
|
var negPrompt = gradioApp().getElementById(tabname + '_neg_prompt_row');
|
||||||
|
var elem = id ? gradioApp().getElementById(id) : null;
|
||||||
|
|
||||||
|
if (showNegativePrompt && elem) {
|
||||||
|
elem.insertBefore(negPrompt, elem.firstChild);
|
||||||
|
} else {
|
||||||
|
promptContainer.insertBefore(negPrompt, promptContainer.firstChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showPrompt && elem) {
|
||||||
|
elem.insertBefore(prompt, elem.firstChild);
|
||||||
|
} else {
|
||||||
|
promptContainer.insertBefore(prompt, promptContainer.firstChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (elem) {
|
||||||
|
elem.classList.toggle('extra-page-prompts-active', showNegativePrompt || showPrompt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function extraNetworksShowControlsForPage(tabname, tabname_full) {
|
||||||
|
gradioApp().querySelectorAll('#' + tabname + '_extra_tabs .extra-networks-controls-div > div').forEach(function(elem) {
|
||||||
|
var targetId = tabname_full + "_controls";
|
||||||
|
elem.style.display = elem.id == targetId ? "" : "none";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function extraNetworksUnrelatedTabSelected(tabname) { // called from python when user selects an unrelated tab (generate)
|
||||||
|
extraNetworksMovePromptToTab(tabname, '', false, false);
|
||||||
|
|
||||||
|
extraNetworksShowControlsForPage(tabname, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksTabSelected(tabname, id, showPrompt, showNegativePrompt, tabname_full) { // called from python when user selects an extra networks tab
|
||||||
|
extraNetworksMovePromptToTab(tabname, id, showPrompt, showNegativePrompt);
|
||||||
|
|
||||||
|
extraNetworksShowControlsForPage(tabname, tabname_full);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyExtraNetworkFilter(tabname_full) {
|
||||||
|
var doFilter = function() {
|
||||||
|
var applyFunction = extraNetworksApplyFilter[tabname_full];
|
||||||
|
|
||||||
|
if (applyFunction) {
|
||||||
|
applyFunction(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
setTimeout(doFilter, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyExtraNetworkSort(tabname_full) {
|
||||||
|
var doSort = function() {
|
||||||
|
extraNetworksApplySort[tabname_full](true);
|
||||||
|
};
|
||||||
|
setTimeout(doSort, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
var extraNetworksApplyFilter = {};
|
||||||
|
var extraNetworksApplySort = {};
|
||||||
|
var activePromptTextarea = {};
|
||||||
|
|
||||||
|
function setupExtraNetworks() {
|
||||||
|
setupExtraNetworksForTab('txt2img');
|
||||||
|
setupExtraNetworksForTab('img2img');
|
||||||
|
}
|
||||||
|
|
||||||
|
var re_extranet = /<([^:^>]+:[^:]+):[\d.]+>(.*)/;
|
||||||
|
var re_extranet_g = /<([^:^>]+:[^:]+):[\d.]+>/g;
|
||||||
|
|
||||||
|
var re_extranet_neg = /\(([^:^>]+:[\d.]+)\)/;
|
||||||
|
var re_extranet_g_neg = /\(([^:^>]+:[\d.]+)\)/g;
|
||||||
|
function tryToRemoveExtraNetworkFromPrompt(textarea, text, isNeg) {
|
||||||
|
var m = text.match(isNeg ? re_extranet_neg : re_extranet);
|
||||||
|
var replaced = false;
|
||||||
|
var newTextareaText;
|
||||||
|
var extraTextBeforeNet = opts.extra_networks_add_text_separator;
|
||||||
|
if (m) {
|
||||||
|
var extraTextAfterNet = m[2];
|
||||||
|
var partToSearch = m[1];
|
||||||
|
var foundAtPosition = -1;
|
||||||
|
newTextareaText = textarea.value.replaceAll(isNeg ? re_extranet_g_neg : re_extranet_g, function(found, net, pos) {
|
||||||
|
m = found.match(isNeg ? re_extranet_neg : re_extranet);
|
||||||
|
if (m[1] == partToSearch) {
|
||||||
|
replaced = true;
|
||||||
|
foundAtPosition = pos;
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
});
|
||||||
|
if (foundAtPosition >= 0) {
|
||||||
|
if (extraTextAfterNet && newTextareaText.substr(foundAtPosition, extraTextAfterNet.length) == extraTextAfterNet) {
|
||||||
|
newTextareaText = newTextareaText.substr(0, foundAtPosition) + newTextareaText.substr(foundAtPosition + extraTextAfterNet.length);
|
||||||
|
}
|
||||||
|
if (newTextareaText.substr(foundAtPosition - extraTextBeforeNet.length, extraTextBeforeNet.length) == extraTextBeforeNet) {
|
||||||
|
newTextareaText = newTextareaText.substr(0, foundAtPosition - extraTextBeforeNet.length) + newTextareaText.substr(foundAtPosition);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
newTextareaText = textarea.value.replaceAll(new RegExp(`((?:${extraTextBeforeNet})?${text})`, "g"), "");
|
||||||
|
replaced = (newTextareaText != textarea.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (replaced) {
|
||||||
|
textarea.value = newTextareaText;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updatePromptArea(text, textArea, isNeg) {
|
||||||
|
if (!tryToRemoveExtraNetworkFromPrompt(textArea, text, isNeg)) {
|
||||||
|
textArea.value = textArea.value + opts.extra_networks_add_text_separator + text;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateInput(textArea);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cardClicked(tabname, textToAdd, textToAddNegative, allowNegativePrompt) {
|
||||||
|
if (textToAddNegative.length > 0) {
|
||||||
|
updatePromptArea(textToAdd, gradioApp().querySelector("#" + tabname + "_prompt > label > textarea"));
|
||||||
|
updatePromptArea(textToAddNegative, gradioApp().querySelector("#" + tabname + "_neg_prompt > label > textarea"), true);
|
||||||
|
} else {
|
||||||
|
var textarea = allowNegativePrompt ? activePromptTextarea[tabname] : gradioApp().querySelector("#" + tabname + "_prompt > label > textarea");
|
||||||
|
updatePromptArea(textToAdd, textarea);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveCardPreview(event, tabname, filename) {
|
||||||
|
var textarea = gradioApp().querySelector("#" + tabname + '_preview_filename > label > textarea');
|
||||||
|
var button = gradioApp().getElementById(tabname + '_save_preview');
|
||||||
|
|
||||||
|
textarea.value = filename;
|
||||||
|
updateInput(textarea);
|
||||||
|
|
||||||
|
button.click();
|
||||||
|
|
||||||
|
event.stopPropagation();
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksSearchButton(tabname, extra_networks_tabname, event) {
|
||||||
|
var searchTextarea = gradioApp().querySelector("#" + tabname + "_" + extra_networks_tabname + "_extra_search");
|
||||||
|
var button = event.target;
|
||||||
|
var text = button.classList.contains("search-all") ? "" : button.textContent.trim();
|
||||||
|
|
||||||
|
searchTextarea.value = text;
|
||||||
|
updateInput(searchTextarea);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksTreeProcessFileClick(event, btn, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Processes `onclick` events when user clicks on files in tree.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param btn The clicked `tree-list-item` button.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
// NOTE: Currently unused.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksTreeProcessDirectoryClick(event, btn, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Processes `onclick` events when user clicks on directories in tree.
|
||||||
|
*
|
||||||
|
* Here is how the tree reacts to clicks for various states:
|
||||||
|
* unselected unopened directory: Directory is selected and expanded.
|
||||||
|
* unselected opened directory: Directory is selected.
|
||||||
|
* selected opened directory: Directory is collapsed and deselected.
|
||||||
|
* chevron is clicked: Directory is expanded or collapsed. Selected state unchanged.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param btn The clicked `tree-list-item` button.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
var ul = btn.nextElementSibling;
|
||||||
|
// This is the actual target that the user clicked on within the target button.
|
||||||
|
// We use this to detect if the chevron was clicked.
|
||||||
|
var true_targ = event.target;
|
||||||
|
|
||||||
|
function _expand_or_collapse(_ul, _btn) {
|
||||||
|
// Expands <ul> if it is collapsed, collapses otherwise. Updates button attributes.
|
||||||
|
if (_ul.hasAttribute("hidden")) {
|
||||||
|
_ul.removeAttribute("hidden");
|
||||||
|
_btn.dataset.expanded = "";
|
||||||
|
} else {
|
||||||
|
_ul.setAttribute("hidden", "");
|
||||||
|
delete _btn.dataset.expanded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _remove_selected_from_all() {
|
||||||
|
// Removes the `selected` attribute from all buttons.
|
||||||
|
var sels = document.querySelectorAll("div.tree-list-content");
|
||||||
|
[...sels].forEach(el => {
|
||||||
|
delete el.dataset.selected;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function _select_button(_btn) {
|
||||||
|
// Removes `data-selected` attribute from all buttons then adds to passed button.
|
||||||
|
_remove_selected_from_all();
|
||||||
|
_btn.dataset.selected = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function _update_search(_tabname, _extra_networks_tabname, _search_text) {
|
||||||
|
// Update search input with select button's path.
|
||||||
|
var search_input_elem = gradioApp().querySelector("#" + tabname + "_" + extra_networks_tabname + "_extra_search");
|
||||||
|
search_input_elem.value = _search_text;
|
||||||
|
updateInput(search_input_elem);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// If user clicks on the chevron, then we do not select the folder.
|
||||||
|
if (true_targ.matches(".tree-list-item-action--leading, .tree-list-item-action-chevron")) {
|
||||||
|
_expand_or_collapse(ul, btn);
|
||||||
|
} else {
|
||||||
|
// User clicked anywhere else on the button.
|
||||||
|
if ("selected" in btn.dataset && !(ul.hasAttribute("hidden"))) {
|
||||||
|
// If folder is select and open, collapse and deselect button.
|
||||||
|
_expand_or_collapse(ul, btn);
|
||||||
|
delete btn.dataset.selected;
|
||||||
|
_update_search(tabname, extra_networks_tabname, "");
|
||||||
|
} else if (!(!("selected" in btn.dataset) && !(ul.hasAttribute("hidden")))) {
|
||||||
|
// If folder is open and not selected, then we don't collapse; just select.
|
||||||
|
// NOTE: Double inversion sucks but it is the clearest way to show the branching here.
|
||||||
|
_expand_or_collapse(ul, btn);
|
||||||
|
_select_button(btn, tabname, extra_networks_tabname);
|
||||||
|
_update_search(tabname, extra_networks_tabname, btn.dataset.path);
|
||||||
|
} else {
|
||||||
|
// All other cases, just select the button.
|
||||||
|
_select_button(btn, tabname, extra_networks_tabname);
|
||||||
|
_update_search(tabname, extra_networks_tabname, btn.dataset.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksTreeOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Handles `onclick` events for buttons within an `extra-network-tree .tree-list--tree`.
|
||||||
|
*
|
||||||
|
* Determines whether the clicked button in the tree is for a file entry or a directory
|
||||||
|
* then calls the appropriate function.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
var btn = event.currentTarget;
|
||||||
|
var par = btn.parentElement;
|
||||||
|
if (par.dataset.treeEntryType === "file") {
|
||||||
|
extraNetworksTreeProcessFileClick(event, btn, tabname, extra_networks_tabname);
|
||||||
|
} else {
|
||||||
|
extraNetworksTreeProcessDirectoryClick(event, btn, tabname, extra_networks_tabname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksControlSortOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/** Handles `onclick` events for Sort Mode buttons. */
|
||||||
|
|
||||||
|
var self = event.currentTarget;
|
||||||
|
var parent = event.currentTarget.parentElement;
|
||||||
|
|
||||||
|
parent.querySelectorAll('.extra-network-control--sort').forEach(function(x) {
|
||||||
|
x.classList.remove('extra-network-control--enabled');
|
||||||
|
});
|
||||||
|
|
||||||
|
self.classList.add('extra-network-control--enabled');
|
||||||
|
|
||||||
|
applyExtraNetworkSort(tabname + "_" + extra_networks_tabname);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksControlSortDirOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Handles `onclick` events for the Sort Direction button.
|
||||||
|
*
|
||||||
|
* Modifies the data attributes of the Sort Direction button to cycle between
|
||||||
|
* ascending and descending sort directions.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
if (event.currentTarget.dataset.sortdir == "Ascending") {
|
||||||
|
event.currentTarget.dataset.sortdir = "Descending";
|
||||||
|
event.currentTarget.setAttribute("title", "Sort descending");
|
||||||
|
} else {
|
||||||
|
event.currentTarget.dataset.sortdir = "Ascending";
|
||||||
|
event.currentTarget.setAttribute("title", "Sort ascending");
|
||||||
|
}
|
||||||
|
applyExtraNetworkSort(tabname + "_" + extra_networks_tabname);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksControlTreeViewOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Handles `onclick` events for the Tree View button.
|
||||||
|
*
|
||||||
|
* Toggles the tree view in the extra networks pane.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
var button = event.currentTarget;
|
||||||
|
button.classList.toggle("extra-network-control--enabled");
|
||||||
|
var show = !button.classList.contains("extra-network-control--enabled");
|
||||||
|
|
||||||
|
var pane = gradioApp().getElementById(tabname + "_" + extra_networks_tabname + "_pane");
|
||||||
|
pane.classList.toggle("extra-network-dirs-hidden", show);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksControlRefreshOnClick(event, tabname, extra_networks_tabname) {
|
||||||
|
/**
|
||||||
|
* Handles `onclick` events for the Refresh Page button.
|
||||||
|
*
|
||||||
|
* In order to actually call the python functions in `ui_extra_networks.py`
|
||||||
|
* to refresh the page, we created an empty gradio button in that file with an
|
||||||
|
* event handler that refreshes the page. So what this function here does
|
||||||
|
* is it manually raises a `click` event on that button.
|
||||||
|
*
|
||||||
|
* @param event The generated event.
|
||||||
|
* @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
|
||||||
|
* @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
|
||||||
|
*/
|
||||||
|
var btn_refresh_internal = gradioApp().getElementById(tabname + "_" + extra_networks_tabname + "_extra_refresh_internal");
|
||||||
|
btn_refresh_internal.dispatchEvent(new Event("click"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var globalPopup = null;
|
||||||
|
var globalPopupInner = null;
|
||||||
|
|
||||||
|
function closePopup() {
|
||||||
|
if (!globalPopup) return;
|
||||||
|
globalPopup.style.display = "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
function popup(contents) {
|
||||||
|
if (!globalPopup) {
|
||||||
|
globalPopup = document.createElement('div');
|
||||||
|
globalPopup.classList.add('global-popup');
|
||||||
|
|
||||||
|
var close = document.createElement('div');
|
||||||
|
close.classList.add('global-popup-close');
|
||||||
|
close.addEventListener("click", closePopup);
|
||||||
|
close.title = "Close";
|
||||||
|
globalPopup.appendChild(close);
|
||||||
|
|
||||||
|
globalPopupInner = document.createElement('div');
|
||||||
|
globalPopupInner.classList.add('global-popup-inner');
|
||||||
|
globalPopup.appendChild(globalPopupInner);
|
||||||
|
|
||||||
|
gradioApp().querySelector('.main').appendChild(globalPopup);
|
||||||
|
}
|
||||||
|
|
||||||
|
globalPopupInner.innerHTML = '';
|
||||||
|
globalPopupInner.appendChild(contents);
|
||||||
|
|
||||||
|
globalPopup.style.display = "flex";
|
||||||
|
}
|
||||||
|
|
||||||
|
var storedPopupIds = {};
|
||||||
|
function popupId(id) {
|
||||||
|
if (!storedPopupIds[id]) {
|
||||||
|
storedPopupIds[id] = gradioApp().getElementById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
popup(storedPopupIds[id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksFlattenMetadata(obj) {
|
||||||
|
const result = {};
|
||||||
|
|
||||||
|
// Convert any stringified JSON objects to actual objects
|
||||||
|
for (const key of Object.keys(obj)) {
|
||||||
|
if (typeof obj[key] === 'string') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(obj[key]);
|
||||||
|
if (parsed && typeof parsed === 'object') {
|
||||||
|
obj[key] = parsed;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flatten the object
|
||||||
|
for (const key of Object.keys(obj)) {
|
||||||
|
if (typeof obj[key] === 'object' && obj[key] !== null) {
|
||||||
|
const nested = extraNetworksFlattenMetadata(obj[key]);
|
||||||
|
for (const nestedKey of Object.keys(nested)) {
|
||||||
|
result[`${key}/${nestedKey}`] = nested[nestedKey];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result[key] = obj[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Special case for handling modelspec keys
|
||||||
|
for (const key of Object.keys(result)) {
|
||||||
|
if (key.startsWith("modelspec.")) {
|
||||||
|
result[key.replaceAll(".", "/")] = result[key];
|
||||||
|
delete result[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add empty keys to designate hierarchy
|
||||||
|
for (const key of Object.keys(result)) {
|
||||||
|
const parts = key.split("/");
|
||||||
|
for (let i = 1; i < parts.length; i++) {
|
||||||
|
const parent = parts.slice(0, i).join("/");
|
||||||
|
if (!result[parent]) {
|
||||||
|
result[parent] = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksShowMetadata(text) {
|
||||||
|
try {
|
||||||
|
let parsed = JSON.parse(text);
|
||||||
|
if (parsed && typeof parsed === 'object') {
|
||||||
|
parsed = extraNetworksFlattenMetadata(parsed);
|
||||||
|
const table = createVisualizationTable(parsed, 0);
|
||||||
|
popup(table);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
var elem = document.createElement('pre');
|
||||||
|
elem.classList.add('popup-metadata');
|
||||||
|
elem.textContent = text;
|
||||||
|
|
||||||
|
popup(elem);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestGet(url, data, handler, errorHandler) {
|
||||||
|
var xhr = new XMLHttpRequest();
|
||||||
|
var args = Object.keys(data).map(function(k) {
|
||||||
|
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
|
||||||
|
}).join('&');
|
||||||
|
xhr.open("GET", url + "?" + args, true);
|
||||||
|
|
||||||
|
xhr.onreadystatechange = function() {
|
||||||
|
if (xhr.readyState === 4) {
|
||||||
|
if (xhr.status === 200) {
|
||||||
|
try {
|
||||||
|
var js = JSON.parse(xhr.responseText);
|
||||||
|
handler(js);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
errorHandler();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
errorHandler();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var js = JSON.stringify(data);
|
||||||
|
xhr.send(js);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksCopyCardPath(event) {
|
||||||
|
navigator.clipboard.writeText(event.target.getAttribute("data-clipboard-text"));
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksRequestMetadata(event, extraPage) {
|
||||||
|
var showError = function() {
|
||||||
|
extraNetworksShowMetadata("there was an error getting metadata");
|
||||||
|
};
|
||||||
|
|
||||||
|
var cardName = event.target.parentElement.parentElement.getAttribute("data-name");
|
||||||
|
|
||||||
|
requestGet("./sd_extra_networks/metadata", {page: extraPage, item: cardName}, function(data) {
|
||||||
|
if (data && data.metadata) {
|
||||||
|
extraNetworksShowMetadata(data.metadata);
|
||||||
|
} else {
|
||||||
|
showError();
|
||||||
|
}
|
||||||
|
}, showError);
|
||||||
|
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
var extraPageUserMetadataEditors = {};
|
||||||
|
|
||||||
|
function extraNetworksEditUserMetadata(event, tabname, extraPage) {
|
||||||
|
var id = tabname + '_' + extraPage + '_edit_user_metadata';
|
||||||
|
|
||||||
|
var editor = extraPageUserMetadataEditors[id];
|
||||||
|
if (!editor) {
|
||||||
|
editor = {};
|
||||||
|
editor.page = gradioApp().getElementById(id);
|
||||||
|
editor.nameTextarea = gradioApp().querySelector("#" + id + "_name" + ' textarea');
|
||||||
|
editor.button = gradioApp().querySelector("#" + id + "_button");
|
||||||
|
extraPageUserMetadataEditors[id] = editor;
|
||||||
|
}
|
||||||
|
|
||||||
|
var cardName = event.target.parentElement.parentElement.getAttribute("data-name");
|
||||||
|
editor.nameTextarea.value = cardName;
|
||||||
|
updateInput(editor.nameTextarea);
|
||||||
|
|
||||||
|
editor.button.click();
|
||||||
|
|
||||||
|
popup(editor.page);
|
||||||
|
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function extraNetworksRefreshSingleCard(page, tabname, name) {
|
||||||
|
requestGet("./sd_extra_networks/get-single-card", {page: page, tabname: tabname, name: name}, function(data) {
|
||||||
|
if (data && data.html) {
|
||||||
|
var card = gradioApp().querySelector(`#${tabname}_${page.replace(" ", "_")}_cards > .card[data-name="${name}"]`);
|
||||||
|
|
||||||
|
var newDiv = document.createElement('DIV');
|
||||||
|
newDiv.innerHTML = data.html;
|
||||||
|
var newCard = newDiv.firstElementChild;
|
||||||
|
|
||||||
|
newCard.style.display = '';
|
||||||
|
card.parentElement.insertBefore(newCard, card);
|
||||||
|
card.parentElement.removeChild(card);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("keydown", function(event) {
|
||||||
|
if (event.key == "Escape") {
|
||||||
|
closePopup();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Setup custom loading for this script.
|
||||||
|
* We need to wait for all of our HTML to be generated in the extra networks tabs
|
||||||
|
* before we can actually run the `setupExtraNetworks` function.
|
||||||
|
* The `onUiLoaded` function actually runs before all of our extra network tabs are
|
||||||
|
* finished generating. Thus we needed this new method.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
var uiAfterScriptsCallbacks = [];
|
||||||
|
var uiAfterScriptsTimeout = null;
|
||||||
|
var executedAfterScripts = false;
|
||||||
|
|
||||||
|
function scheduleAfterScriptsCallbacks() {
|
||||||
|
clearTimeout(uiAfterScriptsTimeout);
|
||||||
|
uiAfterScriptsTimeout = setTimeout(function() {
|
||||||
|
executeCallbacks(uiAfterScriptsCallbacks);
|
||||||
|
}, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
var mutationObserver = new MutationObserver(function(m) {
|
||||||
|
let existingSearchfields = gradioApp().querySelectorAll("[id$='_extra_search']").length;
|
||||||
|
let neededSearchfields = gradioApp().querySelectorAll("[id$='_extra_tabs'] > .tab-nav > button").length - 2;
|
||||||
|
|
||||||
|
if (!executedAfterScripts && existingSearchfields >= neededSearchfields) {
|
||||||
|
mutationObserver.disconnect();
|
||||||
|
executedAfterScripts = true;
|
||||||
|
scheduleAfterScriptsCallbacks();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
mutationObserver.observe(gradioApp(), {childList: true, subtree: true});
|
||||||
|
});
|
||||||
|
|
||||||
|
uiAfterScriptsCallbacks.push(setupExtraNetworks);
|
35
javascript/generationParams.js
Normal file
35
javascript/generationParams.js
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
// attaches listeners to the txt2img and img2img galleries to update displayed generation param text when the image changes
|
||||||
|
|
||||||
|
let txt2img_gallery, img2img_gallery, modal = undefined;
|
||||||
|
onAfterUiUpdate(function() {
|
||||||
|
if (!txt2img_gallery) {
|
||||||
|
txt2img_gallery = attachGalleryListeners("txt2img");
|
||||||
|
}
|
||||||
|
if (!img2img_gallery) {
|
||||||
|
img2img_gallery = attachGalleryListeners("img2img");
|
||||||
|
}
|
||||||
|
if (!modal) {
|
||||||
|
modal = gradioApp().getElementById('lightboxModal');
|
||||||
|
modalObserver.observe(modal, {attributes: true, attributeFilter: ['style']});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let modalObserver = new MutationObserver(function(mutations) {
|
||||||
|
mutations.forEach(function(mutationRecord) {
|
||||||
|
let selectedTab = gradioApp().querySelector('#tabs div button.selected')?.innerText;
|
||||||
|
if (mutationRecord.target.style.display === 'none' && (selectedTab === 'txt2img' || selectedTab === 'img2img')) {
|
||||||
|
gradioApp().getElementById(selectedTab + "_generation_info_button")?.click();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function attachGalleryListeners(tab_name) {
|
||||||
|
var gallery = gradioApp().querySelector('#' + tab_name + '_gallery');
|
||||||
|
gallery?.addEventListener('click', () => gradioApp().getElementById(tab_name + "_generation_info_button").click());
|
||||||
|
gallery?.addEventListener('keydown', (e) => {
|
||||||
|
if (e.keyCode == 37 || e.keyCode == 39) { // left or right arrow
|
||||||
|
gradioApp().getElementById(tab_name + "_generation_info_button").click();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return gallery;
|
||||||
|
}
|
203
javascript/hints.js
Normal file
203
javascript/hints.js
Normal file
@ -0,0 +1,203 @@
|
|||||||
|
// mouseover tooltips for various UI elements
|
||||||
|
|
||||||
|
var titles = {
|
||||||
|
"Sampling steps": "How many times to improve the generated image iteratively; higher values take longer; very low values can produce bad results",
|
||||||
|
"Sampling method": "Which algorithm to use to produce the image",
|
||||||
|
"GFPGAN": "Restore low quality faces using GFPGAN neural network",
|
||||||
|
"Euler a": "Euler Ancestral - very creative, each can get a completely different picture depending on step count, setting steps higher than 30-40 does not help",
|
||||||
|
"DDIM": "Denoising Diffusion Implicit Models - best at inpainting",
|
||||||
|
"UniPC": "Unified Predictor-Corrector Framework for Fast Sampling of Diffusion Models",
|
||||||
|
"DPM adaptive": "Ignores step count - uses a number of steps determined by the CFG and resolution",
|
||||||
|
|
||||||
|
"\u{1F4D0}": "Auto detect size from img2img",
|
||||||
|
"Batch count": "How many batches of images to create (has no impact on generation performance or VRAM usage)",
|
||||||
|
"Batch size": "How many image to create in a single batch (increases generation performance at cost of higher VRAM usage)",
|
||||||
|
"CFG Scale": "Classifier Free Guidance Scale - how strongly the image should conform to prompt - lower values produce more creative results",
|
||||||
|
"Seed": "A value that determines the output of random number generator - if you create an image with same parameters and seed as another image, you'll get the same result",
|
||||||
|
"\u{1f3b2}\ufe0f": "Set seed to -1, which will cause a new random number to be used every time",
|
||||||
|
"\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomized",
|
||||||
|
"\u2199\ufe0f": "Read generation parameters from prompt or last generation if prompt is empty into user interface.",
|
||||||
|
"\u{1f4c2}": "Open images output directory",
|
||||||
|
"\u{1f4be}": "Save style",
|
||||||
|
"\u{1f5d1}\ufe0f": "Clear prompt",
|
||||||
|
"\u{1f4cb}": "Apply selected styles to current prompt",
|
||||||
|
"\u{1f4d2}": "Paste available values into the field",
|
||||||
|
"\u{1f3b4}": "Show/hide extra networks",
|
||||||
|
"\u{1f300}": "Restore progress",
|
||||||
|
|
||||||
|
"Inpaint a part of image": "Draw a mask over an image, and the script will regenerate the masked area with content according to prompt",
|
||||||
|
"SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back",
|
||||||
|
|
||||||
|
"Just resize": "Resize image to target resolution. Unless height and width match, you will get incorrect aspect ratio.",
|
||||||
|
"Crop and resize": "Resize the image so that entirety of target resolution is filled with the image. Crop parts that stick out.",
|
||||||
|
"Resize and fill": "Resize the image so that entirety of image is inside target resolution. Fill empty space with image's colors.",
|
||||||
|
|
||||||
|
"Mask blur": "How much to blur the mask before processing, in pixels.",
|
||||||
|
"Masked content": "What to put inside the masked area before processing it with Stable Diffusion.",
|
||||||
|
"fill": "fill it with colors of the image",
|
||||||
|
"original": "keep whatever was there originally",
|
||||||
|
"latent noise": "fill it with latent space noise",
|
||||||
|
"latent nothing": "fill it with latent space zeroes",
|
||||||
|
"Inpaint at full resolution": "Upscale masked region to target resolution, do inpainting, downscale back and paste into original image",
|
||||||
|
|
||||||
|
"Denoising strength": "Determines how little respect the algorithm should have for image's content. At 0, nothing will change, and at 1 you'll get an unrelated image. With values below 1.0, processing will take less steps than the Sampling Steps slider specifies.",
|
||||||
|
|
||||||
|
"Skip": "Stop processing current image and continue processing.",
|
||||||
|
"Interrupt": "Stop processing images and return any results accumulated so far.",
|
||||||
|
"Save": "Write image to a directory (default - log/images) and generation parameters into csv file.",
|
||||||
|
|
||||||
|
"X values": "Separate values for X axis using commas.",
|
||||||
|
"Y values": "Separate values for Y axis using commas.",
|
||||||
|
|
||||||
|
"None": "Do not do anything special",
|
||||||
|
"Prompt matrix": "Separate prompts into parts using vertical pipe character (|) and the script will create a picture for every combination of them (except for the first part, which will be present in all combinations)",
|
||||||
|
"X/Y/Z plot": "Create grid(s) where images will have different parameters. Use inputs below to specify which parameters will be shared by columns and rows",
|
||||||
|
"Custom code": "Run Python code. Advanced user only. Must run program with --allow-code for this to work",
|
||||||
|
|
||||||
|
"Prompt S/R": "Separate a list of words with commas, and the first word will be used as a keyword: script will search for this word in the prompt, and replace it with others",
|
||||||
|
"Prompt order": "Separate a list of words with commas, and the script will make a variation of prompt with those words for their every possible order",
|
||||||
|
|
||||||
|
"Tiling": "Produce an image that can be tiled.",
|
||||||
|
"Tile overlap": "For SD upscale, how much overlap in pixels should there be between tiles. Tiles overlap so that when they are merged back into one picture, there is no clearly visible seam.",
|
||||||
|
|
||||||
|
"Variation seed": "Seed of a different picture to be mixed into the generation.",
|
||||||
|
"Variation strength": "How strong of a variation to produce. At 0, there will be no effect. At 1, you will get the complete picture with variation seed (except for ancestral samplers, where you will just get something).",
|
||||||
|
"Resize seed from height": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution",
|
||||||
|
"Resize seed from width": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution",
|
||||||
|
|
||||||
|
"Interrogate": "Reconstruct prompt from existing image and put it into the prompt field.",
|
||||||
|
|
||||||
|
"Images filename pattern": "Use tags like [seed] and [date] to define how filenames for images are chosen. Leave empty for default.",
|
||||||
|
"Directory name pattern": "Use tags like [seed] and [date] to define how subdirectories for images and grids are chosen. Leave empty for default.",
|
||||||
|
"Max prompt words": "Set the maximum number of words to be used in the [prompt_words] option; ATTENTION: If the words are too long, they may exceed the maximum length of the file path that the system can handle",
|
||||||
|
|
||||||
|
"Loopback": "Performs img2img processing multiple times. Output images are used as input for the next loop.",
|
||||||
|
"Loops": "How many times to process an image. Each output is used as the input of the next loop. If set to 1, behavior will be as if this script were not used.",
|
||||||
|
"Final denoising strength": "The denoising strength for the final loop of each image in the batch.",
|
||||||
|
"Denoising strength curve": "The denoising curve controls the rate of denoising strength change each loop. Aggressive: Most of the change will happen towards the start of the loops. Linear: Change will be constant through all loops. Lazy: Most of the change will happen towards the end of the loops.",
|
||||||
|
|
||||||
|
"Style 1": "Style to apply; styles have components for both positive and negative prompts and apply to both",
|
||||||
|
"Style 2": "Style to apply; styles have components for both positive and negative prompts and apply to both",
|
||||||
|
"Apply style": "Insert selected styles into prompt fields",
|
||||||
|
"Create style": "Save current prompts as a style. If you add the token {prompt} to the text, the style uses that as a placeholder for your prompt when you use the style in the future.",
|
||||||
|
|
||||||
|
"Checkpoint name": "Loads weights from checkpoint before making images. You can either use hash or a part of filename (as seen in settings) for checkpoint name. Recommended to use with Y axis for less switching.",
|
||||||
|
"Inpainting conditioning mask strength": "Only applies to inpainting models. Determines how strongly to mask off the original image for inpainting and img2img. 1.0 means fully masked, which is the default behaviour. 0.0 means a fully unmasked conditioning. Lower values will help preserve the overall composition of the image, but will struggle with large changes.",
|
||||||
|
|
||||||
|
"Eta noise seed delta": "If this values is non-zero, it will be added to seed and used to initialize RNG for noises when using samplers with Eta. You can use this to produce even more variation of images, or you can use this to match images of other software if you know what you are doing.",
|
||||||
|
|
||||||
|
"Filename word regex": "This regular expression will be used extract words from filename, and they will be joined using the option below into label text used for training. Leave empty to keep filename text as it is.",
|
||||||
|
"Filename join string": "This string will be used to join split words into a single line if the option above is enabled.",
|
||||||
|
|
||||||
|
"Quicksettings list": "List of setting names, separated by commas, for settings that should go to the quick access bar at the top, rather than the usual setting tab. See modules/shared.py for setting names. Requires restarting to apply.",
|
||||||
|
|
||||||
|
"Weighted sum": "Result = A * (1 - M) + B * M",
|
||||||
|
"Add difference": "Result = A + (B - C) * M",
|
||||||
|
"No interpolation": "Result = A",
|
||||||
|
|
||||||
|
"Initialization text": "If the number of tokens is more than the number of vectors, some may be skipped.\nLeave the textbox empty to start with zeroed out vectors",
|
||||||
|
"Learning rate": "How fast should training go. Low values will take longer to train, high values may fail to converge (not generate accurate results) and/or may break the embedding (This has happened if you see Loss: nan in the training info textbox. If this happens, you need to manually restore your embedding from an older not-broken backup).\n\nYou can set a single numeric value, or multiple learning rates using the syntax:\n\n rate_1:max_steps_1, rate_2:max_steps_2, ...\n\nEG: 0.005:100, 1e-3:1000, 1e-5\n\nWill train with rate of 0.005 for first 100 steps, then 1e-3 until 1000 steps, then 1e-5 for all remaining steps.",
|
||||||
|
|
||||||
|
"Clip skip": "Early stopping parameter for CLIP model; 1 is stop at last layer as usual, 2 is stop at penultimate layer, etc.",
|
||||||
|
|
||||||
|
"Approx NN": "Cheap neural network approximation. Very fast compared to VAE, but produces pictures with 4 times smaller horizontal/vertical resolution and lower quality.",
|
||||||
|
"Approx cheap": "Very cheap approximation. Very fast compared to VAE, but produces pictures with 8 times smaller horizontal/vertical resolution and extremely low quality.",
|
||||||
|
|
||||||
|
"Hires. fix": "Use a two step process to partially create an image at smaller resolution, upscale, and then improve details in it without changing composition",
|
||||||
|
"Hires steps": "Number of sampling steps for upscaled picture. If 0, uses same as for original.",
|
||||||
|
"Upscale by": "Adjusts the size of the image by multiplying the original width and height by the selected value. Ignored if either Resize width to or Resize height to are non-zero.",
|
||||||
|
"Resize width to": "Resizes image to this width. If 0, width is inferred from either of two nearby sliders.",
|
||||||
|
"Resize height to": "Resizes image to this height. If 0, height is inferred from either of two nearby sliders.",
|
||||||
|
"Discard weights with matching name": "Regular expression; if weights's name matches it, the weights is not written to the resulting checkpoint. Use ^model_ema to discard EMA weights.",
|
||||||
|
"Extra networks tab order": "Comma-separated list of tab names; tabs listed here will appear in the extra networks UI first and in order listed.",
|
||||||
|
"Negative Guidance minimum sigma": "Skip negative prompt for steps where image is already mostly denoised; the higher this value, the more skips there will be; provides increased performance in exchange for minor quality reduction."
|
||||||
|
};
|
||||||
|
|
||||||
|
function updateTooltip(element) {
|
||||||
|
if (element.title) return; // already has a title
|
||||||
|
|
||||||
|
let text = element.textContent;
|
||||||
|
let tooltip = localization[titles[text]] || titles[text];
|
||||||
|
|
||||||
|
if (!tooltip) {
|
||||||
|
let value = element.value;
|
||||||
|
if (value) tooltip = localization[titles[value]] || titles[value];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tooltip) {
|
||||||
|
// Gradio dropdown options have `data-value`.
|
||||||
|
let dataValue = element.dataset.value;
|
||||||
|
if (dataValue) tooltip = localization[titles[dataValue]] || titles[dataValue];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tooltip) {
|
||||||
|
for (const c of element.classList) {
|
||||||
|
if (c in titles) {
|
||||||
|
tooltip = localization[titles[c]] || titles[c];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tooltip) {
|
||||||
|
element.title = tooltip;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nodes to check for adding tooltips.
|
||||||
|
const tooltipCheckNodes = new Set();
|
||||||
|
// Timer for debouncing tooltip check.
|
||||||
|
let tooltipCheckTimer = null;
|
||||||
|
|
||||||
|
function processTooltipCheckNodes() {
|
||||||
|
for (const node of tooltipCheckNodes) {
|
||||||
|
updateTooltip(node);
|
||||||
|
}
|
||||||
|
tooltipCheckNodes.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiUpdate(function(mutationRecords) {
|
||||||
|
for (const record of mutationRecords) {
|
||||||
|
if (record.type === "childList" && record.target.classList.contains("options")) {
|
||||||
|
// This smells like a Gradio dropdown menu having changed,
|
||||||
|
// so let's enqueue an update for the input element that shows the current value.
|
||||||
|
let wrap = record.target.parentNode;
|
||||||
|
let input = wrap?.querySelector("input");
|
||||||
|
if (input) {
|
||||||
|
input.title = ""; // So we'll even have a chance to update it.
|
||||||
|
tooltipCheckNodes.add(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const node of record.addedNodes) {
|
||||||
|
if (node.nodeType === Node.ELEMENT_NODE && !node.classList.contains("hide")) {
|
||||||
|
if (!node.title) {
|
||||||
|
if (
|
||||||
|
node.tagName === "SPAN" ||
|
||||||
|
node.tagName === "BUTTON" ||
|
||||||
|
node.tagName === "P" ||
|
||||||
|
node.tagName === "INPUT" ||
|
||||||
|
(node.tagName === "LI" && node.classList.contains("item")) // Gradio dropdown item
|
||||||
|
) {
|
||||||
|
tooltipCheckNodes.add(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
node.querySelectorAll('span, button, p').forEach(n => tooltipCheckNodes.add(n));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (tooltipCheckNodes.size) {
|
||||||
|
clearTimeout(tooltipCheckTimer);
|
||||||
|
tooltipCheckTimer = setTimeout(processTooltipCheckNodes, 1000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
for (var comp of window.gradio_config.components) {
|
||||||
|
if (comp.props.webui_tooltip && comp.props.elem_id) {
|
||||||
|
var elem = gradioApp().getElementById(comp.props.elem_id);
|
||||||
|
if (elem) {
|
||||||
|
elem.title = comp.props.webui_tooltip;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
18
javascript/hires_fix.js
Normal file
18
javascript/hires_fix.js
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
|
||||||
|
function onCalcResolutionHires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y) {
|
||||||
|
function setInactive(elem, inactive) {
|
||||||
|
elem.classList.toggle('inactive', !!inactive);
|
||||||
|
}
|
||||||
|
|
||||||
|
var hrUpscaleBy = gradioApp().getElementById('txt2img_hr_scale');
|
||||||
|
var hrResizeX = gradioApp().getElementById('txt2img_hr_resize_x');
|
||||||
|
var hrResizeY = gradioApp().getElementById('txt2img_hr_resize_y');
|
||||||
|
|
||||||
|
gradioApp().getElementById('txt2img_hires_fix_row2').style.display = opts.use_old_hires_fix_width_height ? "none" : "";
|
||||||
|
|
||||||
|
setInactive(hrUpscaleBy, opts.use_old_hires_fix_width_height || hr_resize_x > 0 || hr_resize_y > 0);
|
||||||
|
setInactive(hrResizeX, opts.use_old_hires_fix_width_height || hr_resize_x == 0);
|
||||||
|
setInactive(hrResizeY, opts.use_old_hires_fix_width_height || hr_resize_y == 0);
|
||||||
|
|
||||||
|
return [enable, width, height, hr_scale, hr_resize_x, hr_resize_y];
|
||||||
|
}
|
43
javascript/imageMaskFix.js
Normal file
43
javascript/imageMaskFix.js
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* temporary fix for https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/668
|
||||||
|
* @see https://github.com/gradio-app/gradio/issues/1721
|
||||||
|
*/
|
||||||
|
function imageMaskResize() {
|
||||||
|
const canvases = gradioApp().querySelectorAll('#img2maskimg .touch-none canvas');
|
||||||
|
if (!canvases.length) {
|
||||||
|
window.removeEventListener('resize', imageMaskResize);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const wrapper = canvases[0].closest('.touch-none');
|
||||||
|
const previewImage = wrapper.previousElementSibling;
|
||||||
|
|
||||||
|
if (!previewImage.complete) {
|
||||||
|
previewImage.addEventListener('load', imageMaskResize);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const w = previewImage.width;
|
||||||
|
const h = previewImage.height;
|
||||||
|
const nw = previewImage.naturalWidth;
|
||||||
|
const nh = previewImage.naturalHeight;
|
||||||
|
const portrait = nh > nw;
|
||||||
|
|
||||||
|
const wW = Math.min(w, portrait ? h / nh * nw : w / nw * nw);
|
||||||
|
const wH = Math.min(h, portrait ? h / nh * nh : w / nw * nh);
|
||||||
|
|
||||||
|
wrapper.style.width = `${wW}px`;
|
||||||
|
wrapper.style.height = `${wH}px`;
|
||||||
|
wrapper.style.left = `0px`;
|
||||||
|
wrapper.style.top = `0px`;
|
||||||
|
|
||||||
|
canvases.forEach(c => {
|
||||||
|
c.style.width = c.style.height = '';
|
||||||
|
c.style.maxWidth = '100%';
|
||||||
|
c.style.maxHeight = '100%';
|
||||||
|
c.style.objectFit = 'contain';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onAfterUiUpdate(imageMaskResize);
|
||||||
|
window.addEventListener('resize', imageMaskResize);
|
268
javascript/imageviewer.js
Normal file
268
javascript/imageviewer.js
Normal file
@ -0,0 +1,268 @@
|
|||||||
|
// A full size 'lightbox' preview modal shown when left clicking on gallery previews
|
||||||
|
function closeModal() {
|
||||||
|
gradioApp().getElementById("lightboxModal").style.display = "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
function showModal(event) {
|
||||||
|
const source = event.target || event.srcElement;
|
||||||
|
const modalImage = gradioApp().getElementById("modalImage");
|
||||||
|
const modalToggleLivePreviewBtn = gradioApp().getElementById("modal_toggle_live_preview");
|
||||||
|
modalToggleLivePreviewBtn.innerHTML = opts.js_live_preview_in_modal_lightbox ? "🗇" : "🗆";
|
||||||
|
const lb = gradioApp().getElementById("lightboxModal");
|
||||||
|
modalImage.src = source.src;
|
||||||
|
if (modalImage.style.display === 'none') {
|
||||||
|
lb.style.setProperty('background-image', 'url(' + source.src + ')');
|
||||||
|
}
|
||||||
|
lb.style.display = "flex";
|
||||||
|
lb.focus();
|
||||||
|
|
||||||
|
const tabTxt2Img = gradioApp().getElementById("tab_txt2img");
|
||||||
|
const tabImg2Img = gradioApp().getElementById("tab_img2img");
|
||||||
|
// show the save button in modal only on txt2img or img2img tabs
|
||||||
|
if (tabTxt2Img.style.display != "none" || tabImg2Img.style.display != "none") {
|
||||||
|
gradioApp().getElementById("modal_save").style.display = "inline";
|
||||||
|
} else {
|
||||||
|
gradioApp().getElementById("modal_save").style.display = "none";
|
||||||
|
}
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function negmod(n, m) {
|
||||||
|
return ((n % m) + m) % m;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateOnBackgroundChange() {
|
||||||
|
const modalImage = gradioApp().getElementById("modalImage");
|
||||||
|
if (modalImage && modalImage.offsetParent) {
|
||||||
|
let currentButton = selected_gallery_button();
|
||||||
|
let preview = gradioApp().querySelectorAll('.livePreview > img');
|
||||||
|
if (opts.js_live_preview_in_modal_lightbox && preview.length > 0) {
|
||||||
|
// show preview image if available
|
||||||
|
modalImage.src = preview[preview.length - 1].src;
|
||||||
|
} else if (currentButton?.children?.length > 0 && modalImage.src != currentButton.children[0].src) {
|
||||||
|
modalImage.src = currentButton.children[0].src;
|
||||||
|
if (modalImage.style.display === 'none') {
|
||||||
|
const modal = gradioApp().getElementById("lightboxModal");
|
||||||
|
modal.style.setProperty('background-image', `url(${modalImage.src})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalImageSwitch(offset) {
|
||||||
|
var galleryButtons = all_gallery_buttons();
|
||||||
|
|
||||||
|
if (galleryButtons.length > 1) {
|
||||||
|
var result = selected_gallery_index();
|
||||||
|
|
||||||
|
if (result != -1) {
|
||||||
|
var nextButton = galleryButtons[negmod((result + offset), galleryButtons.length)];
|
||||||
|
nextButton.click();
|
||||||
|
const modalImage = gradioApp().getElementById("modalImage");
|
||||||
|
const modal = gradioApp().getElementById("lightboxModal");
|
||||||
|
modalImage.src = nextButton.children[0].src;
|
||||||
|
if (modalImage.style.display === 'none') {
|
||||||
|
modal.style.setProperty('background-image', `url(${modalImage.src})`);
|
||||||
|
}
|
||||||
|
setTimeout(function() {
|
||||||
|
modal.focus();
|
||||||
|
}, 10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveImage() {
|
||||||
|
const tabTxt2Img = gradioApp().getElementById("tab_txt2img");
|
||||||
|
const tabImg2Img = gradioApp().getElementById("tab_img2img");
|
||||||
|
const saveTxt2Img = "save_txt2img";
|
||||||
|
const saveImg2Img = "save_img2img";
|
||||||
|
if (tabTxt2Img.style.display != "none") {
|
||||||
|
gradioApp().getElementById(saveTxt2Img).click();
|
||||||
|
} else if (tabImg2Img.style.display != "none") {
|
||||||
|
gradioApp().getElementById(saveImg2Img).click();
|
||||||
|
} else {
|
||||||
|
console.error("missing implementation for saving modal of this type");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalSaveImage(event) {
|
||||||
|
saveImage();
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalNextImage(event) {
|
||||||
|
modalImageSwitch(1);
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalPrevImage(event) {
|
||||||
|
modalImageSwitch(-1);
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalKeyHandler(event) {
|
||||||
|
switch (event.key) {
|
||||||
|
case "s":
|
||||||
|
saveImage();
|
||||||
|
break;
|
||||||
|
case "ArrowLeft":
|
||||||
|
modalPrevImage(event);
|
||||||
|
break;
|
||||||
|
case "ArrowRight":
|
||||||
|
modalNextImage(event);
|
||||||
|
break;
|
||||||
|
case "Escape":
|
||||||
|
closeModal();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupImageForLightbox(e) {
|
||||||
|
if (e.dataset.modded) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
e.dataset.modded = true;
|
||||||
|
e.style.cursor = 'pointer';
|
||||||
|
e.style.userSelect = 'none';
|
||||||
|
|
||||||
|
e.addEventListener('mousedown', function(evt) {
|
||||||
|
if (evt.button == 1) {
|
||||||
|
open(evt.target.src);
|
||||||
|
evt.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}, true);
|
||||||
|
|
||||||
|
e.addEventListener('click', function(evt) {
|
||||||
|
if (!opts.js_modal_lightbox || evt.button != 0) return;
|
||||||
|
|
||||||
|
modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initially_zoomed);
|
||||||
|
evt.preventDefault();
|
||||||
|
showModal(evt);
|
||||||
|
}, true);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalZoomSet(modalImage, enable) {
|
||||||
|
if (modalImage) modalImage.classList.toggle('modalImageFullscreen', !!enable);
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalZoomToggle(event) {
|
||||||
|
var modalImage = gradioApp().getElementById("modalImage");
|
||||||
|
modalZoomSet(modalImage, !modalImage.classList.contains('modalImageFullscreen'));
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalLivePreviewToggle(event) {
|
||||||
|
const modalToggleLivePreview = gradioApp().getElementById("modal_toggle_live_preview");
|
||||||
|
opts.js_live_preview_in_modal_lightbox = !opts.js_live_preview_in_modal_lightbox;
|
||||||
|
modalToggleLivePreview.innerHTML = opts.js_live_preview_in_modal_lightbox ? "🗇" : "🗆";
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function modalTileImageToggle(event) {
|
||||||
|
const modalImage = gradioApp().getElementById("modalImage");
|
||||||
|
const modal = gradioApp().getElementById("lightboxModal");
|
||||||
|
const isTiling = modalImage.style.display === 'none';
|
||||||
|
if (isTiling) {
|
||||||
|
modalImage.style.display = 'block';
|
||||||
|
modal.style.setProperty('background-image', 'none');
|
||||||
|
} else {
|
||||||
|
modalImage.style.display = 'none';
|
||||||
|
modal.style.setProperty('background-image', `url(${modalImage.src})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
onAfterUiUpdate(function() {
|
||||||
|
var fullImg_preview = gradioApp().querySelectorAll('.gradio-gallery > div > img');
|
||||||
|
if (fullImg_preview != null) {
|
||||||
|
fullImg_preview.forEach(setupImageForLightbox);
|
||||||
|
}
|
||||||
|
updateOnBackgroundChange();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener("DOMContentLoaded", function() {
|
||||||
|
//const modalFragment = document.createDocumentFragment();
|
||||||
|
const modal = document.createElement('div');
|
||||||
|
modal.onclick = closeModal;
|
||||||
|
modal.id = "lightboxModal";
|
||||||
|
modal.tabIndex = 0;
|
||||||
|
modal.addEventListener('keydown', modalKeyHandler, true);
|
||||||
|
|
||||||
|
const modalControls = document.createElement('div');
|
||||||
|
modalControls.className = 'modalControls gradio-container';
|
||||||
|
modal.append(modalControls);
|
||||||
|
|
||||||
|
const modalZoom = document.createElement('span');
|
||||||
|
modalZoom.className = 'modalZoom cursor';
|
||||||
|
modalZoom.innerHTML = '⤡';
|
||||||
|
modalZoom.addEventListener('click', modalZoomToggle, true);
|
||||||
|
modalZoom.title = "Toggle zoomed view";
|
||||||
|
modalControls.appendChild(modalZoom);
|
||||||
|
|
||||||
|
const modalTileImage = document.createElement('span');
|
||||||
|
modalTileImage.className = 'modalTileImage cursor';
|
||||||
|
modalTileImage.innerHTML = '⊞';
|
||||||
|
modalTileImage.addEventListener('click', modalTileImageToggle, true);
|
||||||
|
modalTileImage.title = "Preview tiling";
|
||||||
|
modalControls.appendChild(modalTileImage);
|
||||||
|
|
||||||
|
const modalSave = document.createElement("span");
|
||||||
|
modalSave.className = "modalSave cursor";
|
||||||
|
modalSave.id = "modal_save";
|
||||||
|
modalSave.innerHTML = "🖫";
|
||||||
|
modalSave.addEventListener("click", modalSaveImage, true);
|
||||||
|
modalSave.title = "Save Image(s)";
|
||||||
|
modalControls.appendChild(modalSave);
|
||||||
|
|
||||||
|
const modalToggleLivePreview = document.createElement('span');
|
||||||
|
modalToggleLivePreview.className = 'modalToggleLivePreview cursor';
|
||||||
|
modalToggleLivePreview.id = "modal_toggle_live_preview";
|
||||||
|
modalToggleLivePreview.innerHTML = "🗆";
|
||||||
|
modalToggleLivePreview.onclick = modalLivePreviewToggle;
|
||||||
|
modalToggleLivePreview.title = "Toggle live preview";
|
||||||
|
modalControls.appendChild(modalToggleLivePreview);
|
||||||
|
|
||||||
|
const modalClose = document.createElement('span');
|
||||||
|
modalClose.className = 'modalClose cursor';
|
||||||
|
modalClose.innerHTML = '×';
|
||||||
|
modalClose.onclick = closeModal;
|
||||||
|
modalClose.title = "Close image viewer";
|
||||||
|
modalControls.appendChild(modalClose);
|
||||||
|
|
||||||
|
const modalImage = document.createElement('img');
|
||||||
|
modalImage.id = 'modalImage';
|
||||||
|
modalImage.onclick = closeModal;
|
||||||
|
modalImage.tabIndex = 0;
|
||||||
|
modalImage.addEventListener('keydown', modalKeyHandler, true);
|
||||||
|
modal.appendChild(modalImage);
|
||||||
|
|
||||||
|
const modalPrev = document.createElement('a');
|
||||||
|
modalPrev.className = 'modalPrev';
|
||||||
|
modalPrev.innerHTML = '❮';
|
||||||
|
modalPrev.tabIndex = 0;
|
||||||
|
modalPrev.addEventListener('click', modalPrevImage, true);
|
||||||
|
modalPrev.addEventListener('keydown', modalKeyHandler, true);
|
||||||
|
modal.appendChild(modalPrev);
|
||||||
|
|
||||||
|
const modalNext = document.createElement('a');
|
||||||
|
modalNext.className = 'modalNext';
|
||||||
|
modalNext.innerHTML = '❯';
|
||||||
|
modalNext.tabIndex = 0;
|
||||||
|
modalNext.addEventListener('click', modalNextImage, true);
|
||||||
|
modalNext.addEventListener('keydown', modalKeyHandler, true);
|
||||||
|
|
||||||
|
modal.appendChild(modalNext);
|
||||||
|
|
||||||
|
try {
|
||||||
|
gradioApp().appendChild(modal);
|
||||||
|
} catch (e) {
|
||||||
|
gradioApp().body.appendChild(modal);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.body.appendChild(modal);
|
||||||
|
|
||||||
|
});
|
63
javascript/imageviewerGamepad.js
Normal file
63
javascript/imageviewerGamepad.js
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
let gamepads = [];
|
||||||
|
|
||||||
|
window.addEventListener('gamepadconnected', (e) => {
|
||||||
|
const index = e.gamepad.index;
|
||||||
|
let isWaiting = false;
|
||||||
|
gamepads[index] = setInterval(async() => {
|
||||||
|
if (!opts.js_modal_lightbox_gamepad || isWaiting) return;
|
||||||
|
const gamepad = navigator.getGamepads()[index];
|
||||||
|
const xValue = gamepad.axes[0];
|
||||||
|
if (xValue <= -0.3) {
|
||||||
|
modalPrevImage(e);
|
||||||
|
isWaiting = true;
|
||||||
|
} else if (xValue >= 0.3) {
|
||||||
|
modalNextImage(e);
|
||||||
|
isWaiting = true;
|
||||||
|
}
|
||||||
|
if (isWaiting) {
|
||||||
|
await sleepUntil(() => {
|
||||||
|
const xValue = navigator.getGamepads()[index].axes[0];
|
||||||
|
if (xValue < 0.3 && xValue > -0.3) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}, opts.js_modal_lightbox_gamepad_repeat);
|
||||||
|
isWaiting = false;
|
||||||
|
}
|
||||||
|
}, 10);
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('gamepaddisconnected', (e) => {
|
||||||
|
clearInterval(gamepads[e.gamepad.index]);
|
||||||
|
});
|
||||||
|
|
||||||
|
/*
|
||||||
|
Primarily for vr controller type pointer devices.
|
||||||
|
I use the wheel event because there's currently no way to do it properly with web xr.
|
||||||
|
*/
|
||||||
|
let isScrolling = false;
|
||||||
|
window.addEventListener('wheel', (e) => {
|
||||||
|
if (!opts.js_modal_lightbox_gamepad || isScrolling) return;
|
||||||
|
isScrolling = true;
|
||||||
|
|
||||||
|
if (e.deltaX <= -0.6) {
|
||||||
|
modalPrevImage(e);
|
||||||
|
} else if (e.deltaX >= 0.6) {
|
||||||
|
modalNextImage(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
isScrolling = false;
|
||||||
|
}, opts.js_modal_lightbox_gamepad_repeat);
|
||||||
|
});
|
||||||
|
|
||||||
|
function sleepUntil(f, timeout) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const timeStart = new Date();
|
||||||
|
const wait = setInterval(function() {
|
||||||
|
if (f() || new Date() - timeStart > timeout) {
|
||||||
|
clearInterval(wait);
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
}, 20);
|
||||||
|
});
|
||||||
|
}
|
68
javascript/inputAccordion.js
Normal file
68
javascript/inputAccordion.js
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
function inputAccordionChecked(id, checked) {
|
||||||
|
var accordion = gradioApp().getElementById(id);
|
||||||
|
accordion.visibleCheckbox.checked = checked;
|
||||||
|
accordion.onVisibleCheckboxChange();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupAccordion(accordion) {
|
||||||
|
var labelWrap = accordion.querySelector('.label-wrap');
|
||||||
|
var gradioCheckbox = gradioApp().querySelector('#' + accordion.id + "-checkbox input");
|
||||||
|
var extra = gradioApp().querySelector('#' + accordion.id + "-extra");
|
||||||
|
var span = labelWrap.querySelector('span');
|
||||||
|
var linked = true;
|
||||||
|
|
||||||
|
var isOpen = function() {
|
||||||
|
return labelWrap.classList.contains('open');
|
||||||
|
};
|
||||||
|
|
||||||
|
var observerAccordionOpen = new MutationObserver(function(mutations) {
|
||||||
|
mutations.forEach(function(mutationRecord) {
|
||||||
|
accordion.classList.toggle('input-accordion-open', isOpen());
|
||||||
|
|
||||||
|
if (linked) {
|
||||||
|
accordion.visibleCheckbox.checked = isOpen();
|
||||||
|
accordion.onVisibleCheckboxChange();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
observerAccordionOpen.observe(labelWrap, {attributes: true, attributeFilter: ['class']});
|
||||||
|
|
||||||
|
if (extra) {
|
||||||
|
labelWrap.insertBefore(extra, labelWrap.lastElementChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
accordion.onChecked = function(checked) {
|
||||||
|
if (isOpen() != checked) {
|
||||||
|
labelWrap.click();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var visibleCheckbox = document.createElement('INPUT');
|
||||||
|
visibleCheckbox.type = 'checkbox';
|
||||||
|
visibleCheckbox.checked = isOpen();
|
||||||
|
visibleCheckbox.id = accordion.id + "-visible-checkbox";
|
||||||
|
visibleCheckbox.className = gradioCheckbox.className + " input-accordion-checkbox";
|
||||||
|
span.insertBefore(visibleCheckbox, span.firstChild);
|
||||||
|
|
||||||
|
accordion.visibleCheckbox = visibleCheckbox;
|
||||||
|
accordion.onVisibleCheckboxChange = function() {
|
||||||
|
if (linked && isOpen() != visibleCheckbox.checked) {
|
||||||
|
labelWrap.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
gradioCheckbox.checked = visibleCheckbox.checked;
|
||||||
|
updateInput(gradioCheckbox);
|
||||||
|
};
|
||||||
|
|
||||||
|
visibleCheckbox.addEventListener('click', function(event) {
|
||||||
|
linked = false;
|
||||||
|
event.stopPropagation();
|
||||||
|
});
|
||||||
|
visibleCheckbox.addEventListener('input', accordion.onVisibleCheckboxChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
for (var accordion of gradioApp().querySelectorAll('.input-accordion')) {
|
||||||
|
setupAccordion(accordion);
|
||||||
|
}
|
||||||
|
});
|
26
javascript/localStorage.js
Normal file
26
javascript/localStorage.js
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
|
||||||
|
function localSet(k, v) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(k, v);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to save ${k} to localStorage: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function localGet(k, def) {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(k);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to load ${k} from localStorage: ${e}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
|
||||||
|
function localRemove(k) {
|
||||||
|
try {
|
||||||
|
return localStorage.removeItem(k);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to remove ${k} from localStorage: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
205
javascript/localization.js
Normal file
205
javascript/localization.js
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
|
||||||
|
// localization = {} -- the dict with translations is created by the backend
|
||||||
|
|
||||||
|
var ignore_ids_for_localization = {
|
||||||
|
setting_sd_hypernetwork: 'OPTION',
|
||||||
|
setting_sd_model_checkpoint: 'OPTION',
|
||||||
|
modelmerger_primary_model_name: 'OPTION',
|
||||||
|
modelmerger_secondary_model_name: 'OPTION',
|
||||||
|
modelmerger_tertiary_model_name: 'OPTION',
|
||||||
|
train_embedding: 'OPTION',
|
||||||
|
train_hypernetwork: 'OPTION',
|
||||||
|
txt2img_styles: 'OPTION',
|
||||||
|
img2img_styles: 'OPTION',
|
||||||
|
setting_random_artist_categories: 'OPTION',
|
||||||
|
setting_face_restoration_model: 'OPTION',
|
||||||
|
setting_realesrgan_enabled_models: 'OPTION',
|
||||||
|
extras_upscaler_1: 'OPTION',
|
||||||
|
extras_upscaler_2: 'OPTION',
|
||||||
|
};
|
||||||
|
|
||||||
|
var re_num = /^[.\d]+$/;
|
||||||
|
var re_emoji = /[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]/u;
|
||||||
|
|
||||||
|
var original_lines = {};
|
||||||
|
var translated_lines = {};
|
||||||
|
|
||||||
|
function hasLocalization() {
|
||||||
|
return window.localization && Object.keys(window.localization).length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function textNodesUnder(el) {
|
||||||
|
var n, a = [], walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false);
|
||||||
|
while ((n = walk.nextNode())) a.push(n);
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
function canBeTranslated(node, text) {
|
||||||
|
if (!text) return false;
|
||||||
|
if (!node.parentElement) return false;
|
||||||
|
|
||||||
|
var parentType = node.parentElement.nodeName;
|
||||||
|
if (parentType == 'SCRIPT' || parentType == 'STYLE' || parentType == 'TEXTAREA') return false;
|
||||||
|
|
||||||
|
if (parentType == 'OPTION' || parentType == 'SPAN') {
|
||||||
|
var pnode = node;
|
||||||
|
for (var level = 0; level < 4; level++) {
|
||||||
|
pnode = pnode.parentElement;
|
||||||
|
if (!pnode) break;
|
||||||
|
|
||||||
|
if (ignore_ids_for_localization[pnode.id] == parentType) return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (re_num.test(text)) return false;
|
||||||
|
if (re_emoji.test(text)) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTranslation(text) {
|
||||||
|
if (!text) return undefined;
|
||||||
|
|
||||||
|
if (translated_lines[text] === undefined) {
|
||||||
|
original_lines[text] = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
var tl = localization[text];
|
||||||
|
if (tl !== undefined) {
|
||||||
|
translated_lines[tl] = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return tl;
|
||||||
|
}
|
||||||
|
|
||||||
|
function processTextNode(node) {
|
||||||
|
var text = node.textContent.trim();
|
||||||
|
|
||||||
|
if (!canBeTranslated(node, text)) return;
|
||||||
|
|
||||||
|
var tl = getTranslation(text);
|
||||||
|
if (tl !== undefined) {
|
||||||
|
node.textContent = tl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function processNode(node) {
|
||||||
|
if (node.nodeType == 3) {
|
||||||
|
processTextNode(node);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.title) {
|
||||||
|
let tl = getTranslation(node.title);
|
||||||
|
if (tl !== undefined) {
|
||||||
|
node.title = tl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.placeholder) {
|
||||||
|
let tl = getTranslation(node.placeholder);
|
||||||
|
if (tl !== undefined) {
|
||||||
|
node.placeholder = tl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
textNodesUnder(node).forEach(function(node) {
|
||||||
|
processTextNode(node);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function localizeWholePage() {
|
||||||
|
processNode(gradioApp());
|
||||||
|
|
||||||
|
function elem(comp) {
|
||||||
|
var elem_id = comp.props.elem_id ? comp.props.elem_id : "component-" + comp.id;
|
||||||
|
return gradioApp().getElementById(elem_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var comp of window.gradio_config.components) {
|
||||||
|
if (comp.props.webui_tooltip) {
|
||||||
|
let e = elem(comp);
|
||||||
|
|
||||||
|
let tl = e ? getTranslation(e.title) : undefined;
|
||||||
|
if (tl !== undefined) {
|
||||||
|
e.title = tl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (comp.props.placeholder) {
|
||||||
|
let e = elem(comp);
|
||||||
|
let textbox = e ? e.querySelector('[placeholder]') : null;
|
||||||
|
|
||||||
|
let tl = textbox ? getTranslation(textbox.placeholder) : undefined;
|
||||||
|
if (tl !== undefined) {
|
||||||
|
textbox.placeholder = tl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dumpTranslations() {
|
||||||
|
if (!hasLocalization()) {
|
||||||
|
// If we don't have any localization,
|
||||||
|
// we will not have traversed the app to find
|
||||||
|
// original_lines, so do that now.
|
||||||
|
localizeWholePage();
|
||||||
|
}
|
||||||
|
var dumped = {};
|
||||||
|
if (localization.rtl) {
|
||||||
|
dumped.rtl = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const text in original_lines) {
|
||||||
|
if (dumped[text] !== undefined) continue;
|
||||||
|
dumped[text] = localization[text] || text;
|
||||||
|
}
|
||||||
|
|
||||||
|
return dumped;
|
||||||
|
}
|
||||||
|
|
||||||
|
function download_localization() {
|
||||||
|
var text = JSON.stringify(dumpTranslations(), null, 4);
|
||||||
|
|
||||||
|
var element = document.createElement('a');
|
||||||
|
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
|
||||||
|
element.setAttribute('download', "localization.json");
|
||||||
|
element.style.display = 'none';
|
||||||
|
document.body.appendChild(element);
|
||||||
|
|
||||||
|
element.click();
|
||||||
|
|
||||||
|
document.body.removeChild(element);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("DOMContentLoaded", function() {
|
||||||
|
if (!hasLocalization()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
onUiUpdate(function(m) {
|
||||||
|
m.forEach(function(mutation) {
|
||||||
|
mutation.addedNodes.forEach(function(node) {
|
||||||
|
processNode(node);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
localizeWholePage();
|
||||||
|
|
||||||
|
if (localization.rtl) { // if the language is from right to left,
|
||||||
|
(new MutationObserver((mutations, observer) => { // wait for the style to load
|
||||||
|
mutations.forEach(mutation => {
|
||||||
|
mutation.addedNodes.forEach(node => {
|
||||||
|
if (node.tagName === 'STYLE') {
|
||||||
|
observer.disconnect();
|
||||||
|
|
||||||
|
for (const x of node.sheet.rules) { // find all rtl media rules
|
||||||
|
if (Array.from(x.media || []).includes('rtl')) {
|
||||||
|
x.media.appendMedium('all'); // enable them
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})).observe(gradioApp(), {childList: true});
|
||||||
|
}
|
||||||
|
});
|
53
javascript/notification.js
Normal file
53
javascript/notification.js
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
// Monitors the gallery and sends a browser notification when the leading image is new.
|
||||||
|
|
||||||
|
let lastHeadImg = null;
|
||||||
|
|
||||||
|
let notificationButton = null;
|
||||||
|
|
||||||
|
onAfterUiUpdate(function() {
|
||||||
|
if (notificationButton == null) {
|
||||||
|
notificationButton = gradioApp().getElementById('request_notifications');
|
||||||
|
|
||||||
|
if (notificationButton != null) {
|
||||||
|
notificationButton.addEventListener('click', () => {
|
||||||
|
void Notification.requestPermission();
|
||||||
|
}, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const galleryPreviews = gradioApp().querySelectorAll('div[id^="tab_"] div[id$="_results"] .thumbnail-item > img');
|
||||||
|
|
||||||
|
if (galleryPreviews == null) return;
|
||||||
|
|
||||||
|
const headImg = galleryPreviews[0]?.src;
|
||||||
|
|
||||||
|
if (headImg == null || headImg == lastHeadImg) return;
|
||||||
|
|
||||||
|
lastHeadImg = headImg;
|
||||||
|
|
||||||
|
// play notification sound if available
|
||||||
|
const notificationAudio = gradioApp().querySelector('#audio_notification audio');
|
||||||
|
if (notificationAudio) {
|
||||||
|
notificationAudio.volume = opts.notification_volume / 100.0 || 1.0;
|
||||||
|
notificationAudio.play();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.hasFocus()) return;
|
||||||
|
|
||||||
|
// Multiple copies of the images are in the DOM when one is selected. Dedup with a Set to get the real number generated.
|
||||||
|
const imgs = new Set(Array.from(galleryPreviews).map(img => img.src));
|
||||||
|
|
||||||
|
const notification = new Notification(
|
||||||
|
'Stable Diffusion',
|
||||||
|
{
|
||||||
|
body: `Generated ${imgs.size > 1 ? imgs.size - opts.return_grid : 1} image${imgs.size > 1 ? 's' : ''}`,
|
||||||
|
icon: headImg,
|
||||||
|
image: headImg,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
notification.onclick = function(_) {
|
||||||
|
parent.focus();
|
||||||
|
this.close();
|
||||||
|
};
|
||||||
|
});
|
174
javascript/profilerVisualization.js
Normal file
174
javascript/profilerVisualization.js
Normal file
@ -0,0 +1,174 @@
|
|||||||
|
|
||||||
|
function createRow(table, cellName, items) {
|
||||||
|
var tr = document.createElement('tr');
|
||||||
|
var res = [];
|
||||||
|
|
||||||
|
items.forEach(function(x, i) {
|
||||||
|
if (x === undefined) {
|
||||||
|
res.push(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var td = document.createElement(cellName);
|
||||||
|
td.textContent = x;
|
||||||
|
tr.appendChild(td);
|
||||||
|
res.push(td);
|
||||||
|
|
||||||
|
var colspan = 1;
|
||||||
|
for (var n = i + 1; n < items.length; n++) {
|
||||||
|
if (items[n] !== undefined) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
colspan += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (colspan > 1) {
|
||||||
|
td.colSpan = colspan;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
table.appendChild(tr);
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createVisualizationTable(data, cutoff = 0, sort = "") {
|
||||||
|
var table = document.createElement('table');
|
||||||
|
table.className = 'popup-table';
|
||||||
|
|
||||||
|
var keys = Object.keys(data);
|
||||||
|
if (sort === "number") {
|
||||||
|
keys = keys.sort(function(a, b) {
|
||||||
|
return data[b] - data[a];
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
keys = keys.sort();
|
||||||
|
}
|
||||||
|
var items = keys.map(function(x) {
|
||||||
|
return {key: x, parts: x.split('/'), value: data[x]};
|
||||||
|
});
|
||||||
|
var maxLength = items.reduce(function(a, b) {
|
||||||
|
return Math.max(a, b.parts.length);
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
var cols = createRow(
|
||||||
|
table,
|
||||||
|
'th',
|
||||||
|
[
|
||||||
|
cutoff === 0 ? 'key' : 'record',
|
||||||
|
cutoff === 0 ? 'value' : 'seconds'
|
||||||
|
]
|
||||||
|
);
|
||||||
|
cols[0].colSpan = maxLength;
|
||||||
|
|
||||||
|
function arraysEqual(a, b) {
|
||||||
|
return !(a < b || b < a);
|
||||||
|
}
|
||||||
|
|
||||||
|
var addLevel = function(level, parent, hide) {
|
||||||
|
var matching = items.filter(function(x) {
|
||||||
|
return x.parts[level] && !x.parts[level + 1] && arraysEqual(x.parts.slice(0, level), parent);
|
||||||
|
});
|
||||||
|
if (sort === "number") {
|
||||||
|
matching = matching.sort(function(a, b) {
|
||||||
|
return b.value - a.value;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
matching = matching.sort();
|
||||||
|
}
|
||||||
|
var othersTime = 0;
|
||||||
|
var othersList = [];
|
||||||
|
var othersRows = [];
|
||||||
|
var childrenRows = [];
|
||||||
|
matching.forEach(function(x) {
|
||||||
|
var visible = (cutoff === 0 && !hide) || (x.value >= cutoff && !hide);
|
||||||
|
|
||||||
|
var cells = [];
|
||||||
|
for (var i = 0; i < maxLength; i++) {
|
||||||
|
cells.push(x.parts[i]);
|
||||||
|
}
|
||||||
|
cells.push(cutoff === 0 ? x.value : x.value.toFixed(3));
|
||||||
|
var cols = createRow(table, 'td', cells);
|
||||||
|
for (i = 0; i < level; i++) {
|
||||||
|
cols[i].className = 'muted';
|
||||||
|
}
|
||||||
|
|
||||||
|
var tr = cols[0].parentNode;
|
||||||
|
if (!visible) {
|
||||||
|
tr.classList.add("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cutoff === 0 || x.value >= cutoff) {
|
||||||
|
childrenRows.push(tr);
|
||||||
|
} else {
|
||||||
|
othersTime += x.value;
|
||||||
|
othersList.push(x.parts[level]);
|
||||||
|
othersRows.push(tr);
|
||||||
|
}
|
||||||
|
|
||||||
|
var children = addLevel(level + 1, parent.concat([x.parts[level]]), true);
|
||||||
|
if (children.length > 0) {
|
||||||
|
var cell = cols[level];
|
||||||
|
var onclick = function() {
|
||||||
|
cell.classList.remove("link");
|
||||||
|
cell.removeEventListener("click", onclick);
|
||||||
|
children.forEach(function(x) {
|
||||||
|
x.classList.remove("hidden");
|
||||||
|
});
|
||||||
|
};
|
||||||
|
cell.classList.add("link");
|
||||||
|
cell.addEventListener("click", onclick);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (othersTime > 0) {
|
||||||
|
var cells = [];
|
||||||
|
for (var i = 0; i < maxLength; i++) {
|
||||||
|
cells.push(parent[i]);
|
||||||
|
}
|
||||||
|
cells.push(othersTime.toFixed(3));
|
||||||
|
cells[level] = 'others';
|
||||||
|
var cols = createRow(table, 'td', cells);
|
||||||
|
for (i = 0; i < level; i++) {
|
||||||
|
cols[i].className = 'muted';
|
||||||
|
}
|
||||||
|
|
||||||
|
var cell = cols[level];
|
||||||
|
var tr = cell.parentNode;
|
||||||
|
var onclick = function() {
|
||||||
|
tr.classList.add("hidden");
|
||||||
|
cell.classList.remove("link");
|
||||||
|
cell.removeEventListener("click", onclick);
|
||||||
|
othersRows.forEach(function(x) {
|
||||||
|
x.classList.remove("hidden");
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
cell.title = othersList.join(", ");
|
||||||
|
cell.classList.add("link");
|
||||||
|
cell.addEventListener("click", onclick);
|
||||||
|
|
||||||
|
if (hide) {
|
||||||
|
tr.classList.add("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
childrenRows.push(tr);
|
||||||
|
}
|
||||||
|
|
||||||
|
return childrenRows;
|
||||||
|
};
|
||||||
|
|
||||||
|
addLevel(0, []);
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showProfile(path, cutoff = 0.05) {
|
||||||
|
requestGet(path, {}, function(data) {
|
||||||
|
data.records['total'] = data.total;
|
||||||
|
const table = createVisualizationTable(data.records, cutoff, "number");
|
||||||
|
popup(table);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
215
javascript/progressbar.js
Normal file
215
javascript/progressbar.js
Normal file
@ -0,0 +1,215 @@
|
|||||||
|
// code related to showing and updating progressbar shown as the image is being made
|
||||||
|
|
||||||
|
function rememberGallerySelection() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
function getGallerySelectedIndex() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
function request(url, data, handler, errorHandler) {
|
||||||
|
var xhr = new XMLHttpRequest();
|
||||||
|
xhr.open("POST", url, true);
|
||||||
|
xhr.setRequestHeader("Content-Type", "application/json");
|
||||||
|
xhr.onreadystatechange = function() {
|
||||||
|
if (xhr.readyState === 4) {
|
||||||
|
if (xhr.status === 200) {
|
||||||
|
try {
|
||||||
|
var js = JSON.parse(xhr.responseText);
|
||||||
|
handler(js);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
errorHandler();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
errorHandler();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var js = JSON.stringify(data);
|
||||||
|
xhr.send(js);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pad2(x) {
|
||||||
|
return x < 10 ? '0' + x : x;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(secs) {
|
||||||
|
if (secs > 3600) {
|
||||||
|
return pad2(Math.floor(secs / 60 / 60)) + ":" + pad2(Math.floor(secs / 60) % 60) + ":" + pad2(Math.floor(secs) % 60);
|
||||||
|
} else if (secs > 60) {
|
||||||
|
return pad2(Math.floor(secs / 60)) + ":" + pad2(Math.floor(secs) % 60);
|
||||||
|
} else {
|
||||||
|
return Math.floor(secs) + "s";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
var originalAppTitle = undefined;
|
||||||
|
|
||||||
|
onUiLoaded(function() {
|
||||||
|
originalAppTitle = document.title;
|
||||||
|
});
|
||||||
|
|
||||||
|
function setTitle(progress) {
|
||||||
|
var title = originalAppTitle;
|
||||||
|
|
||||||
|
if (opts.show_progress_in_title && progress) {
|
||||||
|
title = '[' + progress.trim() + '] ' + title;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.title != title) {
|
||||||
|
document.title = title;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function randomId() {
|
||||||
|
return "task(" + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7) + Math.random().toString(36).slice(2, 7) + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
// starts sending progress requests to "/internal/progress" uri, creating progressbar above progressbarContainer element and
|
||||||
|
// preview inside gallery element. Cleans up all created stuff when the task is over and calls atEnd.
|
||||||
|
// calls onProgress every time there is a progress update
|
||||||
|
function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgress, inactivityTimeout = 40) {
|
||||||
|
var dateStart = new Date();
|
||||||
|
var wasEverActive = false;
|
||||||
|
var parentProgressbar = progressbarContainer.parentNode;
|
||||||
|
var wakeLock = null;
|
||||||
|
|
||||||
|
var requestWakeLock = async function() {
|
||||||
|
if (!opts.prevent_screen_sleep_during_generation || wakeLock) return;
|
||||||
|
try {
|
||||||
|
wakeLock = await navigator.wakeLock.request('screen');
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Wake Lock is not supported.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var releaseWakeLock = async function() {
|
||||||
|
if (!opts.prevent_screen_sleep_during_generation || !wakeLock) return;
|
||||||
|
try {
|
||||||
|
await wakeLock.release();
|
||||||
|
wakeLock = null;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Wake Lock release failed', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var divProgress = document.createElement('div');
|
||||||
|
divProgress.className = 'progressDiv';
|
||||||
|
divProgress.style.display = opts.show_progressbar ? "block" : "none";
|
||||||
|
var divInner = document.createElement('div');
|
||||||
|
divInner.className = 'progress';
|
||||||
|
|
||||||
|
divProgress.appendChild(divInner);
|
||||||
|
parentProgressbar.insertBefore(divProgress, progressbarContainer);
|
||||||
|
|
||||||
|
var livePreview = null;
|
||||||
|
|
||||||
|
var removeProgressBar = function() {
|
||||||
|
releaseWakeLock();
|
||||||
|
if (!divProgress) return;
|
||||||
|
|
||||||
|
setTitle("");
|
||||||
|
parentProgressbar.removeChild(divProgress);
|
||||||
|
if (gallery && livePreview) gallery.removeChild(livePreview);
|
||||||
|
atEnd();
|
||||||
|
|
||||||
|
divProgress = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
var funProgress = function(id_task) {
|
||||||
|
requestWakeLock();
|
||||||
|
request("./internal/progress", {id_task: id_task, live_preview: false}, function(res) {
|
||||||
|
if (res.completed) {
|
||||||
|
removeProgressBar();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let progressText = "";
|
||||||
|
|
||||||
|
divInner.style.width = ((res.progress || 0) * 100.0) + '%';
|
||||||
|
divInner.style.background = res.progress ? "" : "transparent";
|
||||||
|
|
||||||
|
if (res.progress > 0) {
|
||||||
|
progressText = ((res.progress || 0) * 100.0).toFixed(0) + '%';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.eta) {
|
||||||
|
progressText += " ETA: " + formatTime(res.eta);
|
||||||
|
}
|
||||||
|
|
||||||
|
setTitle(progressText);
|
||||||
|
|
||||||
|
if (res.textinfo && res.textinfo.indexOf("\n") == -1) {
|
||||||
|
progressText = res.textinfo + " " + progressText;
|
||||||
|
}
|
||||||
|
|
||||||
|
divInner.textContent = progressText;
|
||||||
|
|
||||||
|
var elapsedFromStart = (new Date() - dateStart) / 1000;
|
||||||
|
|
||||||
|
if (res.active) wasEverActive = true;
|
||||||
|
|
||||||
|
if (!res.active && wasEverActive) {
|
||||||
|
removeProgressBar();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (elapsedFromStart > inactivityTimeout && !res.queued && !res.active) {
|
||||||
|
removeProgressBar();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (onProgress) {
|
||||||
|
onProgress(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
funProgress(id_task, res.id_live_preview);
|
||||||
|
}, opts.live_preview_refresh_period || 500);
|
||||||
|
}, function() {
|
||||||
|
removeProgressBar();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
var funLivePreview = function(id_task, id_live_preview) {
|
||||||
|
request("./internal/progress", {id_task: id_task, id_live_preview: id_live_preview}, function(res) {
|
||||||
|
if (!divProgress) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.live_preview && gallery) {
|
||||||
|
var img = new Image();
|
||||||
|
img.onload = function() {
|
||||||
|
if (!livePreview) {
|
||||||
|
livePreview = document.createElement('div');
|
||||||
|
livePreview.className = 'livePreview';
|
||||||
|
gallery.insertBefore(livePreview, gallery.firstElementChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
livePreview.appendChild(img);
|
||||||
|
if (livePreview.childElementCount > 2) {
|
||||||
|
livePreview.removeChild(livePreview.firstElementChild);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
img.src = res.live_preview;
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
funLivePreview(id_task, res.id_live_preview);
|
||||||
|
}, opts.live_preview_refresh_period || 500);
|
||||||
|
}, function() {
|
||||||
|
removeProgressBar();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
funProgress(id_task, 0);
|
||||||
|
|
||||||
|
if (gallery) {
|
||||||
|
funLivePreview(id_task, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user