diff --git a/.gitattributes b/.gitattributes index c7d9f3332a950355d5a77d85000f05e6f45435ea..26e7e7115777704e43009452c20f56a15912ea38 100644 --- a/.gitattributes +++ b/.gitattributes @@ -32,3 +32,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +Auto-Photoshop-StableDiffusion-Plugin/docs/heal_brush.gif filter=lfs diff=lfs merge=lfs -text +Auto-Photoshop-StableDiffusion-Plugin/docs/inpainting.gif filter=lfs diff=lfs merge=lfs -text +Auto-Photoshop-StableDiffusion-Plugin/docs/outpainting.gif filter=lfs diff=lfs merge=lfs -text +Auto-Photoshop-StableDiffusion-Plugin/docs/prompt_shortcut.gif filter=lfs diff=lfs merge=lfs -text +Stable-Diffusion-Webui-Civitai-Helper/img/all_in_one.png filter=lfs diff=lfs merge=lfs -text +posex/image/sample-webui2.jpg filter=lfs diff=lfs merge=lfs -text +posex/image/sample-webui2.png filter=lfs diff=lfs merge=lfs -text +sd_feed/assets/pinterest.png filter=lfs diff=lfs merge=lfs -text diff --git a/Auto-Photoshop-StableDiffusion-Plugin/.github/workflows/publish_docs_to_wiki b/Auto-Photoshop-StableDiffusion-Plugin/.github/workflows/publish_docs_to_wiki new file mode 100644 index 0000000000000000000000000000000000000000..aef8c2ac2d5203c26e2c8a351528d0991e6e1138 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/.github/workflows/publish_docs_to_wiki @@ -0,0 +1,43 @@ +name: Publish docs to Wiki + +# Trigger this action only if there are changes pushed to the docs/** directory under the main branch +on: + push: + branches: + - main # This can be changed to any branch of your preference + +env: + USER_TOKEN: ${{ secrets.WIKI_ACTION_TOKEN }} # This is the repository secret + USER_NAME: AbdullahAlfaraj # Enter the username of your (bot) account + USER_EMAIL: 7842232+AbdullahAlfaraj@users.noreply.github.com # Enter the e-mail of your (bot) account + OWNER: ${{ github.event.repository.owner.name }} # This is the repository owner + REPOSITORY_NAME: ${{ github.event.repository.name }} # This is the repository name + +jobs: + publish_docs_to_wiki: + name: Publish docs to Wiki + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + # 1. Create folder named `tmp_wiki` + # 2. Initialize Git + # 3. Pull old Wiki content + - name: Pull content from wiki + run: | + mkdir tmp_wiki + cd tmp_wiki + git init + git config user.name $USER_NAME + git config user.email $USER_EMAIL + git pull https://$USER_TOKEN@github.com/$OWNER/$REPOSITORY_NAME.wiki.git + # 4. Synchronize differences between `docs` & `tmp_wiki` + # 5. Push new Wiki content + - name: Push content to wiki + run: | + rsync -av --delete docs/ tmp_wiki/ --exclude .git + cd tmp_wiki + git add . + git commit -m "Update Wiki content" + git push -f --set-upstream https://$USER_TOKEN@github.com/$OWNER/$REPOSITORY_NAME.wiki.git master diff --git a/Auto-Photoshop-StableDiffusion-Plugin/.github/workflows/wiki-sync-action.yml b/Auto-Photoshop-StableDiffusion-Plugin/.github/workflows/wiki-sync-action.yml new file mode 100644 index 0000000000000000000000000000000000000000..672f18d4555d6b58d30241522ac7a61a1690b022 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/.github/workflows/wiki-sync-action.yml @@ -0,0 +1,29 @@ +on: + push: + branches: + - master + pull_request: + branches: + - master +name: Wiki Sync +jobs: + update-wiki: + runs-on: ubuntu-latest + steps: +# - name: wiki-safe +# run: | +# git config --global --add safe.directory /wiki + - uses: actions/checkout@master + - name: Sync Wiki +# uses: joeizzard/action-wiki-sync@master + uses: AbdullahAlfaraj/ghaction-wiki-sync@master + + + with: + username: AbdullahAlfaraj + access_token: ${{ secrets.WIKI_ACTION_TOKEN }} + wiki_folder: docs + commit_username: 'AbdullahAlfaraj ' + commit_email: '7842232+AbdullahAlfaraj@users.noreply.github.com' + commit_message: 'action: wiki sync' + diff --git a/Auto-Photoshop-StableDiffusion-Plugin/.github/workflows/wiki_action_2 b/Auto-Photoshop-StableDiffusion-Plugin/.github/workflows/wiki_action_2 new file mode 100644 index 0000000000000000000000000000000000000000..4d741935b5aa3b9c4d1bea067ed5d723157fa7ac --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/.github/workflows/wiki_action_2 @@ -0,0 +1,23 @@ +name: Deploy Wiki + +on: + push: + branches: + # And only on master branch + - master + +jobs: + deploy-wiki: + runs-on: ubuntu-latest + steps: + + - name: Push Wiki Changes + uses: Andrew-Chen-Wang/github-wiki-action@v3 + env: + # Make sure you have that / at the end. We use rsync + # WIKI_DIR's default is wiki/ + WIKI_DIR: docs/ + GH_TOKEN: ${{ secrets.WIKI_ACTION_TOKEN }} + GH_MAIL: 7842232+AbdullahAlfaraj@users.noreply.github.com + GH_NAME: ${{ github.repository_owner }} + EXCLUDED_FILES: "a/ b.md" diff --git a/Auto-Photoshop-StableDiffusion-Plugin/.gitignore b/Auto-Photoshop-StableDiffusion-Plugin/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..eb85a81c800ce528fa87cd0869ebd743080bf184 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/.gitignore @@ -0,0 +1,34 @@ +**/__pycache__ +env +/server_env +/tmp +/outputs +/log +/.idea +/.vscode +/.git +/.github +test.bat +server/python_server/output/* +server/python_server/init_images/* +node_modules/ +server/python_server/prompt_shortcut.json +experimental/ +start_server.sh +start_server.bat +*.ccx +expanded_mask.png +original_mask.png +/config + +/jimp/* +!/jimp/browser/ +/jimp/browser/examples +/jimp/browser/*.md +/jimp/browser/*.editorconfig +/jimp/browser/lib/jimp.js + + +# comments when packaging: +ultimate_sd_upscaler/dist/*LICENSE.txt +ultimate_sd_upscaler/dist/*.bundle.js diff --git a/Auto-Photoshop-StableDiffusion-Plugin/.prettierignore b/Auto-Photoshop-StableDiffusion-Plugin/.prettierignore new file mode 100644 index 0000000000000000000000000000000000000000..ac336ae1a550ee74a03fac92ec1c2777afd8bb3b --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/.prettierignore @@ -0,0 +1,3 @@ +server/python_server/output/* +*.md +manifest.json \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/.prettierrc b/Auto-Photoshop-StableDiffusion-Plugin/.prettierrc new file mode 100644 index 0000000000000000000000000000000000000000..e74ed9ff357859b4fe43a022c49f14813553c400 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/.prettierrc @@ -0,0 +1,6 @@ +{ + "trailingComma": "es5", + "tabWidth": 4, + "semi": false, + "singleQuote": true +} diff --git a/Auto-Photoshop-StableDiffusion-Plugin/LICENSE.md b/Auto-Photoshop-StableDiffusion-Plugin/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..40defe74a871b99597dfdd88eeafad14daa03b4e --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Abdullah Alfaraj + +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. diff --git a/Auto-Photoshop-StableDiffusion-Plugin/README.md b/Auto-Photoshop-StableDiffusion-Plugin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f86edd44c538fe1878948c857e568a313d64d35a --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/README.md @@ -0,0 +1,202 @@ + + +# Auto-Photoshop-StableDiffusion-Plugin +[![Become a Patron!](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/AbdullahAlfaraj) +[![discord badge]][discord link] + +[discord badge]: https://flat.badgen.net/discord/members/3mVEtrddXJ +[discord link]: https://discord.gg/3mVEtrddXJ + + + +With Auto-Photoshop-StableDiffusion-Plugin, you can directly use the capabilities of Automatic1111 Stable Diffusion in Photoshop without switching between programs. This allows you to easily use Stable Diffusion AI in a familiar environment. You can edit your Stable Diffusion image with all your favorite tools and save it right in Photoshop. + +# Table of Contents +- [Auto-Photoshop-StableDiffusion-Plugin](#auto-photoshop-stablediffusion-plugin) +- [Table of Contents](#table-of-contents) +- [Demo:](#demo) +- [Support Us On Patreon](#support-us-on-patreon) +- [How to Install](#how-to-install) + - [Method 1: One Click Installer](#method-1-one-click-installer) + - [Method 2: The Unzip Method](#method-2-the-unzip-method) + - [Method 3: The UXP Method (for Developers/Programmers Only)](#method-3-the-uxp-method-instruction-for-developers) + +- [FAQ and Known Issues](#faq-and-known-issues) + - [What Photoshop version do I need to run the plugin?](#what-photoshop-version-do-i-need-to-run-the-plugin) + - [Path Doesn't Exist](#path-doesnt-exist) + - [Plugin Load Failed](#plugin-load-failed) + - [No application are connected to the service](#no-application-are-connected-to-the-service) + - [Load command failed in App with ID PS and Version X.X.X](#load-command-failed-in-app-with-id-ps-and-version-xxx) + - [Exception in ASGI application / Expecting value: line 1 column 1](#exception-in-asgi-application--expecting-value-line-1-column-1) + - [No Generations and Plugin Server doesn't send messages. (Remote setup)](#no-generations-and-plugin-server-doesnt-send-messages-remote-setup) + +- [No GPU Options](#no-gpu-options) + - [Stable Horde](#stable-horde) + - [Colab](#colab) + +# Support Us On Patreon: +By supporting us on [Patreon](https://www.patreon.com/AbdullahAlfaraj), you’ll help us continue to develop and improve the Auto-Photoshop-StableDiffusion-Plugin, making it even easier for you to use Stable Diffusion AI in a familiar environment. As a supporter, you’ll have the opportunity to provide feedback and suggestions for future development. Plus, you’ll get early access to new features and tutorials, as well as exclusive art tutorials and tips from a professional artist. We’re passionate about making AI approachable to artists and with your help, we can continue to do just that. +# Auto-Photoshop-SD Backers and Sponsors: +**💎 Diamond:** +| [![Ronny Khalil](https://images.weserv.nl/?url=https://raw.githubusercontent.com/AbdullahAlfaraj/Auto-Photoshop-StableDiffusion-Plugin/206b56c911f67ede3ca3a934d0bce8c1d68a2113/docs/profile_image/A934E4F0-7778-47E9-A395-531BFF2E61F1_1_105_c.jpeg&h=80&w=80&fit=cover&mask=circle&maxage=7d)](https://ronnykhalil.com/) | ![zachary](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=zachary) | ![Razvan Matei](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Razvan+Matei) +|:---:|:---:|:---:| +| [Ronny Khalil](https://ronnykhalil.com/) | zachary | Razvan Matei + +**🥇 Gold:** +| ![Alex ](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Alex+) | ![Florin-Alexandru Ilinescu](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Florin-Alexandru+Ilinescu) | ![Robin Edwards](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Robin+Edwards) | ![Danny Sahagun](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Danny+Sahagun) +|:---:|:---:|:---:|:---:| +| Alex | Florin-Alexandru Ilinescu | Robin Edwards | Danny Sahagun + +**🥈 Silver:** +| ![Amith Thomas](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Amith+Thomas) | ![Olivier Lefebvre](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Olivier+Lefebvre) | ![xiao yuan](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=xiao+yuan) | ![Ezra Blake](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Ezra+Blake) | ![Zenko ](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Zenko+) | ![Frederic Dreuilhe](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Frederic+Dreuilhe) | ![Kevin Schofield](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Kevin+Schofield) | ![darius coal](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=darius+coal) | ![Kerwin](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Kerwin) | ![The Dread Vixen Alinsa](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=The+Dread+Vixen+Alinsa) | ![Chris Canterbury](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Chris+Canterbury) +|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| +| Amith Thomas | Olivier Lefebvre | xiao yuan | Ezra Blake | Zenko | Frederic Dreuilhe | Kevin Schofield | darius coal | Kerwin | The Dread Vixen Alinsa | Chris Canterbury + +**🥉 Copper:** +| ![Sebastian Karbowniczek](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Sebastian+Karbowniczek) | ![Arthur Liu](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Arthur+Liu) | ![Juan Pablo Mendiola](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Juan+Pablo+Mendiola) | ![Bruce Hunter](https://ui-avatars.com/api/?background=random&color=fff&rounded=true&name=Bruce+Hunter) +|:---:|:---:|:---:|:---:| +| Sebastian Karbowniczek | Arthur Liu | Juan Pablo Mendiola | Bruce Hunter + + + + + + + + + + + + + +# How To Install: +Use method 1 or 2 if you are an Artist +use method 3 if you are a Developer/Programmer + + +# Method 1: One Click Installer + +1) Download the [.ccx](https://github.com/AbdullahAlfaraj/Auto-Photoshop-StableDiffusion-Plugin/releases/latest) file +2) run the ccx file . that's all. you will be able to use all of stable diffusion modes (txt2img, img2img, inpainting and outpainting), check the [tutorials](https://github.com/AbdullahAlfaraj/Auto-Photoshop-StableDiffusion-Plugin/wiki) section to master the tool. + +![install_plugin_1](https://user-images.githubusercontent.com/7842232/217213943-3e2a588d-3ed8-4757-ba69-9846b55a1b36.gif) + + +3) (optional step) Install the Auto-Photoshop-SD Extension from Automatic1111. the extension will allow you to use the smart masking and image search features + - a) Copy Auto-Photoshop plugin url +![copy_githup_url_2](https://user-images.githubusercontent.com/7842232/217213998-367873ce-2c09-4c42-a5fa-0044415e3908.gif) + +- b) Paste the url in auto1111's extension tab and click install + +![install_extension_3](https://user-images.githubusercontent.com/7842232/217214062-4c2fef9e-8d49-46a0-aa3b-80c4975f8a70.gif) + +- c) Make sure the Auto-Photoshop plugin is listed, then click "Apply and Restart UI" + +![apply_and_restart_4](https://user-images.githubusercontent.com/7842232/217214116-2e30d7b8-aeb6-44df-aff3-4788a56cd800.gif) + + + +# Method 2: The Unzip Method +1) Download the [.zip](https://github.com/AbdullahAlfaraj/Auto-Photoshop-StableDiffusion-Plugin/releases/latest) file +2) Unzip it in a folder with the same name +3) move the unzipped folder to the Photoshop Plugin folder +4) (optional step) Install the Auto-Photoshop-SD Extension from Automatic1111. the extension will allow you to use the smart masking and image search features +![image](https://user-images.githubusercontent.com/7842232/223751539-1a3013aa-aa1d-4058-87ae-e8b3fdfc5ec8.png) + + + +# Method 3: The UXP method (Instruction for Developers): +For artists we recommend you use [the one click installer](#one-click-installer). If you are a developer Watch the any of these videos or follow the instruction bellow. + + + + + +For artists we recommend you use [the one click installer](#one-click-installer) +## First time running the plugin (local Automatic1111): +1) download the plugin: +``` +git clone https://github.com/AbdullahAlfaraj/Auto-Photoshop-StableDiffusion-Plugin.git +``` +2) open cmd window in the "Auto-Photoshop-StableDiffusion-Plugin" directory and then install the dependencies by typing: +``` +npm install +``` +3) build the plugin by transpiling typescript to javascript: +``` +npm run watch +``` + +4) run "start_server.bat" inside "Auto-Photoshop-StableDiffusion-Plugin" directory +5) go to where you have [automatic1111](https://github.com/AUTOMATIC1111/stable-diffusion-webui) installed. +Edit the "webui-user.bat" in automatic1111 + change this line +``` +set COMMANDLINE_ARGS= +``` +to +``` +set COMMANDLINE_ARGS= --api +``` +that will allow the plugin to communicate with the automatic1111 project. After saving close the "webui-user.bat" file and run it normally. + +6) run photoshop. go to edit -> prefrences -> plugins + 1) make sure you check "Enable Developer Mode" checkbox +7) install "Adobe UXP Developer Tool" from here [Installation (adobe.com)](https://developer.adobe.com/photoshop/uxp/devtool/installation/) + this tool will add the plugin into photoshop +8) run Adobe UXP Developer Tool and click on "Add Plugin" button in the top right. Navigate to where you have "Auto-Photoshop-StableDiffusion-Plugin" folder and open "manifest.json" +9) select the plugin and click on Actions -> Load Selected +that's it. + +## First time running the plugin (remote Automatic1111): +__The remote webui must also have `--api` set in `COMMANDLINE_ARGS`. You can check if api access is enabled by appending "/docs#" to the end of the url. If the documentation includes `/sdapi/v1/samplers` then api access is enabled.__ + +1) download the plugin: +``` +git clone https://github.com/AbdullahAlfaraj/Auto-Photoshop-StableDiffusion-Plugin.git +``` +1) edit [start_server.bat](start_server.bat) (or start_server.sh if on linux) to point to the remote installation of Automatic1111 +2) run "start_server.bat" inside "Auto-Photoshop-StableDiffusion-Plugin" directory +3) run photoshop. go to edit -> prefrences -> plugins + 1) make sure you check "Enable Developer Mode" checkbox +4) install "Adobe UXP Developer Tool" from here [Installation (adobe.com)](https://developer.adobe.com/photoshop/uxp/devtool/installation/) + this tool will add the plugin into photoshop +5) run Adobe UXP Developer Tool and click on "Add Plugin" button in the top right. Navigate to where you have "Auto-Photoshop-StableDiffusion-Plugin" folder and open "manifest.json" +6) select the plugin and click on Actions -> Load Selected +that's it. + + + + + + +# Demo: +[![Click Here to Watch Demo](https://i3.ytimg.com/vi/VL_gbQai79E/maxresdefault.jpg)](https://youtu.be/VL_gbQai79E "Stable diffusion AI Photoshop Plugin Free and Open Source") + + +# FAQ and Known Issues +## What Photoshop version do I need to run the plugin? +The minimum Photoshop version that the plugin supports is Photoshop v24 + +## Plugin Load Failed +There are a few issues that can result in this error, please follow the instructions for the corresponding error message in the UDT logs + +### No application are connected to the service +This error occurs when Photoshop is not started before the plugin is attempted to be loaded. Simply start photoshop then restart UXP and load the plugin + + +## Exception in ASGI application / Expecting value: line 1 column 1 +This error occurs due to mismatched expectations between the plugin and the Automatic1111 backend. +It can be solved by both updating the version of the Automatic111 backend to the latest verion, and making sure "Save text information about generation parameters as chunks to png files" setting is enabled within the UI. + +## No Generations and Plugin Server doesn't send messages. (Remote setup) +This error occurs when the remote server does not have the api enabled. You can verify this by attempting to go to the URL you access the webui at and appending "/docs#" to the end of the url. If you have permissions, make relaunch the remote instance with the "--api" flag. + +# No GPU Options: +we provide two options to use the auto-photoshp plugin without GPU. +## Stable Horde +This is an awesome free crowdsourced distributed cluster of Stable Diffusion workers. If you like this service, consider joining the horde yourself! +the horde is enabled completely by the generosity of volunteers so make sure you don't overwhelm the service and help join the cause if you can. +read more on their [GitHub page](https://github.com/db0/AI-Horde) +## Colab: +we link to this [Colab](https://colab.research.google.com/drive/1nbcx_WOneRmYv9idBO33pN5CbxXrqZHu?usp=sharing#scrollTo=Y4ebYsPqTrGb) directly inside plugin find it in the settings tab. you only need to run it. no need to change any of the settings. copy the gradio.live url the colab will generate and paste it into ```sd url``` field in the settings tab. diff --git a/Auto-Photoshop-StableDiffusion-Plugin/dialog_box.js b/Auto-Photoshop-StableDiffusion-Plugin/dialog_box.js new file mode 100644 index 0000000000000000000000000000000000000000..1dc465fbc33b67595f5727926c02aef32fba3caf --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/dialog_box.js @@ -0,0 +1,78 @@ +async function prompt( + heading, + body, + buttons = ['Cancel', 'Ok'], + options = { title: heading, size: { width: 360, height: 280 } } +) { + const [dlgEl, formEl, headingEl, dividerEl, bodyEl, footerEl] = [ + 'dialog', + 'form', + 'sp-heading', + 'sp-divider', + 'sp-body', + 'footer', + ].map((tag) => document.createElement(tag)) + ;[headingEl, dividerEl, bodyEl, footerEl].forEach((el) => { + el.style.margin = '6px' + el.style.width = 'calc(100% - 12px)' + }) + + formEl.setAttribute('method', 'dialog') + formEl.addEventListener('submit', () => dlgEl.close()) + + footerEl.style.marginTop = '26px' + + dividerEl.setAttribute('size', 'large') + + headingEl.textContent = heading + + bodyEl.textContent = body + + buttons.forEach((btnText, idx) => { + const btnEl = document.createElement('sp-button') + btnEl.setAttribute( + 'variant', + idx === buttons.length - 1 ? btnText.variant || 'cta' : 'secondary' + ) + if (idx === buttons.length - 1) + btnEl.setAttribute('autofocus', 'autofocus') + if (idx < buttons.length - 1) btnEl.setAttribute('quiet') + btnEl.textContent = btnText.text || btnText + btnEl.style.marginLeft = '12px' + btnEl.addEventListener('click', () => + dlgEl.close(btnText.text || btnText) + ) + footerEl.appendChild(btnEl) + }) + ;[headingEl, dividerEl, bodyEl, footerEl].forEach((el) => + formEl.appendChild(el) + ) + dlgEl.appendChild(formEl) + document.body.appendChild(dlgEl) + + return dlgEl.uxpShowModal(options) +} + +// const r1 = await prompt( +// 'Upload Large File', +// 'This is a large file (over 100MB) -- it may take a few moments to upload.', +// ['Skip', 'Upload'] +// ) +// if ((r1 || 'Upload') !== 'Upload') { +// /* cancelled or No */ +// } else { +// /* Yes */ +// } + +// const r2 = await prompt( +// 'Delete File', +// 'Are you sure you wish to delete this file? This action cannot be undone.', +// ['Cancel', { variant: 'warning', text: 'Delete' }] +// ) +// if (r2 !== 'Delete') { +// /* nope, don't do it! */ +// } else { +// /* Do the delete */ +// } + +module.exports = { prompt } diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Generate txt2img.gif b/Auto-Photoshop-StableDiffusion-Plugin/docs/Generate txt2img.gif new file mode 100644 index 0000000000000000000000000000000000000000..464a9a5fa55f6e50169cf9b1c4cdef0758b6d1e5 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Generate txt2img.gif differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/History.gif b/Auto-Photoshop-StableDiffusion-Plugin/docs/History.gif new file mode 100644 index 0000000000000000000000000000000000000000..2a838dfa87e32f164fab837c25f392dffe54cc66 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/History.gif differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Home.md b/Auto-Photoshop-StableDiffusion-Plugin/docs/Home.md new file mode 100644 index 0000000000000000000000000000000000000000..e75f1ceb9d62c74e6f5653df0bdc4350e1309561 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/docs/Home.md @@ -0,0 +1,217 @@ + +*Version 1.1.0* + +## Introduction + +This guide explains the Auto Photoshop UI and its main features, it doesn't go into any detail of how Stable Diffusion works or the functionalities implemented by AUTOMATIC1111. For the latter you can read the manual [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features). + +## Stable Diffusion UI Tab + +![[Pasted image 20230131191554.png]] + +- **Model Selection** - allows to select the .ckpt / .safetensors model to be used for image generation. +- **Refresh** - refreshes the models. *Note*: this will extract all loaded models in AUTOMATIC1111, if you want to add a new model, first refresh AUTOMATIC1111. +- **L2S (Layer to selection)** - convenience function to move the content of the currently selected layer into the photoshop selection. +- **Snapshot** - convenience function equivalent to "ALT + Merge Visible Layers" +- **Reset** - reset UI to default values +- **Prompt Shortcut** - enables prompt shortcuts +- Prompt - text area for the image generation prompt +- Negative Prompt - text area for the image generation negative prompt + +### txt2img + +[[Pasted image 20230131192430.png]] + +- **Images**: number of images to be generated in a single generation session +- **Steps**: number of steps +- **Selection Mode Ratio**: the generation dimension will be set automatically to match the proportion of the photoshop selection, using 512 as the base value. +- **Selection Mode Precise**: the generation dimension will be set to match exactly the photoshop selection. +- **Selection Mode Ignore**: the generation dimension are set by the user. +- **Width and Heigth**: the image generation dimensions +- **CFG Scale**: Influence strength of the prompt (for details please see the AUTOMATIC1111 wiki) +- **Restore Faces**: enables the restore faces function in AUTOMATIC1111 +- **Hi Res Fix**: enables the Hi Res Fix function in AUTOMATIC1111 (see below) +- **Seed**: Displays and edit current seed (-1 = Random) +- **Random / Last**: sets seed to either random or last generation +- **Show Samplers**: allows to select the sampler used for image generation + +**Hi Res Fix** + +[[Pasted image 20230131195947.png]] + +When Hi Res is checked, a number of parameters become avaiable including Upscaler model to be used, output dimensions and denoising strength. This is just an interface into the AUTOMATIC1111 functionality described [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#hires-fix). + +### img2img + +[[Pasted image 20230131200253.png]] + +- **Image**: shows the current image used as img2img base. +- **Denoising Strength**: how much Stable Diffusion should be influenced by the image, 0 = output is same as image, 1 = completely different image. +- **Inpainting conditioning mask strength**; this field only works with inpainting special models (ending in "-inpainting."). Determines how much the process should stick to the image structure, check out [this post](https://www.reddit.com/r/StableDiffusion/comments/yi46px/new_hidden_img2img_feature_conditioning_mask/) for details. + +### inpaint + +[[Pasted image 20230131201122.png]] + +- **Image / Mask**: show image and mask used for the inpaint process +- **Denoising Strength**: similar to img2img however it behaves differently depending on Mask Content context. +- **Mask Blur**: how much to blur the mask before processing it in pixels +- **Mask Expansion**: how much the mask should expand to create a more blended output image +- Mask Content Fill: fill it with colors of the image +- Mask Content original: keep whatever was there originally +- Mask Content latent noise: fill it with latent space noise +- Mask Content latent nothing: fill it with latent space zeros +- **Inpaining at Full Res**: have a look [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/discussions/4637) for an explanation of this feature. +- **Restore Faces**: same as img2img + +### outpaint + +UI and its functionality are same as inpaint. + + + + + + + +## Viewer + +Tab to manage the images generated in the current session. + +[[Pasted image 20230131202255.png]] + +- Set Mask: manually sets the currently selected mask +- Set Init Image: manually sets the currently selected image +- Generate More: adds more generated images to the current session +- Selection Area: selects the boundaries of the currently selected image in the viewer +- [[Pasted image 20230131202517.png]] Keep all images generated in the current session +- [[Pasted image 20230131202539.png]] Discard all images generated in the current session +- [[Pasted image 20230131202558.png]] Keep only the selected image in the viewer +- [[Pasted image 20230131202638.png]] Discard the selected image in the viewer + +## History + +[[Pasted image 20230201161508.png]] + +- **Load Previous Generations**: loads the images generated within this Photoshop file. +- [[Pasted image 20230201161716.png]] hovering on the image loaded from history will allow bringing the image back into the Photoshop Layer stack +- Clicking on the image will load the pluging settings for the image generation (seed and image generation configuration) +- **Image Search**: loads a set of images from the internet, clicking on any of the images will load them into the layer stack. + +## Prompts Library + +[[Pasted image 20230201161938.png]] + +- For this to work a file will need to be created in the following location: Auto-Photoshop-StableDiffusion-Plugin\\server\\python_server\\prompt_shortcut.json +- **Load / Save**: Once the file is present, values can be loaded and saved onto the file. +- **Key / Value / Add top Prompt Shortcut**: allows to change / add values to the existing json file. +- **Refresh Menu**: will load all values from the json, allowing the user to make changes to the value. + +## Horde + +Coming Soon + +## Settings + +[[Pasted image 20230201163236.png]] + +# Tutorials + +## Generate a txt2img + +[[Generate txt2img.gif]] + +1. Make a selection where you want the image to be generated +2. Press [[Pasted image 20230203191656.png]] +3. (optional) use the Viewer to select which images to keep in case of multiple image generation + +## Using the Viewer + +[[Viewer Tutorial.gif]] +1. Generate images as usual +2. Select the image in the viewer grid (shift + click for multiple selection) +3. Choose from: keep one, discard one, keep all, discard all. +4. Images are saved in the latest session layer folder. + +## History Tab + +[[History.gif]] + +1. Load Previous Generations button +2. Single click on image to load its settings in the Stable Diffusion tab (seed, prompt, etc) +3. Click on edit button to load the image in Photoshop + +## Generate an img2img + +[[img2img.gif]] + +1. Select the portion of the image to be used as a sample +2. Select img2img mode and adjust the parameters (denoising strenght especially) +3. Press Generate img2img +4. (optional) use the Viewer to select which images to keep in case of multiple image generation + +## Prompts Shortcut +you can substitute a whole sequence of words with one word. + +Instead of writing the following as a prompt : +``` +Unreal Engine, Octane Render, arcane card game ui, hearthstone art style, epic fantasy style art +``` +you could write: +``` +{game_like} +``` + +as long as you have defined the relationship in the prompt library tab +``` +{ +"game_like": "Unreal Engine, Octane Render, arcane card game ui, hearthstone art style, epic fantasy style art" +} +``` + + +[[prompt_shortcut_file.gif]] + + +### Editing and Using a Prompt File +[[prompt_shortcut.gif]] + +1. Switch to the *Prompt Shortcut* tab. +2. Load the json file. +3. Input a keyword and its value +4. Press *Add to Prompt Shortcut* +5. Now the new Prompt Shortcut can be used in the Stable Diffusion tab +6. To reuse previously saved shortcuts, ensure you load the json file at the start of each session. + +## Inpainting + +[[inpainting.gif]] + +1. Select inpainting mode in the Stable Diffusion tab +2. Select the target area where to produce the image using rectangular marquee tool +3. With a 100% opacity white brush paint the area that you wish to inpaint +4. Ensure that you have a -inpainting.ckpt model selected (this is as important as it is easy to forget) +5. Write a prompt describing the inpaining image +6. Select the desired Mask Content option and adjust the Denoising Strength accordingly. +7. Hit Generate + +## Outpainting + +[[outpainting.gif]] + +1. Select outpainting mode in the Stable Diffusion tab +2. Select the target area where to produce the image using rectangular marquee tool, ensure that you have **some overlap** with the existing image (to provide Stable Diffusion with some context) and that the target area is **transparent**. +4. Ensure that you have a -inpainting.ckpt model selected (this also works for outpainting) +5. Write a prompt describing the outpaining image +6. Select the desired Mask Content option and adjust the Denoising Strength accordingly. +7. Hit Generate + + +## Heal Brush +[[heal_brush.gif]] +1. Select the "Heal Brush" from the Smart Preset dropdown menu in the Stable Diffusion tab +2. Select the target area where to produce the image using rectangular marquee tool +3. With a 100% opacity white brush paint the area that you wish to erase +4. Ensure that you have a -inpainting.ckpt model selected (this is as important as it is easy to forget) +5. Write a prompt describing what you would like to see in the erased area +6. Hit Generate \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131191554.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131191554.png new file mode 100644 index 0000000000000000000000000000000000000000..32d3ce6ef6462b1e06e8334e46b438499b799780 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131191554.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131192430.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131192430.png new file mode 100644 index 0000000000000000000000000000000000000000..2096769404bf5c9f5d076c5b1190204656bff56e Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131192430.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131195947.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131195947.png new file mode 100644 index 0000000000000000000000000000000000000000..cbe557f01e5797c9658c9614032e173fb835f89c Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131195947.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131200253.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131200253.png new file mode 100644 index 0000000000000000000000000000000000000000..ccb94732cbcbc8556c10c56f18716bb9542d23af Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131200253.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131201122.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131201122.png new file mode 100644 index 0000000000000000000000000000000000000000..ecb30a650a1b7d979c2cb2ba80f1d4167e748cbb Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131201122.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202243.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202243.png new file mode 100644 index 0000000000000000000000000000000000000000..3c5741c04d7ab62fb0713b40325f677baffbed37 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202243.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202255.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202255.png new file mode 100644 index 0000000000000000000000000000000000000000..656ee27e33d727945644c03081087262f60866a0 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202255.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202517.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202517.png new file mode 100644 index 0000000000000000000000000000000000000000..7813831719d2663b6680cf985078e509e9cea52e Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202517.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202539.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202539.png new file mode 100644 index 0000000000000000000000000000000000000000..21cafed8431910694f0441c7806f256eba1ea360 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202539.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202558.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202558.png new file mode 100644 index 0000000000000000000000000000000000000000..528ec47b046192d367d0fe905daff89877916277 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202558.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202638.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202638.png new file mode 100644 index 0000000000000000000000000000000000000000..b31045d228f92712145361a845c3caddc328ea4c Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230131202638.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161508.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161508.png new file mode 100644 index 0000000000000000000000000000000000000000..49b64a43f29084aa23a86288337e31ff7d63de51 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161508.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161702.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161702.png new file mode 100644 index 0000000000000000000000000000000000000000..e1b01cf7cb8930b7ffac45b63e878aabc6774d58 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161702.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161716.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161716.png new file mode 100644 index 0000000000000000000000000000000000000000..4e7570f23776fbb90c00384be01ea1eb2a488a9b Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161716.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161938.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161938.png new file mode 100644 index 0000000000000000000000000000000000000000..4079ed607d027e91ec7ce52ea026abd403c37b78 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201161938.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201163236.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201163236.png new file mode 100644 index 0000000000000000000000000000000000000000..34b0eb9e7ee697d7c2817bd3283428a574a0f446 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230201163236.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230203191656.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230203191656.png new file mode 100644 index 0000000000000000000000000000000000000000..fa599c3a8ec03a5c179f9c15569f28440fe52ff8 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Pasted image 20230203191656.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/Viewer Tutorial.gif b/Auto-Photoshop-StableDiffusion-Plugin/docs/Viewer Tutorial.gif new file mode 100644 index 0000000000000000000000000000000000000000..bcbd6027de97ade094d85d5387487f4e43960379 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/Viewer Tutorial.gif differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/become_backer.svg b/Auto-Photoshop-StableDiffusion-Plugin/docs/become_backer.svg new file mode 100644 index 0000000000000000000000000000000000000000..e579e6775016deb4ac0bce951174a64cfe32b5ee --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/docs/become_backer.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/heal_brush.gif b/Auto-Photoshop-StableDiffusion-Plugin/docs/heal_brush.gif new file mode 100644 index 0000000000000000000000000000000000000000..314be506690706557eba30a535d99f53136176ff --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/docs/heal_brush.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a94657edb055db5f57e14abad8734d4e0945e8f9d22b560624a31a7d5ce074a9 +size 8836551 diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/img2img.gif b/Auto-Photoshop-StableDiffusion-Plugin/docs/img2img.gif new file mode 100644 index 0000000000000000000000000000000000000000..08ff2c12dc318abc824cf1c0bc509a2113b8fd6a Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/img2img.gif differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/inpainting.gif b/Auto-Photoshop-StableDiffusion-Plugin/docs/inpainting.gif new file mode 100644 index 0000000000000000000000000000000000000000..b6ebbc9521065fbd4d558ebf35ad9141a0c14523 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/docs/inpainting.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52c2e707ffbf663b74569903d465f193ac34e8f029ef1bec70d6fa22f9277f9d +size 1113396 diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/outpainting.gif b/Auto-Photoshop-StableDiffusion-Plugin/docs/outpainting.gif new file mode 100644 index 0000000000000000000000000000000000000000..6c990ee692eca7fe5c9e90c5010bc92034c13366 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/docs/outpainting.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebfba658009c4764b60f49bfaa4215b911519cd8017dd92105f2c839db01cb05 +size 1042115 diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/profile_image/A934E4F0-7778-47E9-A395-531BFF2E61F1_1_105_c.jpeg b/Auto-Photoshop-StableDiffusion-Plugin/docs/profile_image/A934E4F0-7778-47E9-A395-531BFF2E61F1_1_105_c.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a8afe063ad3ac5fc919e8a6b33fd281cf914b157 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/profile_image/A934E4F0-7778-47E9-A395-531BFF2E61F1_1_105_c.jpeg differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/profile_image/no_profile.png b/Auto-Photoshop-StableDiffusion-Plugin/docs/profile_image/no_profile.png new file mode 100644 index 0000000000000000000000000000000000000000..8cb805a9b6273c510ecea3fb58709d26edda2cf0 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/profile_image/no_profile.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/prompt_shortcut.gif b/Auto-Photoshop-StableDiffusion-Plugin/docs/prompt_shortcut.gif new file mode 100644 index 0000000000000000000000000000000000000000..069064c020be7853f2b7d8242b3984793beaa7c0 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/docs/prompt_shortcut.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:881c55db83b01547b81eb58456d28cca2c2b66a30ce45befeff97f479104ae92 +size 1008480 diff --git a/Auto-Photoshop-StableDiffusion-Plugin/docs/prompt_shortcut_file.gif b/Auto-Photoshop-StableDiffusion-Plugin/docs/prompt_shortcut_file.gif new file mode 100644 index 0000000000000000000000000000000000000000..95f1df198dfe15de3ec36618f9ee68a0d64bd279 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/docs/prompt_shortcut_file.gif differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/enum.js b/Auto-Photoshop-StableDiffusion-Plugin/enum.js new file mode 100644 index 0000000000000000000000000000000000000000..1cf996a2d24772beb9f87070a4a1582bfc2be3e2 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/enum.js @@ -0,0 +1,57 @@ +const clickTypeEnum = { + Click: 'click', + ShiftClick: 'shift_click', + AltClick: 'alt_click', + SecondClick: 'second_click', //when we click a thumbnail that is active/ has orange border +} +const generationModeEnum = { + Txt2Img: 'txt2img', + Img2Img: 'img2img', + Inpaint: 'inpaint', + Outpaint: 'outpaint', + Upscale: 'upscale', +} + +const AutomaticStatusEnum = { + NoApi: 'no_api', + Offline: 'offline', + RunningNoApi: 'running_no_api', + RunningWithApi: 'running_with_api', +} + +const ViewerObjectTypeEnum = { + OutputImage: 'output_image', + InitImage: 'init_image', + MaskImage: 'mask_image', +} + +const RequestStateEnum = { + Generating: 'generating', // in the generation process + Interrupted: 'interrupted', // canceled/ interrupted + Finished: 'finished', // finished generating +} +const DocumentTypeEnum = { + NoBackground: 'no_background', + ImageBackground: 'image_background', + SolidBackground: 'solid_background', + ArtBoard: 'artboard', +} +const BackgroundHistoryEnum = { + CorrectBackground: 'correct_background', + NoBackground: 'no_background', +} + +const PresetTypeEnum = { + SDPreset: 'sd_preset', + ControlNetPreset: 'controlnet_preset', +} +module.exports = { + clickTypeEnum, + generationModeEnum, + AutomaticStatusEnum, + ViewerObjectTypeEnum, + RequestStateEnum, + DocumentTypeEnum, + BackgroundHistoryEnum, + PresetTypeEnum, +} diff --git a/Auto-Photoshop-StableDiffusion-Plugin/helper.js b/Auto-Photoshop-StableDiffusion-Plugin/helper.js new file mode 100644 index 0000000000000000000000000000000000000000..58993d84abe3bc26f33bcfb45bd3f278b0716e91 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/helper.js @@ -0,0 +1,120 @@ +const { unselectActiveLayers } = require('./psapi') + +const app = window.require('photoshop').app + +function getActiveLayer() { + let activeLayers = app.activeDocument.activeLayers + // console.dir(getSize()) + for (const layer of activeLayers) { + console.dir({ layer }) + const name = layer.name + console.dir({ name }) + let layer_size = getLayerSize(layer) + console.dir({ layer_size }) + } + + return activeLayers[0] +} + +function getSize() { + let doc = app.activeDocument + return { height: doc.height, width: doc.width } +} + +const { batchPlay } = require('photoshop').action +const { executeAsModal } = require('photoshop').core + +async function reselectBatchPlay(selectionInfo) { + const result = await batchPlay( + [ + { + _obj: 'set', + _target: [ + { + _ref: 'channel', + _property: 'selection', + }, + ], + to: { + _obj: 'rectangle', + top: { + _unit: 'pixelsUnit', + _value: selectionInfo.top, + }, + left: { + _unit: 'pixelsUnit', + _value: selectionInfo.left, + }, + bottom: { + _unit: 'pixelsUnit', + _value: selectionInfo.bottom, + }, + right: { + _unit: 'pixelsUnit', + _value: selectionInfo.right, + }, + }, + _options: { + dialogOptions: 'dontDisplay', + }, + }, + ], + { + synchronousExecution: true, + modalBehavior: 'execute', + } + ) +} + +async function reselect(selectionInfo) { + await executeAsModal( + async () => { + reselectBatchPlay(selectionInfo) + }, + { commandName: 'reselect' } + ) +} + +//unselect the rectangular marquee selection area +async function unSelect() { + const batchPlay = require('photoshop').action.batchPlay + + const result = await batchPlay( + [ + { + _obj: 'set', + _target: [ + { + _ref: 'channel', + _property: 'selection', + }, + ], + to: { + _enum: 'ordinal', + _value: 'none', + }, + _options: { + dialogOptions: 'dontDisplay', + }, + }, + ], + { + synchronousExecution: true, + modalBehavior: 'execute', + } + ) + + return result +} + +/** + * Convert 1d index to 2d array + * @param {number} index sequential index + * @param {number} width width of 2d array + * @returns {number[]} [x,y] + */ +function indexToXY(index, width) { + return [index % width, Math.floor(index / width)] +} + +module.exports = {} diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_all.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_all.png new file mode 100644 index 0000000000000000000000000000000000000000..2ed421a6589c2c1d00a64a607cc7292d04794665 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_all.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_all.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_all.svg new file mode 100644 index 0000000000000000000000000000000000000000..b8f9be7224df75d57cea95656df63d583936c690 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_all.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_selected.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_selected.png new file mode 100644 index 0000000000000000000000000000000000000000..02ae1812211925aaca8709c4a6b6476c6c6ad640 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_selected.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_selected.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_selected.svg new file mode 100644 index 0000000000000000000000000000000000000000..30342c626fd32ad6de9e80ed650c2c3085c07a76 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/accept_selected.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/camera_icon.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/camera_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..269d032083d2032a727bb3eeae14c619bfe946b2 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/camera_icon.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/camera_icon.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/camera_icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..ad13b59d600fba630f8e70be1b8871973e52d8c6 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/camera_icon.svg @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/chain_black.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/chain_black.svg new file mode 100644 index 0000000000000000000000000000000000000000..369d25bbecea0e5fdc52b88a57793d3ca76417bf --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/chain_black.svg @@ -0,0 +1,4 @@ + + + + diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/chain_white.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/chain_white.svg new file mode 100644 index 0000000000000000000000000000000000000000..2446502430e86985135696c449a6bd4a1fe4fc05 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/chain_white.svg @@ -0,0 +1,4 @@ + + + + diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_all.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_all.png new file mode 100644 index 0000000000000000000000000000000000000000..9980537c03734b70be3ed9caaf264c8022bc0f60 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_all.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_all.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_all.svg new file mode 100644 index 0000000000000000000000000000000000000000..e290f419b29b905a23acbc963f302f41964d51fa --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_all.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_all_border.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_all_border.png new file mode 100644 index 0000000000000000000000000000000000000000..9fd31736256478b66fb5f7dd3b82e9b7e46c0586 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_all_border.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_selected.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_selected.png new file mode 100644 index 0000000000000000000000000000000000000000..6f5507a6cfc06c288e0a4d9a4eacc66e2f4cc70b Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_selected.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_selected.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_selected.svg new file mode 100644 index 0000000000000000000000000000000000000000..8ffdc69272ef15bc398c5de26ca9e5c5609dace3 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_selected.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_selected_border.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_selected_border.png new file mode 100644 index 0000000000000000000000000000000000000000..40c5ec9899564ac65a797b2286490f8fb115449f Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/discard_selected_border.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/ftcopy.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/ftcopy.svg new file mode 100644 index 0000000000000000000000000000000000000000..c6da22d37ecb544cb6f94993a5326c2b45d1eaa2 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/ftcopy.svg @@ -0,0 +1,153 @@ + + + + + + + + + + + image/svg+xml + + + + + Openclipart + + + ftcopy + 2011-01-31T02:01:26 + Originally uploaded by Danny Allen for OCAL 0.18 this icon is part of the flat theme + https://openclipart.org/detail/112297/ftcopy-by-anonymous + + + Anonymous + + + + + flat + icon + theme + + + + + + + + + + + diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/icon_D.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/icon_D.png new file mode 100644 index 0000000000000000000000000000000000000000..420a119633ed630e717e82c3b4b3adcf9ce9158b Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/icon_D.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/icon_N.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/icon_N.png new file mode 100644 index 0000000000000000000000000000000000000000..420a119633ed630e717e82c3b4b3adcf9ce9158b Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/icon_N.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/image-search.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/image-search.svg new file mode 100644 index 0000000000000000000000000000000000000000..342def6d012500c89811b2dc9c850682fd235c5e --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/image-search.svg @@ -0,0 +1,15 @@ + + + + + + image--search + + + + + \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/layer_to_selection.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/layer_to_selection.svg new file mode 100644 index 0000000000000000000000000000000000000000..c78a7c1db078307bb7b95419ddb9cb1eb32ceed2 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/layer_to_selection.svg @@ -0,0 +1,8 @@ + + + + Layer 1 + + + + \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/reset_settings.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/reset_settings.png new file mode 100644 index 0000000000000000000000000000000000000000..084cb50d6d0cc1132d7194ffc8052ceee7b88576 Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/reset_settings.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/reset_settings2.png b/Auto-Photoshop-StableDiffusion-Plugin/icon/reset_settings2.png new file mode 100644 index 0000000000000000000000000000000000000000..da2a6dc67344b9458c4608b94159cf51447bed5a Binary files /dev/null and b/Auto-Photoshop-StableDiffusion-Plugin/icon/reset_settings2.png differ diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/search.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/search.svg new file mode 100644 index 0000000000000000000000000000000000000000..16e7b461ac7dd41e86cdb58d205537412afb2d31 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/search.svg @@ -0,0 +1,19 @@ + + + + + search_right [#1507] + Created with Sketch. + + + + + + + + + + + + + \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/icon/writing-icon.svg b/Auto-Photoshop-StableDiffusion-Plugin/icon/writing-icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..ecc6291818f5655ffc2af073862251082f9650bb --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/icon/writing-icon.svg @@ -0,0 +1 @@ +writing \ No newline at end of file diff --git a/Auto-Photoshop-StableDiffusion-Plugin/index.html b/Auto-Photoshop-StableDiffusion-Plugin/index.html new file mode 100644 index 0000000000000000000000000000000000000000..d34cb8b4a792dc21c6aac68c3d6cbdd188a8a179 --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/index.html @@ -0,0 +1,3012 @@ + + + + + + + + + + + + +
+
+
+ Stable Diffusion +
+
+ Viewer +
+
+ ControlNet +
+ + + + + +
+ Horde +
+
+ Extras +
+ +
+ Settings +
+
+ A + P +
+ v0.0.0 +
+ +
+
+
+
    + +
+ +
+ +
+
+
+ View your generated images on the canvas +
+
+
+ + + + + +
+ + + + + +
+ +
+
+ + + +
+ + Progress... + + +
+ + +
+
+ + Thumbnail Size: + + Square 1:1 +
+
+ +
+ + + +
+ +
+ + +
+ +
+ + +
+ +
+
+ +
+
+ + + + + + +
+ +
+ + +
+ +
+ Disable ControlNet Tab +
+ + +
+
+
+
+ +
+ history of all the images you generated +
+ Seed:00000000000 +
+
+
+
+ + +
+
+ +
+
+
+
+ +
+ Explore Lexica for prompts and inspiration +
+
+
+ Search: + + + + +
+ + +
+ +
+
+ +
+
+ +
+ Image Search Engine +
+
+
+ Search: + + +
+
+ +
+
+
+
+ Prompt Shortcut: a single word that represent a + prompt +
+ Key for new prompt shortcut + +
+
+ Value for new prompt shortcut + + +
+
+ +
+
+ + + + + + +
+
+ + +
+
+
+ +
+
+ Horde Key: + +
+ + + Select Backend: + + Native Horde + Auto1111 Horde Extension + Auto1111 Only + + + + +
+ NSFW + Share with LION + +
+
+
+
+ + + Resize + 2 + +
+
+ + +
+ + + + +
+
+ +
+ No work in progress +
+
+ Upscaler 1: + + + + + + +
+ Upscaler 2: + + + + + + +
+
+ + + Upscaler 2 visibility: + + 0 + +
+
+ + + GFPGAN visibility: + + 0 + +
+
+ + + CodeFormer visibility: + + 0 + +
+
+ + + CodeFormer weight: + + 0 + +
+
+
+ +
+
+ +
+ + Preset Type: + + SD Preset + ControlNet Preset + +
+ + + + +
+ + + + + +
+
+ +
+
+ +
+
+
+
+ +
+ + Settings + Custom Presets + +
+
+ SD Url: + +
+ use sharp mask + Smart Object + Live Progress Image + + Restore Original Prompt + Image Cfg Scale Slider + + + + Your PC Speed(optimization): + + Slow PC + Fast PC + + + + + Use Colab +
+ + Select Extension: + + Proxy Server + Auto111 Extension + None + + +
+
+ + Folder Path (read only): + + +
+
+ +
+ + + + +
+ + + + + + + + + + + + +
+ +
+
+
+ + Progress... + + +
+
+ + + + + + + +
+ +
+
+ + +
+ + + +
+
+ + + +
+ + + +
+ Edit Text +
+ +
+ + + + + + +
+
+ + +
+ + + +
+ +
+ +
+ + + + + +
+
+ + +
+ + + + + + + + + + +
+
+ + +
+ + + + + + + + + +
+
+
+ + +
+ +
+ + +
+ +
+ +
+
+ + + + txt2img + img2img + inpaint + outpaint + + + +
+
+ + +
+ + + + + + + + + + +
+
+ + +
+ +
+
+ +
+
+
+
+
+ +
+
+ +
+
+
+
+
+
+
+
+
+
+ Batch Size: +
+
+ Batch Count: +
+
+ Steps: +
+
+
+
+
+
+ Selection Mode: +
+ + +
+ + Width: + 512 + + + + Height: + 512 + + + + +
+ +
+ + CFG Scale: + + + + + Denoising Strength: + 0.7 + +
+ + + + Mask Blur: + + + + Mask Expansion: + + + +
+ + Inpainting conditioning mask + strength: + 1 + +
+ +
+ + Mask Content: + fill + original + latent noise + latent nothing + +
+ +
+ Inpaint at Full Res + Restore Faces + Hi Res Fix +
+ + + Inpaint Padding: + 0 + + +
+
+ +
+ Seed: + + +
+ + + Select Sampler: + Euler a + Euler + LMS + Heun + DPM2 + DPM2 a + DPM++ 2S a + DPM++ 2M + DPM++ SDE + DPM fast + DPM adaptive + LMS Karras + DPM2 Karras + DPM2 a Karras + DPM++ 2S a Karras + DPM++ 2M Karras + DPM++ SDE Karras + +
+ + +
+
+
+
+ + diff --git a/Auto-Photoshop-StableDiffusion-Plugin/index.js b/Auto-Photoshop-StableDiffusion-Plugin/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5cd333755aebaffee9eb37961b286d1b2c0c3d5a --- /dev/null +++ b/Auto-Photoshop-StableDiffusion-Plugin/index.js @@ -0,0 +1,4777 @@ +const io = require('./utility/io') +const log = console.log +const warn = console.warn +const error = console.error +const should_log = false +if (should_log) { + window.addEventListener('error', (event) => { + const [a, b, c, d, e] = [1, 2, 3, 4, 5] + console.log(`message: ${a}`) + console.log(`source: ${b}`) + console.log(`lineno: ${c}`) + console.log(`colno: ${d}`) + console.log(`error: ${e}`) + }) + + console.log = (data, ...optional_param) => { + log(data, ...optional_param) + io.IOLog.saveLogToFile({ data, ...optional_param }, 'log.txt') + } + console.warn = (data, ...optional_param) => { + try { + warn(data, ...optional_param) + io.IOLog.saveLogToFile({ data, ...optional_param }, 'warn.txt') + } catch (e) { + warn('error while logging: ') + warn(e) + } + } + console.error = (data, ...optional_param) => { + error(data, ...optional_param) + io.IOLog.saveLogToFile({ data, ...optional_param }, 'error.txt') + } +} + +// import {helloHelper} from 'helper.js' +// helloHelper2 = require('./helper.js') +// for organizational proposes +// let g_sdapi_path = 'sdapi' +let g_version = 'v1.2.5' +let g_sd_url = 'http://127.0.0.1:7860' +let g_online_data_url = + 'https://raw.githubusercontent.com/AbdullahAlfaraj/Auto-Photoshop-StableDiffusion-Plugin/master/utility/online_data.json' +const Enum = require('./enum') +const helper = require('./helper') +const sd_tab = require('./utility/tab/sd') +// let g_sdapi_path = 'sdapi_py_re' +// const sdapi = require(`./${g_sdapi_path}`) +const sdapi = require('./sdapi_py_re') + +// const exportHelper = require('./export_png') +const outpaint = require('./outpaint') +const psapi = require('./psapi') +const app = window.require('photoshop').app + +const { batchPlay } = require('photoshop').action +const { executeAsModal } = require('photoshop').core +const dialog_box = require('./dialog_box') +// const {entrypoints} = require('uxp') +const html_manip = require('./utility/html_manip') +// const export_png = require('./export_png') +const viewer = require('./viewer') +const selection = require('./selection') +const layer_util = require('./utility/layer') +const sd_options = require('./utility/sdapi/options') +const sd_config = require('./utility/sdapi/config') +const session = require('./utility/session') +const ui = require('./utility/ui') +const preset_util = require('./utility/presets/preset') +const script_horde = require('./utility/sd_scripts/horde') +const prompt_shortcut = require('./utility/sdapi/prompt_shortcut') +const formats = require('uxp').storage.formats +const storage = require('uxp').storage +const shell = require('uxp').shell +const fs = storage.localFileSystem +const horde_native = require('./utility/sdapi/horde_native') + +const dummy = require('./utility/dummy') +const general = require('./utility/general') +const thumbnail = require('./thumbnail') +const note = require('./utility/notification') +const sampler_data = require('./utility/sampler') +const settings_tab = require('./utility/tab/settings') +const control_net = require('./utility/tab/control_net') +//load tabs +const history_tab = require('./utility/tab/history_tab') +const image_search_tab = require('./utility/tab/image_search_tab') +const lexica_tab = require('./utility/tab/lexica_tab') +const share_tab = require('./utility/tab/share_tab') +// const ultimate_sd_upscaler = require('./ultimate_sd_upscaler/dist/ultimate_sd_upscaler') +const ultimate_sd_upscaler_script = require('./ultimate_sd_upscaler/dist/ultimate_sd_upscaler.bundle') +const scripts = require('./ultimate_sd_upscaler/dist/scripts.bundle') + +// const ultimate_sd_upscaler_script_test = require('./ultimate_sd_upscaler/dist/main') + +// const { +// script_args, +// script_name, +// } = require('./ultimate_sd_upscaler/dist/ultimate_sd_upscaler') + +let g_horde_generator = new horde_native.hordeGenerator() +let g_automatic_status = Enum.AutomaticStatusEnum['Offline'] +let g_models_status = false +let g_current_batch_index = 0 +//REFACTOR: move to session.js +async function hasSessionSelectionChanged() { + try { + const isSelectionActive = await psapi.checkIfSelectionAreaIsActive() + if (isSelectionActive) { + const current_selection = isSelectionActive // Note: don't use checkIfSelectionAreaIsActive to return the selection object, change this. + + if ( + await hasSelectionChanged( + current_selection, + g_generation_session.selectionInfo + ) + ) { + return true + } else { + //selection has not changed + return false + } + } + } catch (e) { + console.warn(e) + return false + } +} +//REFACTOR: move to selection.js, add selection mode as attribute (linked to rbSelectionMode event) +async function calcWidthHeightFromSelection() { + //set the width and height, hrWidth, and hrHeight using selection info and selection mode + const selection_mode = html_manip.getSelectionMode() + if (selection_mode === 'ratio') { + //change (width and height) and (hrWidth, hrHeight) to match the ratio of selection + const [width, height, hr_width, hr_height] = + await selection.selectionToFinalWidthHeight() + + html_manip.autoFillInWidth(width) + html_manip.autoFillInHeight(height) + html_manip.autoFillInHRWidth(hr_width) + html_manip.autoFillInHRHeight(hr_height) + } else if (selection_mode === 'precise') { + const selectionInfo = await psapi.getSelectionInfoExe() + const [width, height, hr_width, hr_height] = [ + selectionInfo.width, + selectionInfo.height, + 0, + 0, + ] + html_manip.autoFillInWidth(width) + html_manip.autoFillInHeight(height) + } +} +//REFACTOR: rename to newSelectionEventHandler and move to session.js +const eventHandler = async (event, descriptor) => { + try { + console.log(event, descriptor) + + const isSelectionActive = await psapi.checkIfSelectionAreaIsActive() + if (isSelectionActive) { + const current_selection = isSelectionActive // Note: don't use checkIfSelectionAreaIsActive to return the selection object, change this. + + await calcWidthHeightFromSelection() + + // console.log(` (${final_width}* ${final_height})/(${current_selection.width} * ${current_selection.height})`) + // console.log("detail density: ",(final_width* final_height)/(current_selection.width * current_selection.height)) + + // const new_selection = await psapi.getSelectionInfoExe() + + if ( + await hasSelectionChanged( + current_selection, + g_generation_session.selectionInfo + ) //new selection + ) { + // endSessionUI //red color + // if selection has changed : change the color and text generate btn "Generate" color "red" + // g_ui.endSessionUI() + // const selected_mode = html_manip.getMode() + const selected_mode = getCurrentGenerationModeByValue(g_sd_mode) + g_ui.generateModeUI(selected_mode) + } else { + // it's the same selection and the session is active + + //indicate that the session will continue. only if the session we are in the same mode as the session's mode + // startSessionUI// green color + const current_mode = html_manip.getMode() + if ( + g_generation_session.isActive() && // the session is active + g_generation_session.isSameMode(current_mode) //same mode + ) { + // g_ui.startSessionUI() + g_ui.generateMoreUI() + } + } + } + } catch (e) { + console.warn(e) + } +} +//REFACTOR: move to generation_settings.js +function getCurrentGenerationModeByValue(value) { + for (let key in generationMode) { + if ( + generationMode.hasOwnProperty(key) && + generationMode[key] === value + ) { + return key + } + } + return undefined +} + +require('photoshop').action.addNotificationListener( + ['set', 'move'], + eventHandler +) +//REFACTOR: move to document.js +async function getUniqueDocumentId() { + console.warn( + 'getUniqueDocumentId is deprecated, instead use the methods in IOFolder' + ) + try { + let uniqueDocumentId = await psapi.readUniqueDocumentIdExe() + + console.log( + 'getUniqueDocumentId(): uniqueDocumentId: ', + uniqueDocumentId + ) + + // Regular expression to check if string is a valid UUID + const regexExp = + /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi + + // String with valid UUID separated by dash + // const str = 'a24a6ea4-ce75-4665-a070-57453082c256' + + const isValidId = regexExp.test(uniqueDocumentId) // true + console.log('isValidId: ', isValidId) + if (isValidId == false) { + let uuid = self.crypto.randomUUID() + console.log(uuid) // for example "36b8f84d-df4e-4d49-b662-bcde71a8764f" + await psapi.saveUniqueDocumentIdExe(uuid) + uniqueDocumentId = uuid + } + return uniqueDocumentId + } catch (e) { + console.warn('warning Document Id may not be valid', e) + } +} + +// document +// .getElementById('btnLinkCurrentDocument') +// .addEventListener('click', async () => { +// await getUniqueDocumentId() +// }) + +// attach event listeners for tabs +//REFACTOR: move to html_manip.js (?) - if there is no business logic here and it's only for UI. +Array.from(document.querySelectorAll('.sp-tab')).forEach((theTab) => { + theTab.onclick = () => { + try { + // localStorage.setItem("currentTab", theTab.getAttribute("id")); + Array.from(document.querySelectorAll('.sp-tab')).forEach((aTab) => { + if (aTab.getAttribute('id') === theTab.getAttribute('id')) { + aTab.classList.add('selected') + } else { + aTab.classList.remove('selected') + } + }) + Array.from(document.querySelectorAll('.sp-tab-page')).forEach( + (tabPage) => { + if ( + tabPage + .getAttribute('id') + .startsWith(theTab.getAttribute('id')) + ) { + tabPage.classList.add('visible-hack') + } else { + tabPage.classList.remove('visible-hack') + } + } + ) + } catch (e) { + console.warn(e) + } + } +}) +//REFACTOR: move to events.js +document.getElementById('sp-viewer-tab').addEventListener('click', async () => { + if ( + g_generation_session.isActive() && + g_generation_session.mode === 'upscale' + ) { + g_sd_mode = 'upscale' + } else { + g_sd_mode = html_manip.getMode() + } +}) +//REFACTOR: move to events.js +document.getElementById('sp-viewer-tab').addEventListener('click', async () => { + moveElementToAnotherTab('batchNumberUi', 'batchNumberViewerTabContainer') + await displayUpdate() +}) +//REFACTOR: move to events.js +document + .getElementById('sp-stable-diffusion-ui-tab') + .addEventListener('click', () => { + moveElementToAnotherTab('batchNumberUi', 'batchNumber-steps-container') + }) +// entrypoints.setup({ + +// panels:{ +// vanilla: ()=>{ +// console.log("you are in the vanilla panel") +// }, +// experimental_1: ()=>{ +// console.log("you are in the experimental_1 panel") + +// } +// } +// } +// ) +// just a number that shouldn't unique enough that we will use when save files. +// each session will get a number from 1 to 1000000 +//REFACTOR: move to session.js +const random_session_id = Math.floor(Math.random() * 1000000 + 1) +//REFACTOR: move to helpers.js (or other utility file) +function getSelectedText() { + // JavaScript + // // Obtain the object reference for the + + + + +
+
+ + +
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/sd_feed/html/lora.html b/sd_feed/html/lora.html new file mode 100644 index 0000000000000000000000000000000000000000..4f4c054a6b3752dd20894a634546ccf24c46e160 --- /dev/null +++ b/sd_feed/html/lora.html @@ -0,0 +1,24 @@ +
+ + + + + + + + + + + +
File Name
+
\ No newline at end of file diff --git a/sd_feed/html/potd.html b/sd_feed/html/potd.html new file mode 100644 index 0000000000000000000000000000000000000000..286e1a8b17f72df2d77fd6f5cd87d65761789ca6 --- /dev/null +++ b/sd_feed/html/potd.html @@ -0,0 +1,135 @@ +
+
+
+ 👑 POTD 👑 +
+
+ +
+
+
+ +
+
+
+
+ Pretty Image +
+
+ + +
+ +
+
+ + +
+
+
+
Generation Data
+
+ +
+
+ +
+
+
+
+
+
+
\ No newline at end of file diff --git a/sd_feed/html/profile.html b/sd_feed/html/profile.html new file mode 100644 index 0000000000000000000000000000000000000000..2ad3f9c1d054d7fa83cfb8361f42a85b7d67dc2f --- /dev/null +++ b/sd_feed/html/profile.html @@ -0,0 +1,21 @@ + + \ No newline at end of file diff --git a/sd_feed/install.py b/sd_feed/install.py new file mode 100644 index 0000000000000000000000000000000000000000..da7f3fe9c600c1e4cbecce3c73c37566e9505f4d --- /dev/null +++ b/sd_feed/install.py @@ -0,0 +1,5 @@ +import launch + + +if not launch.is_installed("browsercookie"): + launch.run_pip("install browsercookie", "requirements for Browser Cookie") \ No newline at end of file diff --git a/sd_feed/javascript/axios.min.js b/sd_feed/javascript/axios.min.js new file mode 100644 index 0000000000000000000000000000000000000000..d3c2a3724140e9a275065d99fc8deb1d828156de --- /dev/null +++ b/sd_feed/javascript/axios.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).axios=t()}(this,(function(){"use strict";function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n2&&void 0!==arguments[2]?arguments[2]:{},a=i.allOwnKeys,s=void 0!==a&&a;if(null!=t)if("object"!==e(t)&&(t=[t]),p(t))for(r=0,o=t.length;r0;)if(t===(n=r[o]).toLowerCase())return n;return null}var N="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,x=function(e){return!h(e)&&e!==N};var C,P=(C="undefined"!=typeof Uint8Array&&c(Uint8Array),function(e){return C&&e instanceof C}),k=l("HTMLFormElement"),U=function(e){var t=Object.prototype.hasOwnProperty;return function(e,n){return t.call(e,n)}}(),_=l("RegExp"),F=function(e,t){var n=Object.getOwnPropertyDescriptors(e),r={};T(n,(function(n,o){!1!==t(n,o,e)&&(r[o]=n)})),Object.defineProperties(e,r)},B="abcdefghijklmnopqrstuvwxyz",L="0123456789",D={DIGIT:L,ALPHA:B,ALPHA_DIGIT:B+B.toUpperCase()+L};var I={isArray:p,isArrayBuffer:m,isBuffer:function(e){return null!==e&&!h(e)&&null!==e.constructor&&!h(e.constructor)&&v(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||u.call(e)===t||v(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&m(e.buffer)},isString:y,isNumber:b,isBoolean:function(e){return!0===e||!1===e},isObject:g,isPlainObject:w,isUndefined:h,isDate:E,isFile:O,isBlob:S,isRegExp:_,isFunction:v,isStream:function(e){return g(e)&&v(e.pipe)},isURLSearchParams:A,isTypedArray:P,isFileList:R,forEach:T,merge:function e(){for(var t=x(this)&&this||{},n=t.caseless,r={},o=function(t,o){var i=n&&j(r,o)||o;w(r[i])&&w(t)?r[i]=e(r[i],t):w(t)?r[i]=e({},t):p(t)?r[i]=t.slice():r[i]=t},i=0,a=arguments.length;i3&&void 0!==arguments[3]?arguments[3]:{},o=r.allOwnKeys;return T(t,(function(t,r){n&&v(t)?e[r]=a(t,n):e[r]=t}),{allOwnKeys:o}),e},trim:function(e){return e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,n,r){e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:function(e,t,n,r){var o,i,a,s={};if(t=t||{},null==e)return t;do{for(i=(o=Object.getOwnPropertyNames(e)).length;i-- >0;)a=o[i],r&&!r(a,e,t)||s[a]||(t[a]=e[a],s[a]=!0);e=!1!==n&&c(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:f,kindOfTest:l,endsWith:function(e,t,n){e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;var r=e.indexOf(t,n);return-1!==r&&r===n},toArray:function(e){if(!e)return null;if(p(e))return e;var t=e.length;if(!b(t))return null;for(var n=new Array(t);t-- >0;)n[t]=e[t];return n},forEachEntry:function(e,t){for(var n,r=(e&&e[Symbol.iterator]).call(e);(n=r.next())&&!n.done;){var o=n.value;t.call(e,o[0],o[1])}},matchAll:function(e,t){for(var n,r=[];null!==(n=e.exec(t));)r.push(n);return r},isHTMLForm:k,hasOwnProperty:U,hasOwnProp:U,reduceDescriptors:F,freezeMethods:function(e){F(e,(function(t,n){if(v(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;var r=e[n];v(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=function(){throw Error("Can not rewrite read-only method '"+n+"'")}))}))},toObjectSet:function(e,t){var n={},r=function(e){e.forEach((function(e){n[e]=!0}))};return p(e)?r(e):r(String(e).split(t)),n},toCamelCase:function(e){return e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n}))},noop:function(){},toFiniteNumber:function(e,t){return e=+e,Number.isFinite(e)?e:t},findKey:j,global:N,isContextDefined:x,ALPHABET:D,generateString:function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:D.ALPHA_DIGIT,n="",r=t.length;e--;)n+=t[Math.random()*r|0];return n},isSpecCompliantForm:function(e){return!!(e&&v(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:function(e){var t=new Array(10);return function e(n,r){if(g(n)){if(t.indexOf(n)>=0)return;if(!("toJSON"in n)){t[r]=n;var o=p(n)?[]:{};return T(n,(function(t,n){var i=e(t,r+1);!h(i)&&(o[n]=i)})),t[r]=void 0,o}}return n}(e,0)}};function q(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}I.inherits(q,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:I.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var M=q.prototype,z={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((function(e){z[e]={value:e}})),Object.defineProperties(q,z),Object.defineProperty(M,"isAxiosError",{value:!0}),q.from=function(e,t,n,r,o,i){var a=Object.create(M);return I.toFlatObject(e,a,(function(e){return e!==Error.prototype}),(function(e){return"isAxiosError"!==e})),q.call(a,e.message,t,n,r,o),a.cause=e,a.name=e.name,i&&Object.assign(a,i),a};function H(e){return I.isPlainObject(e)||I.isArray(e)}function J(e){return I.endsWith(e,"[]")?e.slice(0,-2):e}function W(e,t,n){return e?e.concat(t).map((function(e,t){return e=J(e),!n&&t?"["+e+"]":e})).join(n?".":""):t}var K=I.toFlatObject(I,{},null,(function(e){return/^is[A-Z]/.test(e)}));function V(t,n,r){if(!I.isObject(t))throw new TypeError("target must be an object");n=n||new FormData;var o=(r=I.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!I.isUndefined(t[e])}))).metaTokens,i=r.visitor||f,a=r.dots,s=r.indexes,u=(r.Blob||"undefined"!=typeof Blob&&Blob)&&I.isSpecCompliantForm(n);if(!I.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(I.isDate(e))return e.toISOString();if(!u&&I.isBlob(e))throw new q("Blob is not supported. Use a Buffer instead.");return I.isArrayBuffer(e)||I.isTypedArray(e)?u&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function f(t,r,i){var u=t;if(t&&!i&&"object"===e(t))if(I.endsWith(r,"{}"))r=o?r:r.slice(0,-2),t=JSON.stringify(t);else if(I.isArray(t)&&function(e){return I.isArray(e)&&!e.some(H)}(t)||(I.isFileList(t)||I.endsWith(r,"[]"))&&(u=I.toArray(t)))return r=J(r),u.forEach((function(e,t){!I.isUndefined(e)&&null!==e&&n.append(!0===s?W([r],t,a):null===s?r:r+"[]",c(e))})),!1;return!!H(t)||(n.append(W(i,r,a),c(t)),!1)}var l=[],d=Object.assign(K,{defaultVisitor:f,convertValue:c,isVisitable:H});if(!I.isObject(t))throw new TypeError("data must be an object");return function e(t,r){if(!I.isUndefined(t)){if(-1!==l.indexOf(t))throw Error("Circular reference detected in "+r.join("."));l.push(t),I.forEach(t,(function(t,o){!0===(!(I.isUndefined(t)||null===t)&&i.call(n,t,I.isString(o)?o.trim():o,r,d))&&e(t,r?r.concat(o):[o])})),l.pop()}}(t),n}function G(e){var t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function $(e,t){this._pairs=[],e&&V(e,this,t)}var X=$.prototype;function Q(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Z(e,t,n){if(!t)return e;var r,o=n&&n.encode||Q,i=n&&n.serialize;if(r=i?i(t,n):I.isURLSearchParams(t)?t.toString():new $(t,n).toString(o)){var a=e.indexOf("#");-1!==a&&(e=e.slice(0,a)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e}X.append=function(e,t){this._pairs.push([e,t])},X.toString=function(e){var t=e?function(t){return e.call(this,t,G)}:G;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Y,ee=function(){function e(){t(this,e),this.handlers=[]}return r(e,[{key:"use",value:function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}},{key:"eject",value:function(e){this.handlers[e]&&(this.handlers[e]=null)}},{key:"clear",value:function(){this.handlers&&(this.handlers=[])}},{key:"forEach",value:function(e){I.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}]),e}(),te={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ne={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:$,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},isStandardBrowserEnv:("undefined"==typeof navigator||"ReactNative"!==(Y=navigator.product)&&"NativeScript"!==Y&&"NS"!==Y)&&"undefined"!=typeof window&&"undefined"!=typeof document,isStandardBrowserWebWorkerEnv:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,protocols:["http","https","file","blob","url","data"]};function re(e){function t(e,n,r,o){var i=e[o++],a=Number.isFinite(+i),s=o>=e.length;return i=!i&&I.isArray(r)?r.length:i,s?(I.hasOwnProp(r,i)?r[i]=[r[i],n]:r[i]=n,!a):(r[i]&&I.isObject(r[i])||(r[i]=[]),t(e,n,r[i],o)&&I.isArray(r[i])&&(r[i]=function(e){var t,n,r={},o=Object.keys(e),i=o.length;for(t=0;t-1,i=I.isObject(e);if(i&&I.isHTMLForm(e)&&(e=new FormData(e)),I.isFormData(e))return o&&o?JSON.stringify(re(e)):e;if(I.isArrayBuffer(e)||I.isBuffer(e)||I.isStream(e)||I.isFile(e)||I.isBlob(e))return e;if(I.isArrayBufferView(e))return e.buffer;if(I.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return V(e,new ne.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,r){return ne.isNode&&I.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((n=I.isFileList(e))||r.indexOf("multipart/form-data")>-1){var a=this.env&&this.env.FormData;return V(n?{"files[]":e}:e,a&&new a,this.formSerializer)}}return i||o?(t.setContentType("application/json",!1),function(e,t,n){if(I.isString(e))try{return(t||JSON.parse)(e),I.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||ie.transitional,n=t&&t.forcedJSONParsing,r="json"===this.responseType;if(e&&I.isString(e)&&(n&&!this.responseType||r)){var o=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(e){if(o){if("SyntaxError"===e.name)throw q.from(e,q.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ne.classes.FormData,Blob:ne.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};I.forEach(["delete","get","head"],(function(e){ie.headers[e]={}})),I.forEach(["post","put","patch"],(function(e){ie.headers[e]=I.merge(oe)}));var ae=ie,se=I.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ue=Symbol("internals");function ce(e){return e&&String(e).trim().toLowerCase()}function fe(e){return!1===e||null==e?e:I.isArray(e)?e.map(fe):String(e)}function le(e,t,n,r,o){return I.isFunction(r)?r.call(this,t,n):(o&&(t=n),I.isString(t)?I.isString(r)?-1!==t.indexOf(r):I.isRegExp(r)?r.test(t):void 0:void 0)}var de=function(e,n){function i(e){t(this,i),e&&this.set(e)}return r(i,[{key:"set",value:function(e,t,n){var r=this;function o(e,t,n){var o=ce(t);if(!o)throw new Error("header name must be a non-empty string");var i=I.findKey(r,o);(!i||void 0===r[i]||!0===n||void 0===n&&!1!==r[i])&&(r[i||t]=fe(e))}var i,a,s,u,c,f=function(e,t){return I.forEach(e,(function(e,n){return o(e,n,t)}))};return I.isPlainObject(e)||e instanceof this.constructor?f(e,t):I.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())?f((c={},(i=e)&&i.split("\n").forEach((function(e){u=e.indexOf(":"),a=e.substring(0,u).trim().toLowerCase(),s=e.substring(u+1).trim(),!a||c[a]&&se[a]||("set-cookie"===a?c[a]?c[a].push(s):c[a]=[s]:c[a]=c[a]?c[a]+", "+s:s)})),c),t):null!=e&&o(t,e,n),this}},{key:"get",value:function(e,t){if(e=ce(e)){var n=I.findKey(this,e);if(n){var r=this[n];if(!t)return r;if(!0===t)return function(e){for(var t,n=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;t=r.exec(e);)n[t[1]]=t[2];return n}(r);if(I.isFunction(t))return t.call(this,r,n);if(I.isRegExp(t))return t.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}},{key:"has",value:function(e,t){if(e=ce(e)){var n=I.findKey(this,e);return!(!n||void 0===this[n]||t&&!le(0,this[n],n,t))}return!1}},{key:"delete",value:function(e,t){var n=this,r=!1;function o(e){if(e=ce(e)){var o=I.findKey(n,e);!o||t&&!le(0,n[o],o,t)||(delete n[o],r=!0)}}return I.isArray(e)?e.forEach(o):o(e),r}},{key:"clear",value:function(e){for(var t=Object.keys(this),n=t.length,r=!1;n--;){var o=t[n];e&&!le(0,this[o],o,e,!0)||(delete this[o],r=!0)}return r}},{key:"normalize",value:function(e){var t=this,n={};return I.forEach(this,(function(r,o){var i=I.findKey(n,o);if(i)return t[i]=fe(r),void delete t[o];var a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n}))}(o):String(o).trim();a!==o&&delete t[o],t[a]=fe(r),n[a]=!0})),this}},{key:"concat",value:function(){for(var e,t=arguments.length,n=new Array(t),r=0;r1?n-1:0),o=1;o0;){var a=o[i],s=n[a];if(s){var u=t[a],c=void 0===u||s(u,a,t);if(!0!==c)throw new q("option "+a+" must be "+c,q.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new q("Unknown option "+a,q.ERR_BAD_OPTION)}},validators:Ne},Pe=Ce.validators,ke=function(){function e(n){t(this,e),this.defaults=n,this.interceptors={request:new ee,response:new ee}}return r(e,[{key:"request",value:function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{};var n,r=t=Te(this.defaults,t),o=r.transitional,i=r.paramsSerializer,a=r.headers;void 0!==o&&Ce.assertOptions(o,{silentJSONParsing:Pe.transitional(Pe.boolean),forcedJSONParsing:Pe.transitional(Pe.boolean),clarifyTimeoutError:Pe.transitional(Pe.boolean)},!1),null!=i&&(I.isFunction(i)?t.paramsSerializer={serialize:i}:Ce.assertOptions(i,{encode:Pe.function,serialize:Pe.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase(),(n=a&&I.merge(a.common,a[t.method]))&&I.forEach(["delete","get","head","post","put","patch","common"],(function(e){delete a[e]})),t.headers=pe.concat(n,a);var s=[],u=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(u=u&&e.synchronous,s.unshift(e.fulfilled,e.rejected))}));var c,f=[];this.interceptors.response.forEach((function(e){f.push(e.fulfilled,e.rejected)}));var l,d=0;if(!u){var p=[Re.bind(this),void 0];for(p.unshift.apply(p,s),p.push.apply(p,f),l=p.length,c=Promise.resolve(t);d0;)o._listeners[t](e);o._listeners=null}})),this.promise.then=function(e){var t,n=new Promise((function(e){o.subscribe(e),t=e})).then(e);return n.cancel=function(){o.unsubscribe(t)},n},n((function(e,t,n){o.reason||(o.reason=new ye(e,t,n),r(o.reason))}))}return r(e,[{key:"throwIfRequested",value:function(){if(this.reason)throw this.reason}},{key:"subscribe",value:function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}},{key:"unsubscribe",value:function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}}}],[{key:"source",value:function(){var t;return{token:new e((function(e){t=e})),cancel:t}}}]),e}();var Fe={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Fe).forEach((function(e){var t=o(e,2),n=t[0],r=t[1];Fe[r]=n}));var Be=Fe;var Le=function e(t){var n=new Ue(t),r=a(Ue.prototype.request,n);return I.extend(r,Ue.prototype,n,{allOwnKeys:!0}),I.extend(r,n,null,{allOwnKeys:!0}),r.create=function(n){return e(Te(t,n))},r}(ae);return Le.Axios=Ue,Le.CanceledError=ye,Le.CancelToken=_e,Le.isCancel=me,Le.VERSION=je,Le.toFormData=V,Le.AxiosError=q,Le.Cancel=Le.CanceledError,Le.all=function(e){return Promise.all(e)},Le.spread=function(e){return function(t){return e.apply(null,t)}},Le.isAxiosError=function(e){return I.isObject(e)&&!0===e.isAxiosError},Le.mergeConfig=Te,Le.AxiosHeaders=pe,Le.formToJSON=function(e){return re(I.isHTMLForm(e)?new FormData(e):e)},Le.HttpStatusCode=Be,Le.default=Le,Le})); +// # sourceMappingURL=axios.min.js.map \ No newline at end of file diff --git a/sd_feed/javascript/best_feed.js b/sd_feed/javascript/best_feed.js new file mode 100644 index 0000000000000000000000000000000000000000..9ce29db997387d8754450ceca0afe7e12dca0dee --- /dev/null +++ b/sd_feed/javascript/best_feed.js @@ -0,0 +1,638 @@ + +function waitForElementToDisplay2(selector, callback, checkFrequencyInMs, timeoutInMs) { + (function loopSearch() { + if (document.querySelector(selector) != null && window.localStorage.getItem("userId")) { + callback(); + return; + } + else if(document.getElementsByTagName("gradio-app").length > 0 && + document.getElementsByTagName("gradio-app")[0].shadowRoot){ + callback(); + return; + } + else { + setTimeout(function () { + loopSearch(); + }, checkFrequencyInMs); + } + })(); + } + waitForElementToDisplay2( + "#html_id", + function(){ + async function copyToClipboard(textToCopy) { + // Navigator clipboard api needs a secure context (https) + if (navigator.clipboard && window.isSecureContext) { + await navigator.clipboard.writeText(textToCopy); + } else { + // Use the 'out of viewport hidden text area' trick + const textArea = document.createElement("textarea"); + textArea.value = textToCopy; + + // Move textarea out of the viewport so it's not visible + textArea.style.position = "absolute"; + textArea.style.left = "-999999px"; + + document.body.prepend(textArea); + textArea.select(); + + try { + document.execCommand('copy'); + } catch (error) { + console.error(error); + } finally { + textArea.remove(); + } + } + }; + const userModel = { + data() { + return { + bestFeeds: [], + comments: [], + userId: '', + showCommentWrite: false, + comment: '', + src: '', + imageId: "", + metadata: {}, + currentItem: {}, + filterNsfw: false, + showModal:false, + + } + }, + watch: { + showModal() { + if (this.showModal === false) { + window.removeEventListener("keyup", this.onEscapeKey); + } else { + window.addEventListener("keyup", this.onEscapeKey); + } + } + }, + methods: { + close() { + this.$emit('close'); + this.showModal=false; + this.imageId = ""; + this.src = ""; + this.comment = ''; + this.comments = []; + }, + moveFeedProfileTab(event, nickname){ + event.preventDefault(); + if(nickname){ + this.close(); + const buttonList = gradioApp().querySelector('#tabs').querySelectorAll('button'); + for (step = 0; step < buttonList.length; step++) { + // Runs 5 times, with values of step 0 through 4. + if(buttonList[step].textContent.trim() == 'Feed'){ + buttonList[step].click(); + break; + } + } + try{ + const feedUserButton = gradioApp().querySelector('#feed-user-tab'); + feedUserButton.setAttribute("data-value", nickname); + feedUserButton.innerHTML = nickname; + feedUserButton.click(); + + }catch(e){ + console.log(e); + } + + } + + }, + closeOutsideModal(event) { + if(!event.target.closest('.prompt-modal-image-tag')){ + this.$emit('close'); + this.showModal=false; + this.imageId = ""; + this.src = ""; + this.comment = ''; + this.comments = []; + } + }, + onEscapeKey(event) { + if (event.keyCode === 27 || event.key === 'Escape') { + // Perform action when "Esc" key is pressed + this.close(); + } + // Perform action when "Esc" key is pressed + }, + fetchBests(){ + const token = localStorage.getItem("token"); + const userId = localStorage.getItem("userId"); + const headers={"Authorization":"Token " + token}; + const params = { + filter_nsfw: this.filterNsfw, + }; + axios.get( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/best/${userId}`, + { + headers, + params + } + ) + .then(response => { + const dataObject = response.data; + this.bestFeeds = dataObject.slice(0, 4); + }).catch(error => { + this.loading = false; + console.log(error) + }); + }, + formatNumber(num) { + if (num >= 1000000) { + return (num / 1000000).toFixed(1) + 'm'; + } else if (num >= 1000) { + return (num / 1000).toFixed(1) + 'k'; + } else { + return num.toString(); + } + }, + openModal(item){ + this.showModal = true; + this.$forceUpdate(); + this.currentItem = item; + this.metadata = item.metadata; + this.src = item.url; + this.imageId = item.id; + item.total_clicks += 1; + this.addImageClick(); + this.fetchComments(); + }, + openModalSecond(event){ + console.log(event); + + + }, + addImageClick(){ + const userId = localStorage.getItem("userId"); + const imageId = this.imageId; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/click', + { + userId, + imageId, + }, + { + headers + } + ) + .then(response => { + this.showModal = true; + }).catch(error => { + this.loading = false; + console.log(error) + }) + }, + sendToTextToImage(){ + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + + const imageId = this.imageId; + this.currentItem.total_sendto = this.currentItem.total_sendto + 1; + axios.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/send_to', + { + userId, + imageId, + sendType: "SEND_TO_TEXT", + }, + { + headers + } + ) + .then(response => { + this.sendToTextProcess(); + }).catch(error => { + this.loading = false; + console.log(error) + }) + }, + + copyClipboard(){ + const userId = localStorage.getItem("userId"); + const imageId = this.imageId; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/send_to', + { + userId, + imageId, + sendType: "COPY_TO_CLIPBOARD", + }, + { + headers + } + ) + .then(response => { + let filteredObject = ''; + for (const [k, v] of Object.entries(this.metadata)) { + if (/^[A-Z]/.test(k)) { + filteredObject += `${k}:${v},`; + } + } + this.currentItem.total_sendto = this.currentItem.total_sendto + 1; + copyToClipboard(filteredObject); + }).catch(error => { + this.loading = false; + console.log(error) + }); + + }, + sendToTextProcess(){ + const textPrompt = gradioApp().querySelector('#txt2img_prompt').getElementsByTagName( 'textarea' ); + if(textPrompt&&textPrompt.length> 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_prompt')[0].props.value = this.metadata.prompt; + textPrompt[0].value = this.metadata.prompt; + } + const negativePrompt = gradioApp().querySelector('#txt2img_neg_prompt').getElementsByTagName( 'textarea' ); + if(negativePrompt&&negativePrompt.length> 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_neg_prompt')[0].props.value = this.metadata.negative_prompt; + negativePrompt[0].value = this.metadata.negative_prompt; + } + try{ + const samplerList = gradioApp().querySelector( '#txt2img_sampling' ).getElementsByTagName('span'); + if(samplerList&&samplerList.length> 1){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_sampling')[0].props.value = this.metadata.sampler; + samplerList[1].textContent = this.metadata.sampler; + } + }catch(e){ + } + + try{ + const textImageStepsList = gradioApp().querySelector( '#txt2img_steps' ).getElementsByTagName('input'); + if(textImageStepsList&&textImageStepsList.length> 1){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_steps')[0].props.value = parseInt(this.metadata.n_iter); + textImageStepsList[0].value = this.metadata.n_iter; + textImageStepsList[1].value = this.metadata.n_iter; + } + }catch(e){ + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_width')[0].props.value = parseInt(this.metadata['Size-1']); + const textWidthList = gradioApp().querySelector( '#txt2img_width' ).getElementsByTagName('input'); + if(textWidthList&&textWidthList.length> 1){ + textWidthList[0].value = this.metadata['Size-1']; + textWidthList[1].value = this.metadata['Size-1']; + } + }catch(e){ + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_height')[0].props.value = parseInt(this.metadata['Size-2']); + const textWidthList = gradioApp().querySelector( '#txt2img_height' ).getElementsByTagName('input'); + if(textWidthList&&textWidthList.length> 1){ + textWidthList[0].value = this.metadata['Size-2']; + textWidthList[1].value = this.metadata['Size-2']; + } + }catch(e){ + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_cfg_scale')[0].props.value = parseFloat(this.metadata['cfg_scale']); + const cfgScaleList = gradioApp().querySelector( '#txt2img_cfg_scale' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['cfg_scale']; + cfgScaleList[1].value = this.metadata['cfg_scale']; + } + }catch(e){ + } + try{ + const steps = this.metadata['Hires upscaler']; + if(steps){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_enable_hr')[0].props.value = true; + gradioApp().querySelector( '#txt2img_enable_hr' ).getElementsByTagName('input')[0].checked = true; + try{ + const originalHires = gradioApp().querySelector( '#txt2img_hires_fix' ); + originalHires.classList.remove('hidden'); + }catch(e){ + + } + const scalerMethod = this.metadata['Hires upscaler']; + const containUpscaler = window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_upscaler')[0].props.choices.includes(scalerMethod); + if(containUpscaler){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_upscaler')[0].props.value = this.metadata['Hires upscaler']; + const hr_span = gradioApp().querySelector( '#txt2img_hr_upscaler' ).getElementsByTagName('span'); + hr_span[0].textContent = this.metadata['Hires upscaler']; + + const cfgScaleList = gradioApp().querySelector( '#txt2img_enable_hr' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['cfg_scale']; + cfgScaleList[1].value = this.metadata['cfg_scale']; + } + } + try{ + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hires_steps')[0].props.value = parseInt(this.metadata['Hires steps']); + }catch(e){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hires_steps')[0].props.value = 0; + } + + const cfgScaleList = gradioApp().querySelector( '#txt2img_hires_steps' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['Hires steps']; + cfgScaleList[1].value = this.metadata['Hires steps']; + } + }catch(e){ + console.log(e); + console.log('errorhr0'); + } + + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_scale')[0].props.value = this.metadata['Hires upscale']; + const cfgScaleList = gradioApp().querySelector( '#txt2img_hr_scale' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['Hires upscale']; + cfgScaleList[1].value = this.metadata['Hires upscale']; + } + }catch(e){ + console.log(e); + console.log('errorhr'); + } + try{ + let hiresValue = parseInt(this.metadata['Hires resize-1']); + if(hiresValue == 0){ + hiresValue = parseInt(this.metadata['Size-1']); + } + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_resize_x')[0].props.value = hiresValue; + const cfgScaleList = gradioApp().querySelector( '#txt2img_hr_resize_x' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['Hires resize-1']; + cfgScaleList[1].value = this.metadata['Hires resize-1']; + } + }catch(e){ + console.log(e); + console.log('errorhr2'); + } + try{ + let hiresValueSecond = parseInt(this.metadata['Hires resize-2']); + if(hiresValueSecond == 0){ + hiresValueSecond = parseInt(this.metadata['Size-2']); + } + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_resize_y')[0].props.value = hiresValueSecond; + const cfgScaleList = gradioApp().querySelector( '#txt2img_hr_resize_y' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['Hires resize-2']; + cfgScaleList[1].value = this.metadata['Hires resize-2']; + } + }catch(e){ + console.log(e); + console.log('errorhr3'); + } + } + + + }catch(e){ + console.log(e); + console.log('errorhr4'); + } + this.close(); + }, + sendToImageToImage(){ + const userId = localStorage.getItem("userId"); + const imageId = this.imageId; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/send_to', + { + userId, + imageId, + sendType: "SEND_TO_IMAGE", + }, + { + headers + } + ) + .then(response => { + var xhr = new XMLHttpRequest(); + var self = this; + xhr.onload = function() { + var reader = new FileReader(); + reader.onloadend = function() { + self.sendToImageToImageProcess(reader.result); + } + reader.readAsDataURL(xhr.response); + }; + xhr.open('GET', this.src); + xhr.responseType = 'blob'; + xhr.send(); + this.currentItem.total_sendto = this.currentItem.total_sendto + 1; + + }).catch(error => { + this.loading = false; + console.log(error) + }) + }, + sendToImageToImageProcess(date64Image){ + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_image')[0].props.value = date64Image; + }catch(e){ + + } + try{ + const textPrompt = gradioApp().querySelector('#img2img_prompt').getElementsByTagName( 'textarea' ); + if(textPrompt&&textPrompt.length> 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_prompt')[0].props.value = this.metadata.prompt; + textPrompt[0].value = this.metadata.prompt; + } + }catch(e){ + console.log('Error prompt img2img'); + console.log(e); + + } + try{ + const negativePrompt = gradioApp().querySelector('#img2img_neg_prompt').getElementsByTagName( 'textarea' ); + if(negativePrompt&&negativePrompt.length> 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_neg_prompt')[0].props.value = this.metadata.negative_prompt; + negativePrompt[0].value = this.metadata.negative_prompt; + } + }catch(e){ + console.log('Error neg img2img'); + console.log(e); + + } + + + try{ + const samplerList = gradioApp().querySelector( '#img2img_sampling' ).getElementsByTagName('span'); + if(samplerList&&samplerList.length> 1){ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_sampling')[0].props.value = this.metadata.sampler; + samplerList[1].textContent = this.metadata.sampler; + } + }catch(e){ + } + + try{ + const textImageStepsList = gradioApp().querySelector( '#img2img_steps' ).getElementsByTagName('input'); + if(textImageStepsList&&textImageStepsList.length> 1){ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_steps')[0].props.value = parseInt(this.metadata.n_iter); + textImageStepsList[0].value = this.metadata.n_iter; + textImageStepsList[1].value = this.metadata.n_iter; + } + }catch(e){ + console.log('Error steps img2img'); + console.log(e); + + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_width')[0].props.value = parseInt(this.metadata['Size-1']); + const textWidthList = gradioApp().querySelector( '#img2img_width' ).getElementsByTagName('input'); + if(textWidthList&&textWidthList.length> 1){ + textWidthList[0].value = this.metadata['Size-1']; + textWidthList[1].value = this.metadata['Size-1']; + } + }catch(e){ + console.log('Error width img2img'); + console.log(e); + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_height')[0].props.value = parseInt(this.metadata['Size-2']); + const textWidthList = gradioApp().querySelector( '#img2img_height' ).getElementsByTagName('input'); + if(textWidthList&&textWidthList.length> 1){ + textWidthList[0].value = this.metadata['Size-2']; + textWidthList[1].value = this.metadata['Size-2']; + } + }catch(e){ + console.log('Error width height2img'); + console.log(e); + } + this.close(); + switch_to_img2img(); + }, + addToWishList(item){ + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + item.liked = true; + item.likecount = item.likecount + 1; + axios.post( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/like`, + { + userId, + imageId: item.id, + }, + { + headers + } + ) + }, + handleTextareaInput(event) { + let textarea = event.target; + textarea.style.height = 'auto'; + textarea.style.height = (textarea.scrollHeight) + 'px'; + comment = event.target.text; + }, + deleteWishList(item){ + console.log('delete'); + const userId = localStorage.getItem("userId"); + item.liked = false; + item.likecount = item.likecount -1 ; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.delete( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/like`, + { + data: { + userId, + imageId: item.id, + }, + headers + }, + ) + }, + makeSaveButtonVisible(){ + this.showCommentWrite = true; + }, + hideSaveButtonVisible(){ + this.comment = ''; + this.showCommentWrite = false; + const textArea = gradioApp().querySelector("#modal-writer-type"); + textArea.style.height = 'auto'; + textArea.style.height = (textarea.scrollHeight) + 'px'; + }, + writeComment(){ + if(this.comment.length > 0){ + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/comment`, + { + userId, + imageId: this.currentItem.id, + text: this.comment, + }, + { + headers + } + ).then((res)=>{ + this.fetchComments(); + this.showCommentWrite = false; + this.comment = ''; + this.currentItem.total_comments = this.currentItem.total_comments + 1; + }).catch((e)=>{ + console.log(e); + }); + + }else{ + return false; + } + }, + fetchComments(){ + var self = this; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.get( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/comments/${this.currentItem.id}`, + { + headers + } + ).then((res)=>{ + self.comments = res.data; + }).catch((e)=>{ + console.log(e); + }) + }, + }, + computed:{ + isModalOpen(){ + return this.showModal; + }, + }, + created() { + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.get( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/best/${userId}`, + { + headers + } + ) + .then(response => { + const dataObject = response.data; + this.userId = userId; + this.bestFeeds = dataObject.slice(0, 4); + }).catch(error => { + this.loading = false; + console.log(error) + }) + }, + }; + const fetchApp = Vue.createApp(userModel); + if (document.querySelector("#best-product-tab") != null) { + fetchApp.mount('#best-product-tab'); + }else{ + fetchApp.mount(document.getElementsByTagName("gradio-app")[0].shadowRoot.getElementById("best-product-tab")); + } + console.log('mount success'); + },1000,9000); + diff --git a/sd_feed/javascript/goosviewmodel.js b/sd_feed/javascript/goosviewmodel.js new file mode 100644 index 0000000000000000000000000000000000000000..efc81f25b66573c3b56b8ec65dc0129fcb85b1ee --- /dev/null +++ b/sd_feed/javascript/goosviewmodel.js @@ -0,0 +1,860 @@ +var installLoaded = {}; +function addScript(url) { + if (!installLoaded[url]) { + var s = document.createElement('script'); + s.src = url; + document.head.appendChild(s); + installLoaded[url] = true; + } +} +function waitForElementToDisplay(selector, callback, checkFrequencyInMs, timeoutInMs) { + (function loopSearch() { + if (document.querySelector(selector) != null&& window.localStorage.getItem("userId")) { + callback(); + return; + } + else if(document.getElementsByTagName("gradio-app").length > 0 && + document.getElementsByTagName("gradio-app")[0].shadowRoot){ + callback(); + return; + } + else { + setTimeout(function () { + loopSearch(); + }, checkFrequencyInMs); + } + })(); +} +const reorderData=(arr, columns)=>{ + const cols = columns; + const out = []; + let col = 0; + while(col < cols) { + for(let i = 0; i < arr.length; i += cols) { + let _val = arr[i + col]; + if (_val !== undefined) + out.push(_val); + } + col++; + } + return out; +} + +// addScript('https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js'); +// addScript('https://unpkg.com/vue@3.2.6/dist/vue.global.prod.js'); + + +waitForElementToDisplay( + "#html_id", + function(){ + async function copyToClipboard(textToCopy) { + // Navigator clipboard api needs a secure context (https) + if (navigator.clipboard && window.isSecureContext) { + await navigator.clipboard.writeText(textToCopy); + } else { + // Use the 'out of viewport hidden text area' trick + const textArea = document.createElement("textarea"); + textArea.value = textToCopy; + + // Move textarea out of the viewport so it's not visible + textArea.style.position = "absolute"; + textArea.style.left = "-999999px"; + + document.body.prepend(textArea); + textArea.select(); + + try { + document.execCommand('copy'); + } catch (error) { + console.error(error); + } finally { + textArea.remove(); + } + } + }; + const imageModel = { + data() { + return { + page: 1, + loading: false, + uploadLoading: false, + imageList: [], + sortedDataList: [], + carouselBtnTop: 150, + showCommentWrite: false, + modeSelectList: [ + { name: "Newest", value: "latest" }, + { name: "Popular", value: "likes" }, + { name: "Favorite", value: "favorite" }, + { name: "My Feed", value: "private" }, + ], + mode: "latest", + prompt: "", + showModal: false, + metadata: {}, + filterNsfw: false, + animeTag: false, + realTag: false, + nickname: '', + profile: '', + editMode: false, + userId: '', + searchNickname: "", + searchProfile: "", + } + }, + computed: { + parsedProfile(){ + if(!this.profile){ + return this.profile; + } + return this.profile.replaceAll("\n", "
"); + }, + parsedSearchProfile(){ + if(!this.searchProfile){ + return ''; + } + return this.searchProfile.replaceAll("\n", "
"); + } + }, + watch: { + showModal() { + if (this.showModal === false) { + window.removeEventListener("keyup", this.onEscapeKey); + } else { + window.addEventListener("keyup", this.onEscapeKey); + } + } + }, + methods: { + setEditMode(){ + this.editMode = !this.editMode; + }, + setNicknameSearch(){ + this.mode = 'nicknameSearch'; + const feedUserButton = gradioApp().querySelector('#feed-user-tab'); + const nickname = feedUserButton.getAttribute("data-value"); + this.searchNickname = nickname; + this.fetchSearchProfile(); + this.fetchNewImage(); + }, + moveFeedProfileTab(nickname){ + if(nickname){ + this.close(); + const buttonList = gradioApp().querySelector('#tabs').querySelectorAll('button'); + for (step = 0; step < buttonList.length; step++) { + // Runs 5 times, with values of step 0 through 4. + if(buttonList[step].textContent.trim() == 'Feed'){ + buttonList[step].click(); + break; + } + } + try{ + const feedUserButton = gradioApp().querySelector('#feed-user-tab'); + feedUserButton.setAttribute("data-value", nickname); + feedUserButton.innerHTML = nickname; + feedUserButton.click(); + + }catch(e){ + console.log(e); + } + + } + + }, + saveNickname(){ + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/user/profile`, + { + userId, + nickname: this.nickname, + profile: this.profile, + }, + { + headers + } + ) + .then(response => { + this.editMode = false; + }) + .catch(error => { + this.loading = false; + alert(error.response.data.detail); + }) + }, + selectAnimeTag(){ + if(this.animeTag == false){ + this.animeTag = true; + this.realTag = false; + }else{ + this.animeTag = false; + this.realTag = false; + } + this.fetchNewImage(); + }, + selectRealTag(){ + if(this.realTag == false){ + this.realTag = true; + this.animeTag = false; + }else{ + this.realTag = false; + this.animeTag = false; + } + this.fetchNewImage(); + }, + async uploadImage(event){ + this.uploadLoading = true; + const files = event.target.files; + const userId = localStorage.getItem("userId"); + for (let i=0; i 50000000) { + alert('You cannot upload file larger than 50MB'); + } else { + var body = new FormData(); + body.append('upload_file',files[i]); + body.append('userId', userId); + body.append('extractMetadata', true); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + try{ + await axios({ + url: 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/image', + method: 'post', + withCredentials:true, + data: body, + headers + }); + }catch(e){ + console.log(e); + } + } + } + this.setMode('private'); + this.uploadLoading = false; + }, + close() { + this.$emit('close'); + this.showModal=false; + this.imageId = ""; + this.src = ""; + this.comment = ''; + this.comments = []; + }, + closeOutsideModal(event) { + if(!event.target.closest('.prompt-modal-image-tag')){ + this.$emit('close'); + this.showModal=false; + this.imageId = ""; + this.src = ""; + this.comment = ''; + this.comments = []; + } + }, + onEscapeKey(event) { + if (event.keyCode === 27 || event.key === 'Escape') { + // Perform action when "Esc" key is pressed + this.close(); + } + // Perform action when "Esc" key is pressed + }, + formatNumber(num) { + if (num >= 1000000) { + return (num / 1000000).toFixed(1) + 'm'; + } else if (num >= 1000) { + return (num / 1000).toFixed(1) + 'k'; + } else { + return num.toString(); + } + }, + openModal(item){ + this.showModal = true; + this.currentItem = item; + this.metadata = item.metadata; + this.src = item.url; + this.imageId = item.id; + item.total_clicks += 1; + this.addImageClick(); + this.fetchComments(); + }, + addImageClick(){ + const userId = localStorage.getItem("userId"); + const imageId = this.imageId; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/click', + { + userId, + imageId, + }, + { + headers + } + ) + .then(response => { + + }).catch(error => { + this.loading = false; + console.log(error) + }) + }, + sendToTextToImage(){ + const userId = localStorage.getItem("userId"); + const imageId = this.imageId; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + this.currentItem.total_sendto = this.currentItem.total_sendto + 1; + axios.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/send_to', + { + userId, + imageId, + sendType: "SEND_TO_TEXT", + },{ + headers + } + ) + .then(response => { + this.sendToTextProcess(); + }).catch(error => { + this.loading = false; + console.log(error) + }) + }, + copyClipboard(){ + const userId = localStorage.getItem("userId"); + const imageId = this.imageId; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/send_to', + { + userId, + imageId, + sendType: "COPY_TO_CLIPBOARD", + },{ + headers + } + ) + .then(response => { + let filteredObject = ''; + for (const [k, v] of Object.entries(this.metadata)) { + if (/^[A-Z]/.test(k)) { + filteredObject += `${k}:${v},`; + } + } + this.currentItem.total_sendto = this.currentItem.total_sendto + 1; + copyToClipboard(filteredObject); + }).catch(error => { + this.loading = false; + console.log(error) + }); + + }, + sendToTextProcess(){ + const textPrompt = gradioApp().querySelector('#txt2img_prompt').getElementsByTagName( 'textarea' ); + if(textPrompt&&textPrompt.length> 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_prompt')[0].props.value = this.metadata.prompt; + textPrompt[0].value = this.metadata.prompt; + } + const negativePrompt = gradioApp().querySelector('#txt2img_neg_prompt').getElementsByTagName( 'textarea' ); + if(negativePrompt&&negativePrompt.length> 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_neg_prompt')[0].props.value = this.metadata.negative_prompt; + negativePrompt[0].value = this.metadata.negative_prompt; + } + try{ + const samplerList = gradioApp().querySelector( '#txt2img_sampling' ).getElementsByTagName('span'); + if(samplerList&&samplerList.length> 1){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_sampling')[0].props.value = this.metadata.sampler; + samplerList[1].textContent = this.metadata.sampler; + } + }catch(e){ + } + + try{ + const textImageStepsList = gradioApp().querySelector( '#txt2img_steps' ).getElementsByTagName('input'); + if(textImageStepsList&&textImageStepsList.length> 1){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_steps')[0].props.value = parseInt(this.metadata.n_iter); + textImageStepsList[0].value = this.metadata.n_iter; + textImageStepsList[1].value = this.metadata.n_iter; + } + }catch(e){ + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_width')[0].props.value = parseFloat(this.metadata['Size-1']); + const textWidthList = gradioApp().querySelector( '#txt2img_width' ).getElementsByTagName('input'); + if(textWidthList&&textWidthList.length> 1){ + textWidthList[0].value = this.metadata['Size-1']; + textWidthList[1].value = this.metadata['Size-1']; + } + }catch(e){ + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_height')[0].props.value = parseFloat(this.metadata['Size-2']); + const textWidthList = gradioApp().querySelector( '#txt2img_height' ).getElementsByTagName('input'); + if(textWidthList&&textWidthList.length> 1){ + textWidthList[0].value = this.metadata['Size-2']; + textWidthList[1].value = this.metadata['Size-2']; + } + }catch(e){ + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_cfg_scale')[0].props.value = parseFloat(this.metadata['cfg_scale']); + const cfgScaleList = gradioApp().querySelector( '#txt2img_cfg_scale' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['cfg_scale']; + cfgScaleList[1].value = this.metadata['cfg_scale']; + } + }catch(e){ + } + try{ + const steps = this.metadata['Hires upscaler']; + if(steps){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_enable_hr')[0].props.value = true; + gradioApp().querySelector( '#txt2img_enable_hr' ).getElementsByTagName('input')[0].checked = true; + try{ + const originalHires = gradioApp().querySelector( '#txt2img_hires_fix' ); + originalHires.classList.remove('hidden'); + }catch(e){ + + } + const scalerMethod = this.metadata['Hires upscaler']; + const containUpscaler = window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_upscaler')[0].props.choices.includes(scalerMethod); + if(containUpscaler){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_upscaler')[0].props.value = this.metadata['Hires upscaler']; + const hr_span = gradioApp().querySelector( '#txt2img_hr_upscaler' ).getElementsByTagName('span'); + hr_span[0].textContent = this.metadata['Hires upscaler']; + + const cfgScaleList = gradioApp().querySelector( '#txt2img_enable_hr' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['cfg_scale']; + cfgScaleList[1].value = this.metadata['cfg_scale']; + } + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hires_steps')[0].props.value = parseInt(this.metadata['Hires steps']); + const cfgScaleList = gradioApp().querySelector( '#txt2img_hires_steps' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['Hires steps']; + cfgScaleList[1].value = this.metadata['Hires steps']; + } + }catch(e){ + console.log(e); + console.log('errorhr0'); + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_scale')[0].props.value = parseFloat(this.metadata['Hires upscale']); + const cfgScaleList = gradioApp().querySelector( '#txt2img_hr_scale' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['Hires upscale']; + cfgScaleList[1].value = this.metadata['Hires upscale']; + } + }catch(e){ + console.log(e); + console.log('errorhr'); + } + try{ + const hiresValue1 = parseInt(this.metadata['Hires resize-1']); + console.log(hiresValue1); + if(hiresValue1 && hiresValue1 > 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_resize_x')[0].props.value = parseInt(this.metadata['Hires resize-1']); + const cfgScaleList = gradioApp().querySelector( '#txt2img_hr_resize_x' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['Hires resize-1']; + cfgScaleList[1].value = this.metadata['Hires resize-1']; + } + } + }catch(e){ + console.log(e); + console.log('errorhr2'); + } + try{ + const hiresValue2 = parseInt(this.metadata['Hires resize-2']); + console.log(hiresValue2); + if(hiresValue2 > 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='txt2img_hr_resize_y')[0].props.value = parseInt(this.metadata['Hires resize-2']); + const cfgScaleList = gradioApp().querySelector( '#txt2img_hr_resize_y' ).getElementsByTagName('input'); + if(cfgScaleList&&cfgScaleList.length> 1){ + cfgScaleList[0].value = this.metadata['Hires resize-2']; + cfgScaleList[1].value = this.metadata['Hires resize-2']; + } + } + }catch(e){ + console.log(e); + console.log('errorhr3'); + } + } + + + + }catch(e){ + console.log(e); + console.log('errorhr4'); + } + this.close(); + switch_to_txt2img(); + }, + sendToImageToImage(){ + const userId = localStorage.getItem("userId"); + const imageId = this.imageId; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/send_to', + { + userId, + imageId, + sendType: "SEND_TO_IMAGE", + },{ + headers + } + ) + .then(response => { + var xhr = new XMLHttpRequest(); + var self = this; + xhr.onload = function() { + var reader = new FileReader(); + reader.onloadend = function() { + self.sendToImageToImageProcess(reader.result); + } + reader.readAsDataURL(xhr.response); + }; + xhr.open('GET', this.src); + xhr.responseType = 'blob'; + xhr.send(); + this.currentItem.total_sendto = this.currentItem.total_sendto + 1; + + }).catch(error => { + this.loading = false; + console.log(error) + }) + }, + sendToImageToImageProcess(date64Image){ + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_image')[0].props.value = date64Image; + }catch(e){ + + } + try{ + const textPrompt = gradioApp().querySelector('#img2img_prompt').getElementsByTagName( 'textarea' ); + if(textPrompt&&textPrompt.length> 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_prompt')[0].props.value = this.metadata.prompt; + textPrompt[0].value = this.metadata.prompt; + } + }catch(e){ + console.log('Error prompt img2img'); + console.log(e); + + } + try{ + const negativePrompt = gradioApp().querySelector('#img2img_neg_prompt').getElementsByTagName( 'textarea' ); + if(negativePrompt&&negativePrompt.length> 0){ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_neg_prompt')[0].props.value = this.metadata.negative_prompt; + negativePrompt[0].value = this.metadata.negative_prompt; + } + }catch(e){ + console.log('Error neg img2img'); + console.log(e); + + } + + + try{ + const samplerList = gradioApp().querySelector( '#img2img_sampling' ).getElementsByTagName('span'); + if(samplerList&&samplerList.length> 1){ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_sampling')[0].props.value = this.metadata.sampler; + samplerList[1].textContent = this.metadata.sampler; + } + }catch(e){ + } + + try{ + const textImageStepsList = gradioApp().querySelector( '#img2img_steps' ).getElementsByTagName('input'); + if(textImageStepsList&&textImageStepsList.length> 1){ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_steps')[0].props.value = parseInt(this.metadata.n_iter); + textImageStepsList[0].value = this.metadata.n_iter; + textImageStepsList[1].value = this.metadata.n_iter; + } + }catch(e){ + console.log('Error steps img2img'); + console.log(e); + + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_width')[0].props.value = parseInt(this.metadata['Size-1']); + const textWidthList = gradioApp().querySelector( '#img2img_width' ).getElementsByTagName('input'); + if(textWidthList&&textWidthList.length> 1){ + textWidthList[0].value = this.metadata['Size-1']; + textWidthList[1].value = this.metadata['Size-1']; + } + }catch(e){ + console.log('Error width img2img'); + console.log(e); + } + try{ + window.gradio_config.components.filter(el=>el.props.elem_id=='img2img_height')[0].props.value = parseInt(this.metadata['Size-2']); + const textWidthList = gradioApp().querySelector( '#img2img_height' ).getElementsByTagName('input'); + if(textWidthList&&textWidthList.length> 1){ + textWidthList[0].value = this.metadata['Size-2']; + textWidthList[1].value = this.metadata['Size-2']; + } + }catch(e){ + console.log('Error width height2img'); + console.log(e); + } + this.close(); + switch_to_img2img(); + }, + addToWishList(item){ + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + item.liked = true; + item.likecount = item.likecount + 1; + axios.post( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/like`, + { + userId, + imageId: item.id, + }, + { + headers + } + ) + }, + handleTextareaInput(event) { + let textarea = event.target; + textarea.style.height = 'auto'; + textarea.style.height = (textarea.scrollHeight) + 'px'; + comment = event.target.text; + }, + deleteWishList(item){ + const userId = localStorage.getItem("userId"); + item.liked = false; + item.likecount = item.likecount -1 ; + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.delete( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/like`, + {data: { + userId, + imageId: item.id, + }, + headers + }, + ) + }, + makeSaveButtonVisible(){ + this.showCommentWrite = true; + }, + hideSaveButtonVisible(){ + this.comment = ''; + this.showCommentWrite = false; + const textArea = gradioApp().querySelector("#modal-writer-type"); + textArea.style.height = 'auto'; + textArea.style.height = (textarea.scrollHeight) + 'px'; + }, + writeComment(){ + if(this.comment.length > 0){ + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/comment`, + { + userId, + imageId: this.currentItem.id, + text: this.comment, + },{ + headers + } + ).then((res)=>{ + this.fetchComments(); + this.showCommentWrite = false; + this.comment = ''; + this.currentItem.total_comments = this.currentItem.total_comments + 1; + }).catch((e)=>{ + console.log(e); + }); + + }else{ + return false; + } + }, + fetchComments(){ + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.get( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/comments/${this.currentItem.id}`, + { + headers + } + ).then((res)=>{ + this.comments = res.data; + this.$forceUpdate(); + }).catch((e)=>{ + console.log(e); + }) + }, + setOrder(event){ + this.page = 1; + this.order = event.target.value; + this.fetchImages(); + }, + setPublic(event){ + this.page = 1; + this.mode = event.target.value; + this.fetchImages(); + }, + setMode(mode){ + this.page = 1; + this.mode = mode; + this.fetchImages(); + }, + fetchSearchProfile(){ + const params = { + nickname: this.searchNickname, + }; + axios.get( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/user/profile_nickname`, + { + params + } + ).then((res)=>{ + this.searchProfile = res.data.profile; + this.$forceUpdate(); + }).catch((e)=>{ + console.log(e); + }) + }, + fetchNewImage(){ + this.page = 1; + this.fetchImages(); + }, + fetchImages(){ + this.loading = true; + if(this.page == -1){ + this.loading = false; + return false; + } + const userId = localStorage.getItem("userId"); + const defaultParams = { + page: this.page, + batch_size: 100, + prompt: this.prompt, + filter_nsfw: this.filterNsfw, + }; + if(this.mode == 'latest'){ + defaultParams['order'] = 'created_at'; + } + if(this.mode == 'nicknameSearch'){ + defaultParams['nickname'] = this.searchNickname; + defaultParams['order'] = 'created_at'; + } + if(this.animeTag){ + defaultParams['image_tag'] = 'ANIME'; + } + if(this.realTag){ + defaultParams['image_tag'] = 'REAL'; + } + if(this.mode == 'likes'){ + defaultParams['order'] = 'likes'; + } + if(this.mode == 'favorite'){ + defaultParams['only_liked_pictures'] = true; + defaultParams['order'] = 'likes_created'; + } + if(this.mode == 'private'){ + defaultParams['only_my_pictures'] = true; + defaultParams['order'] = 'created_at'; + } + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + + axios.get( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/images/${userId}`, + {params: defaultParams, headers}, + ) + .then(response => { + if(this.page == 1){ + this.imageList = response.data; + }else{ + this.imageList = [...this.imageList, ...response.data]; + } + this.sortedDataList = reorderData(this.imageList, 4); + if(response.data.length < 100){ + this.page = -1; + } + this.loading = false; + }) + .catch(error => { + this.loading = false; + console.log(error) + }) + + } + }, + mounted(){ + var self = this; + waitForElementToDisplay('#feed-header', function(){ + window.addEventListener('scroll', e => { + const listElem = gradioApp().querySelector("#columns"); + const tabElem = gradioApp().querySelector("#tab_newtype_tab"); + const tabNotVisible = tabElem && tabElem.style && tabElem.style.display && tabElem.style.display == 'none'; + if(listElem&&listElem.clientHeight * 0.8 <= window.scrollY && self.loading == false && self.page > 0 && !tabNotVisible) { + self.page = self.page + 1; + self.fetchImages(); + } + }, false); + },1000,9000); + + }, + beforeDestroy(){ + + }, + created() { + this.fetchImages(); + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.get( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/user/profile/${userId}`, + { + headers + } + ) + .then(response => { + const dataObject = response.data;; + this.likeCount = dataObject.likecount; + this.nickname = dataObject.nickname; + this.profile = dataObject.profile; + this.userId = userId; + }).catch(error => { + this.loading = false; + console.log(error) + }) + }, + }; + const fetchApp = Vue.createApp(imageModel); + if (document.querySelector("#vue-elem") != null) { + fetchApp.mount('#vue-elem'); + }else{ + fetchApp.mount(document.getElementsByTagName("gradio-app")[0].shadowRoot.getElementById("vue-elem")); + } + // const fileInput = gradioApp().querySelector('#feed-image-upload'); + // fileInput.addEventListener("change", function() { + // fileInput.dispatchEvent(new CustomEvent("on_file_upload")); + // setTimeout(() =>{ + // const el = gradioApp().querySelector( + // '#feed-search-btn' + // ); + // el.click(); + // }, 2000); + // }); + console.log("mount success"); + },1000,9000); \ No newline at end of file diff --git a/sd_feed/javascript/loradownload.js b/sd_feed/javascript/loradownload.js new file mode 100644 index 0000000000000000000000000000000000000000..c5e8241090ef7055a0c1328807b6ca7f4fa32e05 --- /dev/null +++ b/sd_feed/javascript/loradownload.js @@ -0,0 +1,55 @@ + +waitForElementToDisplay( + "#lora-search-table", + function(){ + const loraModel = { + data() { + return { + loraList: [], + loraString: '', + } + }, + methods: { + setUrlData(url, fname){ + const textArea = gradioApp().querySelector("#lora-download-url") + textArea.value = url; + const fnameInput = gradioApp().querySelector("#lora-filename") + fnameInput.value = fname; + const downloadBtn = gradioApp().querySelector('#lora_download_btn'); + downloadBtn.click(); + } + }, + mounted(){ + var self = this; + const textArea = gradioApp().querySelector("#table-data").querySelector('textarea'); + const searchLoraBtn = gradioApp().querySelector("#lora_search_button"); + const tableArea = gradioApp().querySelector("#table-data"); + searchLoraBtn.addEventListener('click', (e)=>{ + + const interval = 500; // 1 second + const duration = 15000; // 15 seconds + let count = 0; + const timer = setInterval(() => { + // Perform your desired actions here + count += interval; + const textArea = gradioApp().querySelector("#table-data").querySelector('textarea'); + const textAreaValue = textArea.value; + let newJson; + try{ + newJson = JSON.parse(textAreaValue.replace('(','[').replace(',)', ')').replace(')',']').replaceAll("'", '"')); + }catch(e){ + console.log(e); + newJson = []; + } + if (textAreaValue !== self.loraString||count >= duration) { + self.loraString = textAreaValue; + self.loraList = newJson; + clearInterval(timer); + } + }, interval); + }); + }, + }; + const loraApp = Vue.createApp(loraModel); + loraApp.mount(gradioApp().querySelector("#lora-search-table")); + },1000,9000); \ No newline at end of file diff --git a/sd_feed/javascript/userprofile.js b/sd_feed/javascript/userprofile.js new file mode 100644 index 0000000000000000000000000000000000000000..4db731d00f7811c683d2098df330e1b59a6bb430 --- /dev/null +++ b/sd_feed/javascript/userprofile.js @@ -0,0 +1,74 @@ +waitForElementToDisplay( + "#feed-profile-tab", + function(){ + const userModel = { + data() { + return { + userId: '', + nickname: '', + likeCount: 0, + editMode: false, + loading: false, + } + }, + methods: { + close() {}, + mounted(){}, + beforeDestroy(){}, + setEditMode(){ + this.editMode = !this.editMode; + }, + saveNickname(){ + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.post( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/user/profile`, + { + userId, + nickname: this.nickname, + }, + { + headers + } + ) + .then(response => { + this.editMode = false; + }) + .catch(error => { + this.loading = false; + alert(error.response.data.detail); + }) + }, + + }, + created() { + const userId = localStorage.getItem("userId"); + const token = localStorage.getItem("token"); + const headers={"Authorization":"Token " + token}; + axios.get( + `https://newtypev3-server-vjiloyvjvq-an.a.run.app/user/profile/${userId}`, + { + headers + } + ) + .then(response => { + const dataObject = response.data;; + this.likeCount = dataObject.likecount; + this.nickname = dataObject.nickname; + this.userId = userId; + }).catch(error => { + this.loading = false; + console.log(error) + }) + }, + }; + const fetchApp = Vue.createApp(userModel); + if (document.querySelector("#feed-profile-tab") != null) { + fetchApp.mount('#feed-profile-tab'); + }else{ + fetchApp.mount(document.getElementsByTagName("gradio-app")[0].shadowRoot.getElementById("feed-profile-tab")); + } + + console.log("mount success"); + },1000,9000); \ No newline at end of file diff --git a/sd_feed/javascript/vue.global.js b/sd_feed/javascript/vue.global.js new file mode 100644 index 0000000000000000000000000000000000000000..f5a0b769a2311c9e58b80f1670ffda14aec087b7 --- /dev/null +++ b/sd_feed/javascript/vue.global.js @@ -0,0 +1 @@ +var Vue=function(e){"use strict";function t(e,t){const n=Object.create(null),o=e.split(",");for(let r=0;r!!n[e.toLowerCase()]:e=>!!n[e]}const n=t("Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt"),o=t("itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly");function r(e){return!!e||""===e}function s(e){if(N(e)){const t={};for(let n=0;n{if(e){const n=e.split(l);n.length>1&&(t[n[0].trim()]=n[1].trim())}})),t}function a(e){let t="";if(A(e))t=e;else if(N(e))for(let n=0;nd(e,t)))}const m=(e,t)=>t&&t.__v_isRef?m(e,t.value):E(t)?{[`Map(${t.size})`]:[...t.entries()].reduce(((e,[t,n])=>(e[`${t} =>`]=n,e)),{})}:$(t)?{[`Set(${t.size})`]:[...t.values()]}:!O(t)||N(t)||B(t)?t:String(t),g={},v=[],y=()=>{},b=()=>!1,_=/^on[^a-z]/,S=e=>_.test(e),x=e=>e.startsWith("onUpdate:"),C=Object.assign,w=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},k=Object.prototype.hasOwnProperty,T=(e,t)=>k.call(e,t),N=Array.isArray,E=e=>"[object Map]"===V(e),$=e=>"[object Set]"===V(e),R=e=>e instanceof Date,F=e=>"function"==typeof e,A=e=>"string"==typeof e,M=e=>"symbol"==typeof e,O=e=>null!==e&&"object"==typeof e,P=e=>O(e)&&F(e.then)&&F(e.catch),I=Object.prototype.toString,V=e=>I.call(e),B=e=>"[object Object]"===V(e),L=e=>A(e)&&"NaN"!==e&&"-"!==e[0]&&""+parseInt(e,10)===e,j=t(",key,ref,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),U=e=>{const t=Object.create(null);return n=>t[n]||(t[n]=e(n))},H=/-(\w)/g,D=U((e=>e.replace(H,((e,t)=>t?t.toUpperCase():"")))),W=/\B([A-Z])/g,z=U((e=>e.replace(W,"-$1").toLowerCase())),K=U((e=>e.charAt(0).toUpperCase()+e.slice(1))),G=U((e=>e?`on${K(e)}`:"")),q=(e,t)=>!Object.is(e,t),J=(e,t)=>{for(let n=0;n{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:n})},Q=e=>{const t=parseFloat(e);return isNaN(t)?e:t};let X;const Y=[];class ee{constructor(e=!1){this.active=!0,this.effects=[],this.cleanups=[],!e&&X&&(this.parent=X,this.index=(X.scopes||(X.scopes=[])).push(this)-1)}run(e){if(this.active)try{return this.on(),e()}finally{this.off()}}on(){this.active&&(Y.push(this),X=this)}off(){this.active&&(Y.pop(),X=Y[Y.length-1])}stop(e){if(this.active){if(this.effects.forEach((e=>e.stop())),this.cleanups.forEach((e=>e())),this.scopes&&this.scopes.forEach((e=>e.stop(!0))),this.parent&&!e){const e=this.parent.scopes.pop();e&&e!==this&&(this.parent.scopes[this.index]=e,e.index=this.index)}this.active=!1}}}function te(e,t){(t=t||X)&&t.active&&t.effects.push(e)}const ne=e=>{const t=new Set(e);return t.w=0,t.n=0,t},oe=e=>(e.w&le)>0,re=e=>(e.n&le)>0,se=new WeakMap;let ie=0,le=1;const ce=[];let ae;const ue=Symbol(""),pe=Symbol("");class fe{constructor(e,t=null,n){this.fn=e,this.scheduler=t,this.active=!0,this.deps=[],te(this,n)}run(){if(!this.active)return this.fn();if(!ce.includes(this))try{return ce.push(ae=this),me.push(he),he=!0,le=1<<++ie,ie<=30?(({deps:e})=>{if(e.length)for(let t=0;t{const{deps:t}=e;if(t.length){let n=0;for(let o=0;o0?ce[e-1]:void 0}}stop(){this.active&&(de(this),this.onStop&&this.onStop(),this.active=!1)}}function de(e){const{deps:t}=e;if(t.length){for(let n=0;n{("length"===t||t>=o)&&l.push(e)}));else switch(void 0!==n&&l.push(i.get(n)),t){case"add":N(e)?L(n)&&l.push(i.get("length")):(l.push(i.get(ue)),E(e)&&l.push(i.get(pe)));break;case"delete":N(e)||(l.push(i.get(ue)),E(e)&&l.push(i.get(pe)));break;case"set":E(e)&&l.push(i.get(ue))}if(1===l.length)l[0]&&xe(l[0]);else{const e=[];for(const t of l)t&&e.push(...t);xe(ne(e))}}function xe(e,t){for(const n of N(e)?e:[...e])(n!==ae||n.allowRecurse)&&(n.scheduler?n.scheduler():n.run())}const Ce=t("__proto__,__v_isRef,__isVue"),we=new Set(Object.getOwnPropertyNames(Symbol).map((e=>Symbol[e])).filter(M)),ke=Fe(),Te=Fe(!1,!0),Ne=Fe(!0),Ee=Fe(!0,!0),$e=Re();function Re(){const e={};return["includes","indexOf","lastIndexOf"].forEach((t=>{e[t]=function(...e){const n=bt(this);for(let t=0,r=this.length;t{e[t]=function(...e){ge();const n=bt(this)[t].apply(this,e);return ve(),n}})),e}function Fe(e=!1,t=!1){return function(n,o,r){if("__v_isReactive"===o)return!e;if("__v_isReadonly"===o)return e;if("__v_raw"===o&&r===(e?t?ut:at:t?ct:lt).get(n))return n;const s=N(n);if(!e&&s&&T($e,o))return Reflect.get($e,o,r);const i=Reflect.get(n,o,r);if(M(o)?we.has(o):Ce(o))return i;if(e||ye(n,0,o),t)return i;if(wt(i)){return!s||!L(o)?i.value:i}return O(i)?e?ht(i):ft(i):i}}function Ae(e=!1){return function(t,n,o,r){let s=t[n];if(!e&&(o=bt(o),s=bt(s),!N(t)&&wt(s)&&!wt(o)))return s.value=o,!0;const i=N(t)&&L(n)?Number(n)!0,deleteProperty:(e,t)=>!0},Pe=C({},Me,{get:Te,set:Ae(!0)}),Ie=C({},Oe,{get:Ee}),Ve=e=>O(e)?ft(e):e,Be=e=>O(e)?ht(e):e,Le=e=>e,je=e=>Reflect.getPrototypeOf(e);function Ue(e,t,n=!1,o=!1){const r=bt(e=e.__v_raw),s=bt(t);t!==s&&!n&&ye(r,0,t),!n&&ye(r,0,s);const{has:i}=je(r),l=o?Le:n?Be:Ve;return i.call(r,t)?l(e.get(t)):i.call(r,s)?l(e.get(s)):void(e!==r&&e.get(t))}function He(e,t=!1){const n=this.__v_raw,o=bt(n),r=bt(e);return e!==r&&!t&&ye(o,0,e),!t&&ye(o,0,r),e===r?n.has(e):n.has(e)||n.has(r)}function De(e,t=!1){return e=e.__v_raw,!t&&ye(bt(e),0,ue),Reflect.get(e,"size",e)}function We(e){e=bt(e);const t=bt(this);return je(t).has.call(t,e)||(t.add(e),Se(t,"add",e,e)),this}function ze(e,t){t=bt(t);const n=bt(this),{has:o,get:r}=je(n);let s=o.call(n,e);s||(e=bt(e),s=o.call(n,e));const i=r.call(n,e);return n.set(e,t),s?q(t,i)&&Se(n,"set",e,t):Se(n,"add",e,t),this}function Ke(e){const t=bt(this),{has:n,get:o}=je(t);let r=n.call(t,e);r||(e=bt(e),r=n.call(t,e)),o&&o.call(t,e);const s=t.delete(e);return r&&Se(t,"delete",e,void 0),s}function Ge(){const e=bt(this),t=0!==e.size,n=e.clear();return t&&Se(e,"clear",void 0,void 0),n}function qe(e,t){return function(n,o){const r=this,s=r.__v_raw,i=bt(s),l=t?Le:e?Be:Ve;return!e&&ye(i,0,ue),s.forEach(((e,t)=>n.call(o,l(e),l(t),r)))}}function Je(e,t,n){return function(...o){const r=this.__v_raw,s=bt(r),i=E(s),l="entries"===e||e===Symbol.iterator&&i,c="keys"===e&&i,a=r[e](...o),u=n?Le:t?Be:Ve;return!t&&ye(s,0,c?pe:ue),{next(){const{value:e,done:t}=a.next();return t?{value:e,done:t}:{value:l?[u(e[0]),u(e[1])]:u(e),done:t}},[Symbol.iterator](){return this}}}}function Ze(e){return function(...t){return"delete"!==e&&this}}function Qe(){const e={get(e){return Ue(this,e)},get size(){return De(this)},has:He,add:We,set:ze,delete:Ke,clear:Ge,forEach:qe(!1,!1)},t={get(e){return Ue(this,e,!1,!0)},get size(){return De(this)},has:He,add:We,set:ze,delete:Ke,clear:Ge,forEach:qe(!1,!0)},n={get(e){return Ue(this,e,!0)},get size(){return De(this,!0)},has(e){return He.call(this,e,!0)},add:Ze("add"),set:Ze("set"),delete:Ze("delete"),clear:Ze("clear"),forEach:qe(!0,!1)},o={get(e){return Ue(this,e,!0,!0)},get size(){return De(this,!0)},has(e){return He.call(this,e,!0)},add:Ze("add"),set:Ze("set"),delete:Ze("delete"),clear:Ze("clear"),forEach:qe(!0,!0)};return["keys","values","entries",Symbol.iterator].forEach((r=>{e[r]=Je(r,!1,!1),n[r]=Je(r,!0,!1),t[r]=Je(r,!1,!0),o[r]=Je(r,!0,!0)})),[e,n,t,o]}const[Xe,Ye,et,tt]=Qe();function nt(e,t){const n=t?e?tt:et:e?Ye:Xe;return(t,o,r)=>"__v_isReactive"===o?!e:"__v_isReadonly"===o?e:"__v_raw"===o?t:Reflect.get(T(n,o)&&o in t?n:t,o,r)}const ot={get:nt(!1,!1)},rt={get:nt(!1,!0)},st={get:nt(!0,!1)},it={get:nt(!0,!0)},lt=new WeakMap,ct=new WeakMap,at=new WeakMap,ut=new WeakMap;function pt(e){return e.__v_skip||!Object.isExtensible(e)?0:function(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}((e=>V(e).slice(8,-1))(e))}function ft(e){return e&&e.__v_isReadonly?e:mt(e,!1,Me,ot,lt)}function dt(e){return mt(e,!1,Pe,rt,ct)}function ht(e){return mt(e,!0,Oe,st,at)}function mt(e,t,n,o,r){if(!O(e))return e;if(e.__v_raw&&(!t||!e.__v_isReactive))return e;const s=r.get(e);if(s)return s;const i=pt(e);if(0===i)return e;const l=new Proxy(e,2===i?o:n);return r.set(e,l),l}function gt(e){return vt(e)?gt(e.__v_raw):!(!e||!e.__v_isReactive)}function vt(e){return!(!e||!e.__v_isReadonly)}function yt(e){return gt(e)||vt(e)}function bt(e){const t=e&&e.__v_raw;return t?bt(t):e}function _t(e){return Z(e,"__v_skip",!0),e}function St(e){be()&&((e=bt(e)).dep||(e.dep=ne()),_e(e.dep))}function xt(e,t){(e=bt(e)).dep&&xe(e.dep)}const Ct=e=>O(e)?ft(e):e;function wt(e){return Boolean(e&&!0===e.__v_isRef)}function kt(e){return Nt(e,!1)}class Tt{constructor(e,t){this._shallow=t,this.dep=void 0,this.__v_isRef=!0,this._rawValue=t?e:bt(e),this._value=t?e:Ct(e)}get value(){return St(this),this._value}set value(e){e=this._shallow?e:bt(e),q(e,this._rawValue)&&(this._rawValue=e,this._value=this._shallow?e:Ct(e),xt(this))}}function Nt(e,t){return wt(e)?e:new Tt(e,t)}function Et(e){return wt(e)?e.value:e}const $t={get:(e,t,n)=>Et(Reflect.get(e,t,n)),set:(e,t,n,o)=>{const r=e[t];return wt(r)&&!wt(n)?(r.value=n,!0):Reflect.set(e,t,n,o)}};function Rt(e){return gt(e)?e:new Proxy(e,$t)}class Ft{constructor(e){this.dep=void 0,this.__v_isRef=!0;const{get:t,set:n}=e((()=>St(this)),(()=>xt(this)));this._get=t,this._set=n}get value(){return this._get()}set value(e){this._set(e)}}class At{constructor(e,t){this._object=e,this._key=t,this.__v_isRef=!0}get value(){return this._object[this._key]}set value(e){this._object[this._key]=e}}function Mt(e,t){const n=e[t];return wt(n)?n:new At(e,t)}class Ot{constructor(e,t,n){this._setter=t,this.dep=void 0,this._dirty=!0,this.__v_isRef=!0,this.effect=new fe(e,(()=>{this._dirty||(this._dirty=!0,xt(this))})),this.__v_isReadonly=n}get value(){const e=bt(this);return St(e),e._dirty&&(e._dirty=!1,e._value=e.effect.run()),e._value}set value(e){this._setter(e)}}function Pt(e,t){let n,o;F(e)?(n=e,o=y):(n=e.get,o=e.set);return new Ot(n,o,F(e)||!e.set)}function It(e,t,...n){const o=e.vnode.props||g;let r=n;const s=t.startsWith("update:"),i=s&&t.slice(7);if(i&&i in o){const e=`${"modelValue"===i?"model":i}Modifiers`,{number:t,trim:s}=o[e]||g;s?r=n.map((e=>e.trim())):t&&(r=n.map(Q))}let l,c=o[l=G(t)]||o[l=G(D(t))];!c&&s&&(c=o[l=G(z(t))]),c&&Fr(c,e,6,r);const a=o[l+"Once"];if(a){if(e.emitted){if(e.emitted[l])return}else e.emitted={};e.emitted[l]=!0,Fr(a,e,6,r)}}function Vt(e,t,n=!1){const o=t.emitsCache,r=o.get(e);if(void 0!==r)return r;const s=e.emits;let i={},l=!1;if(!F(e)){const o=e=>{const n=Vt(e,t,!0);n&&(l=!0,C(i,n))};!n&&t.mixins.length&&t.mixins.forEach(o),e.extends&&o(e.extends),e.mixins&&e.mixins.forEach(o)}return s||l?(N(s)?s.forEach((e=>i[e]=null)):C(i,s),o.set(e,i),i):(o.set(e,null),null)}function Bt(e,t){return!(!e||!S(t))&&(t=t.slice(2).replace(/Once$/,""),T(e,t[0].toLowerCase()+t.slice(1))||T(e,z(t))||T(e,t))}let Lt=null,jt=null;function Ut(e){const t=Lt;return Lt=e,jt=e&&e.type.__scopeId||null,t}function Ht(e,t=Lt,n){if(!t)return e;if(e._n)return e;const o=(...n)=>{o._d&&jo(-1);const r=Ut(t),s=e(...n);return Ut(r),o._d&&jo(1),s};return o._n=!0,o._c=!0,o._d=!0,o}function Dt(e){const{type:t,vnode:n,proxy:o,withProxy:r,props:s,propsOptions:[i],slots:l,attrs:c,emit:a,render:u,renderCache:p,data:f,setupState:d,ctx:h,inheritAttrs:m}=e;let g;const v=Ut(e);try{let e;if(4&n.shapeFlag){const t=r||o;g=Yo(u.call(t,t,p,s,d,f,h)),e=c}else{const n=t;0,g=Yo(n(s,n.length>1?{attrs:c,slots:l,emit:a}:null)),e=t.props?c:zt(c)}let v=g;if(e&&!1!==m){const t=Object.keys(e),{shapeFlag:n}=v;t.length&&7&n&&(i&&t.some(x)&&(e=Kt(e,i)),v=Qo(v,e))}0,n.dirs&&(v.dirs=v.dirs?v.dirs.concat(n.dirs):n.dirs),n.transition&&(v.transition=n.transition),g=v}catch(y){Po.length=0,Ar(y,e,1),g=Jo(Mo)}return Ut(v),g}function Wt(e){let t;for(let n=0;n{let t;for(const n in e)("class"===n||"style"===n||S(n))&&((t||(t={}))[n]=e[n]);return t},Kt=(e,t)=>{const n={};for(const o in e)x(o)&&o.slice(9)in t||(n[o]=e[o]);return n};function Gt(e,t,n){const o=Object.keys(t);if(o.length!==Object.keys(e).length)return!0;for(let r=0;r0?(Zt(e,"onPending"),Zt(e,"onFallback"),a(null,e.ssFallback,t,n,o,null,s,i),en(f,e.ssFallback)):f.resolve()}(t,n,o,r,s,i,l,c,a):function(e,t,n,o,r,s,i,l,{p:c,um:a,o:{createElement:u}}){const p=t.suspense=e.suspense;p.vnode=t,t.el=e.el;const f=t.ssContent,d=t.ssFallback,{activeBranch:h,pendingBranch:m,isInFallback:g,isHydrating:v}=p;if(m)p.pendingBranch=f,Wo(f,m)?(c(m,f,p.hiddenContainer,null,r,p,s,i,l),p.deps<=0?p.resolve():g&&(c(h,d,n,o,r,null,s,i,l),en(p,d))):(p.pendingId++,v?(p.isHydrating=!1,p.activeBranch=m):a(m,r,p),p.deps=0,p.effects.length=0,p.hiddenContainer=u("div"),g?(c(null,f,p.hiddenContainer,null,r,p,s,i,l),p.deps<=0?p.resolve():(c(h,d,n,o,r,null,s,i,l),en(p,d))):h&&Wo(f,h)?(c(h,f,n,o,r,p,s,i,l),p.resolve(!0)):(c(null,f,p.hiddenContainer,null,r,p,s,i,l),p.deps<=0&&p.resolve()));else if(h&&Wo(f,h))c(h,f,n,o,r,p,s,i,l),en(p,f);else if(Zt(t,"onPending"),p.pendingBranch=f,p.pendingId++,c(null,f,p.hiddenContainer,null,r,p,s,i,l),p.deps<=0)p.resolve();else{const{timeout:e,pendingId:t}=p;e>0?setTimeout((()=>{p.pendingId===t&&p.fallback(d)}),e):0===e&&p.fallback(d)}}(e,t,n,o,r,i,l,c,a)},hydrate:function(e,t,n,o,r,s,i,l,c){const a=t.suspense=Qt(t,o,n,e.parentNode,document.createElement("div"),null,r,s,i,l,!0),u=c(e,a.pendingBranch=t.ssContent,n,a,s,i);0===a.deps&&a.resolve();return u},create:Qt,normalize:function(e){const{shapeFlag:t,children:n}=e,o=32&t;e.ssContent=Xt(o?n.default:n),e.ssFallback=o?Xt(n.fallback):Jo(Comment)}};function Zt(e,t){const n=e.props&&e.props[t];F(n)&&n()}function Qt(e,t,n,o,r,s,i,l,c,a,u=!1){const{p:p,m:f,um:d,n:h,o:{parentNode:m,remove:g}}=a,v=Q(e.props&&e.props.timeout),y={vnode:e,parent:t,parentComponent:n,isSVG:i,container:o,hiddenContainer:r,anchor:s,deps:0,pendingId:0,timeout:"number"==typeof v?v:-1,activeBranch:null,pendingBranch:null,isInFallback:!0,isHydrating:u,isUnmounted:!1,effects:[],resolve(e=!1){const{vnode:t,activeBranch:n,pendingBranch:o,pendingId:r,effects:s,parentComponent:i,container:l}=y;if(y.isHydrating)y.isHydrating=!1;else if(!e){const e=n&&o.transition&&"out-in"===o.transition.mode;e&&(n.transition.afterLeave=()=>{r===y.pendingId&&f(o,l,t,0)});let{anchor:t}=y;n&&(t=h(n),d(n,i,y,!0)),e||f(o,l,t,0)}en(y,o),y.pendingBranch=null,y.isInFallback=!1;let c=y.parent,a=!1;for(;c;){if(c.pendingBranch){c.effects.push(...s),a=!0;break}c=c.parent}a||Zr(s),y.effects=[],Zt(t,"onResolve")},fallback(e){if(!y.pendingBranch)return;const{vnode:t,activeBranch:n,parentComponent:o,container:r,isSVG:s}=y;Zt(t,"onFallback");const i=h(n),a=()=>{y.isInFallback&&(p(null,e,r,i,o,null,s,l,c),en(y,e))},u=e.transition&&"out-in"===e.transition.mode;u&&(n.transition.afterLeave=a),y.isInFallback=!0,d(n,o,null,!0),u||a()},move(e,t,n){y.activeBranch&&f(y.activeBranch,e,t,n),y.container=e},next:()=>y.activeBranch&&h(y.activeBranch),registerDep(e,t){const n=!!y.pendingBranch;n&&y.deps++;const o=e.vnode.el;e.asyncDep.catch((t=>{Ar(t,e,0)})).then((r=>{if(e.isUnmounted||y.isUnmounted||y.pendingId!==e.suspenseId)return;e.asyncResolved=!0;const{vnode:s}=e;yr(e,r),o&&(s.el=o);const l=!o&&e.subTree.el;t(e,s,m(o||e.subTree.el),o?null:h(e.subTree),y,i,c),l&&g(l),qt(e,s.el),n&&0==--y.deps&&y.resolve()}))},unmount(e,t){y.isUnmounted=!0,y.activeBranch&&d(y.activeBranch,n,e,t),y.pendingBranch&&d(y.pendingBranch,n,e,t)}};return y}function Xt(e){let t;if(F(e)){const n=e._c;n&&(e._d=!1,Vo()),e=e(),n&&(e._d=!0,t=Io,Bo())}if(N(e)){const t=Wt(e);e=t}return e=Yo(e),t&&!e.dynamicChildren&&(e.dynamicChildren=t.filter((t=>t!==e))),e}function Yt(e,t){t&&t.pendingBranch?N(e)?t.effects.push(...e):t.effects.push(e):Zr(e)}function en(e,t){e.activeBranch=t;const{vnode:n,parentComponent:o}=e,r=n.el=t.el;o&&o.subTree===n&&(o.vnode.el=r,qt(o,r))}function tn(e,t){if(ur){let n=ur.provides;const o=ur.parent&&ur.parent.provides;o===n&&(n=ur.provides=Object.create(o)),n[e]=t}else;}function nn(e,t,n=!1){const o=ur||Lt;if(o){const r=null==o.parent?o.vnode.appContext&&o.vnode.appContext.provides:o.parent.provides;if(r&&e in r)return r[e];if(arguments.length>1)return n&&F(t)?t.call(o.proxy):t}}function on(){const e={isMounted:!1,isLeaving:!1,isUnmounting:!1,leavingVNodes:new Map};return En((()=>{e.isMounted=!0})),Fn((()=>{e.isUnmounting=!0})),e}const rn=[Function,Array],sn={name:"BaseTransition",props:{mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:rn,onEnter:rn,onAfterEnter:rn,onEnterCancelled:rn,onBeforeLeave:rn,onLeave:rn,onAfterLeave:rn,onLeaveCancelled:rn,onBeforeAppear:rn,onAppear:rn,onAfterAppear:rn,onAppearCancelled:rn},setup(e,{slots:t}){const n=pr(),o=on();let r;return()=>{const s=t.default&&fn(t.default(),!0);if(!s||!s.length)return;const i=bt(e),{mode:l}=i,c=s[0];if(o.isLeaving)return an(c);const a=un(c);if(!a)return an(c);const u=cn(a,i,o,n);pn(a,u);const p=n.subTree,f=p&&un(p);let d=!1;const{getTransitionKey:h}=a.type;if(h){const e=h();void 0===r?r=e:e!==r&&(r=e,d=!0)}if(f&&f.type!==Mo&&(!Wo(a,f)||d)){const e=cn(f,i,o,n);if(pn(f,e),"out-in"===l)return o.isLeaving=!0,e.afterLeave=()=>{o.isLeaving=!1,n.update()},an(c);"in-out"===l&&a.type!==Mo&&(e.delayLeave=(e,t,n)=>{ln(o,f)[String(f.key)]=f,e._leaveCb=()=>{t(),e._leaveCb=void 0,delete u.delayedLeave},u.delayedLeave=n})}return c}}};function ln(e,t){const{leavingVNodes:n}=e;let o=n.get(t.type);return o||(o=Object.create(null),n.set(t.type,o)),o}function cn(e,t,n,o){const{appear:r,mode:s,persisted:i=!1,onBeforeEnter:l,onEnter:c,onAfterEnter:a,onEnterCancelled:u,onBeforeLeave:p,onLeave:f,onAfterLeave:d,onLeaveCancelled:h,onBeforeAppear:m,onAppear:g,onAfterAppear:v,onAppearCancelled:y}=t,b=String(e.key),_=ln(n,e),S=(e,t)=>{e&&Fr(e,o,9,t)},x={mode:s,persisted:i,beforeEnter(t){let o=l;if(!n.isMounted){if(!r)return;o=m||l}t._leaveCb&&t._leaveCb(!0);const s=_[b];s&&Wo(e,s)&&s.el._leaveCb&&s.el._leaveCb(),S(o,[t])},enter(e){let t=c,o=a,s=u;if(!n.isMounted){if(!r)return;t=g||c,o=v||a,s=y||u}let i=!1;const l=e._enterCb=t=>{i||(i=!0,S(t?s:o,[e]),x.delayedLeave&&x.delayedLeave(),e._enterCb=void 0)};t?(t(e,l),t.length<=1&&l()):l()},leave(t,o){const r=String(e.key);if(t._enterCb&&t._enterCb(!0),n.isUnmounting)return o();S(p,[t]);let s=!1;const i=t._leaveCb=n=>{s||(s=!0,o(),S(n?h:d,[t]),t._leaveCb=void 0,_[r]===e&&delete _[r])};_[r]=e,f?(f(t,i),f.length<=1&&i()):i()},clone:e=>cn(e,t,n,o)};return x}function an(e){if(gn(e))return(e=Qo(e)).children=null,e}function un(e){return gn(e)?e.children?e.children[0]:void 0:e}function pn(e,t){6&e.shapeFlag&&e.component?pn(e.component.subTree,t):128&e.shapeFlag?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function fn(e,t=!1){let n=[],o=0;for(let r=0;r1)for(let r=0;r!!e.type.__asyncLoader;function mn(e,{vnode:{ref:t,props:n,children:o}}){const r=Jo(e,n,o);return r.ref=t,r}const gn=e=>e.type.__isKeepAlive,vn={name:"KeepAlive",__isKeepAlive:!0,props:{include:[String,RegExp,Array],exclude:[String,RegExp,Array],max:[String,Number]},setup(e,{slots:t}){const n=pr(),o=n.ctx;if(!o.renderer)return t.default;const r=new Map,s=new Set;let i=null;const l=n.suspense,{renderer:{p:c,m:a,um:u,o:{createElement:p}}}=o,f=p("div");function d(e){Cn(e),u(e,n,l)}function h(e){r.forEach(((t,n)=>{const o=wr(t.type);!o||e&&e(o)||m(n)}))}function m(e){const t=r.get(e);i&&t.type===i.type?i&&Cn(i):d(t),r.delete(e),s.delete(e)}o.activate=(e,t,n,o,r)=>{const s=e.component;a(e,t,n,0,l),c(s.vnode,e,t,n,s,l,o,e.slotScopeIds,r),mo((()=>{s.isDeactivated=!1,s.a&&J(s.a);const t=e.props&&e.props.onVnodeMounted;t&&_o(t,s.parent,e)}),l)},o.deactivate=e=>{const t=e.component;a(e,f,null,1,l),mo((()=>{t.da&&J(t.da);const n=e.props&&e.props.onVnodeUnmounted;n&&_o(n,t.parent,e),t.isDeactivated=!0}),l)},os((()=>[e.include,e.exclude]),(([e,t])=>{e&&h((t=>yn(e,t))),t&&h((e=>!yn(t,e)))}),{flush:"post",deep:!0});let g=null;const v=()=>{null!=g&&r.set(g,wn(n.subTree))};return En(v),Rn(v),Fn((()=>{r.forEach((e=>{const{subTree:t,suspense:o}=n,r=wn(t);if(e.type!==r.type)d(e);else{Cn(r);const e=r.component.da;e&&mo(e,o)}}))})),()=>{if(g=null,!t.default)return null;const n=t.default(),o=n[0];if(n.length>1)return i=null,n;if(!(Do(o)&&(4&o.shapeFlag||128&o.shapeFlag)))return i=null,o;let l=wn(o);const c=l.type,a=wr(hn(l)?l.type.__asyncResolved||{}:c),{include:u,exclude:p,max:f}=e;if(u&&(!a||!yn(u,a))||p&&a&&yn(p,a))return i=l,o;const d=null==l.key?c:l.key,h=r.get(d);return l.el&&(l=Qo(l),128&o.shapeFlag&&(o.ssContent=l)),g=d,h?(l.el=h.el,l.component=h.component,l.transition&&pn(l,l.transition),l.shapeFlag|=512,s.delete(d),s.add(d)):(s.add(d),f&&s.size>parseInt(f,10)&&m(s.values().next().value)),l.shapeFlag|=256,i=l,o}}};function yn(e,t){return N(e)?e.some((e=>yn(e,t))):A(e)?e.split(",").indexOf(t)>-1:!!e.test&&e.test(t)}function bn(e,t){Sn(e,"a",t)}function _n(e,t){Sn(e,"da",t)}function Sn(e,t,n=ur){const o=e.__wdc||(e.__wdc=()=>{let t=n;for(;t;){if(t.isDeactivated)return;t=t.parent}e()});if(kn(t,o,n),n){let e=n.parent;for(;e&&e.parent;)gn(e.parent.vnode)&&xn(o,t,n,e),e=e.parent}}function xn(e,t,n,o){const r=kn(t,e,o,!0);An((()=>{w(o[t],r)}),n)}function Cn(e){let t=e.shapeFlag;256&t&&(t-=256),512&t&&(t-=512),e.shapeFlag=t}function wn(e){return 128&e.shapeFlag?e.ssContent:e}function kn(e,t,n=ur,o=!1){if(n){const r=n[e]||(n[e]=[]),s=t.__weh||(t.__weh=(...o)=>{if(n.isUnmounted)return;ge(),fr(n);const r=Fr(t,n,e,o);return dr(),ve(),r});return o?r.unshift(s):r.push(s),s}}const Tn=e=>(t,n=ur)=>(!vr||"sp"===e)&&kn(e,t,n),Nn=Tn("bm"),En=Tn("m"),$n=Tn("bu"),Rn=Tn("u"),Fn=Tn("bum"),An=Tn("um"),Mn=Tn("sp"),On=Tn("rtg"),Pn=Tn("rtc");function In(e,t=ur){kn("ec",e,t)}let Vn=!0;function Bn(e){const t=Un(e),n=e.proxy,o=e.ctx;Vn=!1,t.beforeCreate&&Ln(t.beforeCreate,e,"bc");const{data:r,computed:s,methods:i,watch:l,provide:c,inject:a,created:u,beforeMount:p,mounted:f,beforeUpdate:d,updated:h,activated:m,deactivated:g,beforeUnmount:v,unmounted:b,render:_,renderTracked:S,renderTriggered:x,errorCaptured:C,serverPrefetch:w,expose:k,inheritAttrs:T,components:E,directives:$}=t;if(a&&function(e,t,n=y,o=!1){N(e)&&(e=zn(e));for(const r in e){const n=e[r];let s;s=O(n)?"default"in n?nn(n.from||r,n.default,!0):nn(n.from||r):nn(n),wt(s)&&o?Object.defineProperty(t,r,{enumerable:!0,configurable:!0,get:()=>s.value,set:e=>s.value=e}):t[r]=s}}(a,o,null,e.appContext.config.unwrapInjectedRef),i)for(const y in i){const e=i[y];F(e)&&(o[y]=e.bind(n))}if(r){const t=r.call(n,n);O(t)&&(e.data=ft(t))}if(Vn=!0,s)for(const N in s){const e=s[N],t=Pt({get:F(e)?e.bind(n,n):F(e.get)?e.get.bind(n,n):y,set:!F(e)&&F(e.set)?e.set.bind(n):y});Object.defineProperty(o,N,{enumerable:!0,configurable:!0,get:()=>t.value,set:e=>t.value=e})}if(l)for(const y in l)jn(l[y],o,n,y);if(c){const e=F(c)?c.call(n):c;Reflect.ownKeys(e).forEach((t=>{tn(t,e[t])}))}function R(e,t){N(t)?t.forEach((t=>e(t.bind(n)))):t&&e(t.bind(n))}if(u&&Ln(u,e,"c"),R(Nn,p),R(En,f),R($n,d),R(Rn,h),R(bn,m),R(_n,g),R(In,C),R(Pn,S),R(On,x),R(Fn,v),R(An,b),R(Mn,w),N(k))if(k.length){const t=e.exposed||(e.exposed={});k.forEach((e=>{Object.defineProperty(t,e,{get:()=>n[e],set:t=>n[e]=t})}))}else e.exposed||(e.exposed={});_&&e.render===y&&(e.render=_),null!=T&&(e.inheritAttrs=T),E&&(e.components=E),$&&(e.directives=$)}function Ln(e,t,n){Fr(N(e)?e.map((e=>e.bind(t.proxy))):e.bind(t.proxy),t,n)}function jn(e,t,n,o){const r=o.includes(".")?is(n,o):()=>n[o];if(A(e)){const n=t[e];F(n)&&os(r,n)}else if(F(e))os(r,e.bind(n));else if(O(e))if(N(e))e.forEach((e=>jn(e,t,n,o)));else{const o=F(e.handler)?e.handler.bind(n):t[e.handler];F(o)&&os(r,o,e)}}function Un(e){const t=e.type,{mixins:n,extends:o}=t,{mixins:r,optionsCache:s,config:{optionMergeStrategies:i}}=e.appContext,l=s.get(t);let c;return l?c=l:r.length||n||o?(c={},r.length&&r.forEach((e=>Hn(c,e,i,!0))),Hn(c,t,i)):c=t,s.set(t,c),c}function Hn(e,t,n,o=!1){const{mixins:r,extends:s}=t;s&&Hn(e,s,n,!0),r&&r.forEach((t=>Hn(e,t,n,!0)));for(const i in t)if(o&&"expose"===i);else{const o=Dn[i]||n&&n[i];e[i]=o?o(e[i],t[i]):t[i]}return e}const Dn={data:Wn,props:Gn,emits:Gn,methods:Gn,computed:Gn,beforeCreate:Kn,created:Kn,beforeMount:Kn,mounted:Kn,beforeUpdate:Kn,updated:Kn,beforeDestroy:Kn,destroyed:Kn,activated:Kn,deactivated:Kn,errorCaptured:Kn,serverPrefetch:Kn,components:Gn,directives:Gn,watch:function(e,t){if(!e)return t;if(!t)return e;const n=C(Object.create(null),e);for(const o in t)n[o]=Kn(e[o],t[o]);return n},provide:Wn,inject:function(e,t){return Gn(zn(e),zn(t))}};function Wn(e,t){return t?e?function(){return C(F(e)?e.call(this,this):e,F(t)?t.call(this,this):t)}:t:e}function zn(e){if(N(e)){const t={};for(let n=0;n{c=!0;const[n,o]=Zn(e,t,!0);C(i,n),o&&l.push(...o)};!n&&t.mixins.length&&t.mixins.forEach(o),e.extends&&o(e.extends),e.mixins&&e.mixins.forEach(o)}if(!s&&!c)return o.set(e,v),v;if(N(s))for(let u=0;u-1,n[1]=o<0||t-1||T(n,"default"))&&l.push(e)}}}const a=[i,l];return o.set(e,a),a}function Qn(e){return"$"!==e[0]}function Xn(e){const t=e&&e.toString().match(/^\s*function (\w+)/);return t?t[1]:null===e?"null":""}function Yn(e,t){return Xn(e)===Xn(t)}function eo(e,t){return N(t)?t.findIndex((t=>Yn(t,e))):F(t)&&Yn(t,e)?0:-1}const to=e=>"_"===e[0]||"$stable"===e,no=e=>N(e)?e.map(Yo):[Yo(e)],oo=(e,t,n)=>{const o=Ht(((...e)=>no(t(...e))),n);return o._c=!1,o},ro=(e,t,n)=>{const o=e._ctx;for(const r in e){if(to(r))continue;const n=e[r];if(F(n))t[r]=oo(0,n,o);else if(null!=n){const e=no(n);t[r]=()=>e}}},so=(e,t)=>{const n=no(t);e.slots.default=()=>n};function io(e,t,n,o){const r=e.dirs,s=t&&t.dirs;for(let i=0;i(s.has(e)||(e&&F(e.install)?(s.add(e),e.install(l,...t)):F(e)&&(s.add(e),e(l,...t))),l),mixin:e=>(r.mixins.includes(e)||r.mixins.push(e),l),component:(e,t)=>t?(r.components[e]=t,l):r.components[e],directive:(e,t)=>t?(r.directives[e]=t,l):r.directives[e],mount(s,c,a){if(!i){const u=Jo(n,o);return u.appContext=r,c&&t?t(u,s):e(u,s,a),i=!0,l._container=s,s.__vue_app__=l,u.component.proxy}},unmount(){i&&(e(null,l._container),delete l._container.__vue_app__)},provide:(e,t)=>(r.provides[e]=t,l)};return l}}let uo=!1;const po=e=>/svg/.test(e.namespaceURI)&&"foreignObject"!==e.tagName,fo=e=>8===e.nodeType;function ho(e){const{mt:t,p:n,o:{patchProp:o,nextSibling:r,parentNode:s,remove:i,insert:l,createComment:c}}=e,a=(n,o,i,l,c,m=!1)=>{const g=fo(n)&&"["===n.data,v=()=>d(n,o,i,l,c,g),{type:y,ref:b,shapeFlag:_}=o,S=n.nodeType;o.el=n;let x=null;switch(y){case Ao:3!==S?x=v():(n.data!==o.children&&(uo=!0,n.data=o.children),x=r(n));break;case Mo:x=8!==S||g?v():r(n);break;case Oo:if(1===S){x=n;const e=!o.children.length;for(let t=0;t{l=l||!!t.dynamicChildren;const{type:c,props:a,patchFlag:u,shapeFlag:f,dirs:d}=t,h="input"===c&&d||"option"===c;if(h||-1!==u){if(d&&io(t,null,n,"created"),a)if(h||!l||48&u)for(const t in a)(h&&t.endsWith("value")||S(t)&&!j(t))&&o(e,t,null,a[t]);else a.onClick&&o(e,"onClick",null,a.onClick);let c;if((c=a&&a.onVnodeBeforeMount)&&_o(c,n,t),d&&io(t,null,n,"beforeMount"),((c=a&&a.onVnodeMounted)||d)&&Yt((()=>{c&&_o(c,n,t),d&&io(t,null,n,"mounted")}),r),16&f&&(!a||!a.innerHTML&&!a.textContent)){let o=p(e.firstChild,t,e,n,r,s,l);for(;o;){uo=!0;const e=o;o=o.nextSibling,i(e)}}else 8&f&&e.textContent!==t.children&&(uo=!0,e.textContent=t.children)}return e.nextSibling},p=(e,t,o,r,s,i,l)=>{l=l||!!t.dynamicChildren;const c=t.children,u=c.length;for(let p=0;p{const{slotScopeIds:u}=t;u&&(i=i?i.concat(u):u);const f=s(e),d=p(r(e),t,f,n,o,i,a);return d&&fo(d)&&"]"===d.data?r(t.anchor=d):(uo=!0,l(t.anchor=c("]"),f,d),d)},d=(e,t,o,l,c,a)=>{if(uo=!0,t.el=null,a){const t=h(e);for(;;){const n=r(e);if(!n||n===t)break;i(n)}}const u=r(e),p=s(e);return i(e),n(null,t,p,u,o,l,po(p),c),u},h=e=>{let t=0;for(;e;)if((e=r(e))&&fo(e)&&("["===e.data&&t++,"]"===e.data)){if(0===t)return r(e);t--}return e};return[(e,t)=>{if(!t.hasChildNodes())return n(null,e,t),void Xr();uo=!1,a(t.firstChild,e,null,null,null),Xr(),uo&&console.error("Hydration completed but contains mismatches.")},a]}const mo=Yt;function go(e){return yo(e)}function vo(e){return yo(e,ho)}function yo(e,t){const{insert:n,remove:o,patchProp:r,createElement:s,createText:i,createComment:l,setText:c,setElementText:a,parentNode:u,nextSibling:p,setScopeId:f=y,cloneNode:d,insertStaticContent:h}=e,m=(e,t,n,o=null,r=null,s=null,i=!1,l=null,c=!!t.dynamicChildren)=>{if(e===t)return;e&&!Wo(e,t)&&(o=X(e),W(e,r,s,!0),e=null),-2===t.patchFlag&&(c=!1,t.dynamicChildren=null);const{type:a,ref:u,shapeFlag:p}=t;switch(a){case Ao:b(e,t,n,o);break;case Mo:_(e,t,n,o);break;case Oo:null==e&&S(t,n,o,i);break;case Fo:F(e,t,n,o,r,s,i,l,c);break;default:1&p?x(e,t,n,o,r,s,i,l,c):6&p?A(e,t,n,o,r,s,i,l,c):(64&p||128&p)&&a.process(e,t,n,o,r,s,i,l,c,te)}null!=u&&r&&bo(u,e&&e.ref,s,t||e,!t)},b=(e,t,o,r)=>{if(null==e)n(t.el=i(t.children),o,r);else{const n=t.el=e.el;t.children!==e.children&&c(n,t.children)}},_=(e,t,o,r)=>{null==e?n(t.el=l(t.children||""),o,r):t.el=e.el},S=(e,t,n,o)=>{[e.el,e.anchor]=h(e.children,t,n,o)},x=(e,t,n,o,r,s,i,l,c)=>{i=i||"svg"===t.type,null==e?w(t,n,o,r,s,i,l,c):E(e,t,r,s,i,l,c)},w=(e,t,o,i,l,c,u,p)=>{let f,h;const{type:m,props:g,shapeFlag:v,transition:y,patchFlag:b,dirs:_}=e;if(e.el&&void 0!==d&&-1===b)f=e.el=d(e.el);else{if(f=e.el=s(e.type,c,g&&g.is,g),8&v?a(f,e.children):16&v&&N(e.children,f,null,i,l,c&&"foreignObject"!==m,u,p),_&&io(e,null,i,"created"),g){for(const t in g)"value"===t||j(t)||r(f,t,null,g[t],c,e.children,i,l,Q);"value"in g&&r(f,"value",null,g.value),(h=g.onVnodeBeforeMount)&&_o(h,i,e)}k(f,e,e.scopeId,u,i)}_&&io(e,null,i,"beforeMount");const S=(!l||l&&!l.pendingBranch)&&y&&!y.persisted;S&&y.beforeEnter(f),n(f,t,o),((h=g&&g.onVnodeMounted)||S||_)&&mo((()=>{h&&_o(h,i,e),S&&y.enter(f),_&&io(e,null,i,"mounted")}),l)},k=(e,t,n,o,r)=>{if(n&&f(e,n),o)for(let s=0;s{for(let a=c;a{const c=t.el=e.el;let{patchFlag:u,dynamicChildren:p,dirs:f}=t;u|=16&e.patchFlag;const d=e.props||g,h=t.props||g;let m;(m=h.onVnodeBeforeUpdate)&&_o(m,n,t,e),f&&io(t,e,n,"beforeUpdate");const v=s&&"foreignObject"!==t.type;if(p?$(e.dynamicChildren,p,c,n,o,v,i):l||B(e,t,c,null,n,o,v,i,!1),u>0){if(16&u)R(c,t,d,h,n,o,s);else if(2&u&&d.class!==h.class&&r(c,"class",null,h.class,s),4&u&&r(c,"style",d.style,h.style,s),8&u){const i=t.dynamicProps;for(let t=0;t{m&&_o(m,n,t,e),f&&io(t,e,n,"updated")}),o)},$=(e,t,n,o,r,s,i)=>{for(let l=0;l{if(n!==o){for(const c in o){if(j(c))continue;const a=o[c],u=n[c];a!==u&&"value"!==c&&r(e,c,u,a,l,t.children,s,i,Q)}if(n!==g)for(const c in n)j(c)||c in o||r(e,c,n[c],null,l,t.children,s,i,Q);"value"in o&&r(e,"value",n.value,o.value)}},F=(e,t,o,r,s,l,c,a,u)=>{const p=t.el=e?e.el:i(""),f=t.anchor=e?e.anchor:i("");let{patchFlag:d,dynamicChildren:h,slotScopeIds:m}=t;m&&(a=a?a.concat(m):m),null==e?(n(p,o,r),n(f,o,r),N(t.children,o,f,s,l,c,a,u)):d>0&&64&d&&h&&e.dynamicChildren?($(e.dynamicChildren,h,o,s,l,c,a),(null!=t.key||s&&t===s.subTree)&&So(e,t,!0)):B(e,t,o,f,s,l,c,a,u)},A=(e,t,n,o,r,s,i,l,c)=>{t.slotScopeIds=l,null==e?512&t.shapeFlag?r.ctx.activate(t,n,o,i,c):M(t,n,o,r,s,i,c):O(e,t,c)},M=(e,t,n,o,r,s,i)=>{const l=e.component=function(e,t,n){const o=e.type,r=(t?t.appContext:e.appContext)||cr,s={uid:ar++,vnode:e,type:o,parent:t,appContext:r,root:null,next:null,subTree:null,update:null,scope:new ee(!0),render:null,proxy:null,exposed:null,exposeProxy:null,withProxy:null,provides:t?t.provides:Object.create(r.provides),accessCache:null,renderCache:[],components:null,directives:null,propsOptions:Zn(o,r),emitsOptions:Vt(o,r),emit:null,emitted:null,propsDefaults:g,inheritAttrs:o.inheritAttrs,ctx:g,data:g,props:g,attrs:g,slots:g,refs:g,setupState:g,setupContext:null,suspense:n,suspenseId:n?n.pendingId:0,asyncDep:null,asyncResolved:!1,isMounted:!1,isUnmounted:!1,isDeactivated:!1,bc:null,c:null,bm:null,m:null,bu:null,u:null,um:null,bum:null,da:null,a:null,rtg:null,rtc:null,ec:null,sp:null};s.ctx={_:s},s.root=t?t.root:s,s.emit=It.bind(null,s),e.ce&&e.ce(s);return s}(e,o,r);if(gn(e)&&(l.ctx.renderer=te),function(e,t=!1){vr=t;const{props:n,children:o}=e.vnode,r=hr(e);(function(e,t,n,o=!1){const r={},s={};Z(s,zo,1),e.propsDefaults=Object.create(null),qn(e,t,r,s);for(const i in e.propsOptions[0])i in r||(r[i]=void 0);e.props=n?o?r:dt(r):e.type.props?r:s,e.attrs=s})(e,n,r,t),((e,t)=>{if(32&e.vnode.shapeFlag){const n=t._;n?(e.slots=bt(t),Z(t,"_",n)):ro(t,e.slots={})}else e.slots={},t&&so(e,t);Z(e.slots,zo,1)})(e,o);const s=r?function(e,t){const n=e.type;e.accessCache=Object.create(null),e.proxy=_t(new Proxy(e.ctx,ir));const{setup:o}=n;if(o){const n=e.setupContext=o.length>1?Sr(e):null;fr(e),ge();const r=Rr(o,e,0,[e.props,n]);if(ve(),dr(),P(r)){if(r.then(dr,dr),t)return r.then((t=>{yr(e,t)})).catch((t=>{Ar(t,e,0)}));e.asyncDep=r}else yr(e,r)}else _r(e)}(e,t):void 0;vr=!1}(l),l.asyncDep){if(r&&r.registerDep(l,I),!e.el){const e=l.subTree=Jo(Mo);_(null,e,t,n)}}else I(l,e,t,n,r,s,i)},O=(e,t,n)=>{const o=t.component=e.component;if(function(e,t,n){const{props:o,children:r,component:s}=e,{props:i,children:l,patchFlag:c}=t,a=s.emitsOptions;if(t.dirs||t.transition)return!0;if(!(n&&c>=0))return!(!r&&!l||l&&l.$stable)||o!==i&&(o?!i||Gt(o,i,a):!!i);if(1024&c)return!0;if(16&c)return o?Gt(o,i,a):!!i;if(8&c){const e=t.dynamicProps;for(let t=0;tIr&&Pr.splice(t,1)}(o.update),o.update()}else t.component=e.component,t.el=e.el,o.vnode=t},I=(e,t,n,o,r,s,i)=>{const l=new fe((()=>{if(e.isMounted){let t,{next:n,bu:o,u:c,parent:a,vnode:p}=e,f=n;l.allowRecurse=!1,n?(n.el=p.el,V(e,n,i)):n=p,o&&J(o),(t=n.props&&n.props.onVnodeBeforeUpdate)&&_o(t,a,n,p),l.allowRecurse=!0;const d=Dt(e),h=e.subTree;e.subTree=d,m(h,d,u(h.el),X(h),e,r,s),n.el=d.el,null===f&&qt(e,d.el),c&&mo(c,r),(t=n.props&&n.props.onVnodeUpdated)&&mo((()=>_o(t,a,n,p)),r)}else{let i;const{el:c,props:a}=t,{bm:u,m:p,parent:f}=e,d=hn(t);if(l.allowRecurse=!1,u&&J(u),!d&&(i=a&&a.onVnodeBeforeMount)&&_o(i,f,t),l.allowRecurse=!0,c&&oe){const n=()=>{e.subTree=Dt(e),oe(c,e.subTree,e,r,null)};d?t.type.__asyncLoader().then((()=>!e.isUnmounted&&n())):n()}else{const i=e.subTree=Dt(e);m(null,i,n,o,e,r,s),t.el=i.el}if(p&&mo(p,r),!d&&(i=a&&a.onVnodeMounted)){const e=t;mo((()=>_o(i,f,e)),r)}256&t.shapeFlag&&e.a&&mo(e.a,r),e.isMounted=!0,t=n=o=null}}),(()=>Gr(e.update)),e.scope),c=e.update=l.run.bind(l);c.id=e.uid,l.allowRecurse=c.allowRecurse=!0,c()},V=(e,t,n)=>{t.component=e;const o=e.vnode.props;e.vnode=t,e.next=null,function(e,t,n,o){const{props:r,attrs:s,vnode:{patchFlag:i}}=e,l=bt(r),[c]=e.propsOptions;let a=!1;if(!(o||i>0)||16&i){let o;qn(e,t,r,s)&&(a=!0);for(const s in l)t&&(T(t,s)||(o=z(s))!==s&&T(t,o))||(c?!n||void 0===n[s]&&void 0===n[o]||(r[s]=Jn(c,l,s,void 0,e,!0)):delete r[s]);if(s!==l)for(const e in s)t&&T(t,e)||(delete s[e],a=!0)}else if(8&i){const n=e.vnode.dynamicProps;for(let o=0;o{const{vnode:o,slots:r}=e;let s=!0,i=g;if(32&o.shapeFlag){const e=t._;e?n&&1===e?s=!1:(C(r,t),n||1!==e||delete r._):(s=!t.$stable,ro(t,r)),i=t}else t&&(so(e,t),i={default:1});if(s)for(const l in r)to(l)||l in i||delete r[l]})(e,t.children,n),ge(),Qr(void 0,e.update),ve()},B=(e,t,n,o,r,s,i,l,c=!1)=>{const u=e&&e.children,p=e?e.shapeFlag:0,f=t.children,{patchFlag:d,shapeFlag:h}=t;if(d>0){if(128&d)return void U(u,f,n,o,r,s,i,l,c);if(256&d)return void L(u,f,n,o,r,s,i,l,c)}8&h?(16&p&&Q(u,r,s),f!==u&&a(n,f)):16&p?16&h?U(u,f,n,o,r,s,i,l,c):Q(u,r,s,!0):(8&p&&a(n,""),16&h&&N(f,n,o,r,s,i,l,c))},L=(e,t,n,o,r,s,i,l,c)=>{const a=(e=e||v).length,u=(t=t||v).length,p=Math.min(a,u);let f;for(f=0;fu?Q(e,r,s,!0,!1,p):N(t,n,o,r,s,i,l,c,p)},U=(e,t,n,o,r,s,i,l,c)=>{let a=0;const u=t.length;let p=e.length-1,f=u-1;for(;a<=p&&a<=f;){const o=e[a],u=t[a]=c?er(t[a]):Yo(t[a]);if(!Wo(o,u))break;m(o,u,n,null,r,s,i,l,c),a++}for(;a<=p&&a<=f;){const o=e[p],a=t[f]=c?er(t[f]):Yo(t[f]);if(!Wo(o,a))break;m(o,a,n,null,r,s,i,l,c),p--,f--}if(a>p){if(a<=f){const e=f+1,p=ef)for(;a<=p;)W(e[a],r,s,!0),a++;else{const d=a,h=a,g=new Map;for(a=h;a<=f;a++){const e=t[a]=c?er(t[a]):Yo(t[a]);null!=e.key&&g.set(e.key,a)}let y,b=0;const _=f-h+1;let S=!1,x=0;const C=new Array(_);for(a=0;a<_;a++)C[a]=0;for(a=d;a<=p;a++){const o=e[a];if(b>=_){W(o,r,s,!0);continue}let u;if(null!=o.key)u=g.get(o.key);else for(y=h;y<=f;y++)if(0===C[y-h]&&Wo(o,t[y])){u=y;break}void 0===u?W(o,r,s,!0):(C[u-h]=a+1,u>=x?x=u:S=!0,m(o,t[u],n,null,r,s,i,l,c),b++)}const w=S?function(e){const t=e.slice(),n=[0];let o,r,s,i,l;const c=e.length;for(o=0;o>1,e[n[l]]0&&(t[o]=n[s-1]),n[s]=o)}}s=n.length,i=n[s-1];for(;s-- >0;)n[s]=i,i=t[i];return n}(C):v;for(y=w.length-1,a=_-1;a>=0;a--){const e=h+a,p=t[e],f=e+1{const{el:i,type:l,transition:c,children:a,shapeFlag:u}=e;if(6&u)return void H(e.component.subTree,t,o,r);if(128&u)return void e.suspense.move(t,o,r);if(64&u)return void l.move(e,t,o,te);if(l===Fo){n(i,t,o);for(let e=0;e{let s;for(;e&&e!==t;)s=p(e),n(e,o,r),e=s;n(t,o,r)})(e,t,o);if(2!==r&&1&u&&c)if(0===r)c.beforeEnter(i),n(i,t,o),mo((()=>c.enter(i)),s);else{const{leave:e,delayLeave:r,afterLeave:s}=c,l=()=>n(i,t,o),a=()=>{e(i,(()=>{l(),s&&s()}))};r?r(i,l,a):a()}else n(i,t,o)},W=(e,t,n,o=!1,r=!1)=>{const{type:s,props:i,ref:l,children:c,dynamicChildren:a,shapeFlag:u,patchFlag:p,dirs:f}=e;if(null!=l&&bo(l,null,n,e,!0),256&u)return void t.ctx.deactivate(e);const d=1&u&&f,h=!hn(e);let m;if(h&&(m=i&&i.onVnodeBeforeUnmount)&&_o(m,t,e),6&u)q(e.component,n,o);else{if(128&u)return void e.suspense.unmount(n,o);d&&io(e,null,t,"beforeUnmount"),64&u?e.type.remove(e,t,n,r,te,o):a&&(s!==Fo||p>0&&64&p)?Q(a,t,n,!1,!0):(s===Fo&&384&p||!r&&16&u)&&Q(c,t,n),o&&K(e)}(h&&(m=i&&i.onVnodeUnmounted)||d)&&mo((()=>{m&&_o(m,t,e),d&&io(e,null,t,"unmounted")}),n)},K=e=>{const{type:t,el:n,anchor:r,transition:s}=e;if(t===Fo)return void G(n,r);if(t===Oo)return void(({el:e,anchor:t})=>{let n;for(;e&&e!==t;)n=p(e),o(e),e=n;o(t)})(e);const i=()=>{o(n),s&&!s.persisted&&s.afterLeave&&s.afterLeave()};if(1&e.shapeFlag&&s&&!s.persisted){const{leave:t,delayLeave:o}=s,r=()=>t(n,i);o?o(e.el,i,r):r()}else i()},G=(e,t)=>{let n;for(;e!==t;)n=p(e),o(e),e=n;o(t)},q=(e,t,n)=>{const{bum:o,scope:r,update:s,subTree:i,um:l}=e;o&&J(o),r.stop(),s&&(s.active=!1,W(i,e,t,n)),l&&mo(l,t),mo((()=>{e.isUnmounted=!0}),t),t&&t.pendingBranch&&!t.isUnmounted&&e.asyncDep&&!e.asyncResolved&&e.suspenseId===t.pendingId&&(t.deps--,0===t.deps&&t.resolve())},Q=(e,t,n,o=!1,r=!1,s=0)=>{for(let i=s;i6&e.shapeFlag?X(e.component.subTree):128&e.shapeFlag?e.suspense.next():p(e.anchor||e.el),Y=(e,t,n)=>{null==e?t._vnode&&W(t._vnode,null,null,!0):m(t._vnode||null,e,t,null,null,null,n),Xr(),t._vnode=e},te={p:m,um:W,m:H,r:K,mt:M,mc:N,pc:B,pbc:$,n:X,o:e};let ne,oe;return t&&([ne,oe]=t(te)),{render:Y,hydrate:ne,createApp:ao(Y,ne)}}function bo(e,t,n,o,r=!1){if(N(e))return void e.forEach(((e,s)=>bo(e,t&&(N(t)?t[s]:t),n,o,r)));if(hn(o)&&!r)return;const s=4&o.shapeFlag?xr(o.component)||o.component.proxy:o.el,i=r?null:s,{i:l,r:c}=e,a=t&&t.r,u=l.refs===g?l.refs={}:l.refs,p=l.setupState;if(null!=a&&a!==c&&(A(a)?(u[a]=null,T(p,a)&&(p[a]=null)):wt(a)&&(a.value=null)),A(c)){const e=()=>{u[c]=i,T(p,c)&&(p[c]=i)};i?(e.id=-1,mo(e,n)):e()}else if(wt(c)){const e=()=>{c.value=i};i?(e.id=-1,mo(e,n)):e()}else F(c)&&Rr(c,l,12,[i,u])}function _o(e,t,n,o=null){Fr(e,t,7,[n,o])}function So(e,t,n=!1){const o=e.children,r=t.children;if(N(o)&&N(r))for(let s=0;se&&(e.disabled||""===e.disabled),Co=e=>"undefined"!=typeof SVGElement&&e instanceof SVGElement,wo=(e,t)=>{const n=e&&e.to;if(A(n)){if(t){return t(n)}return null}return n};function ko(e,t,n,{o:{insert:o},m:r},s=2){0===s&&o(e.targetAnchor,t,n);const{el:i,anchor:l,shapeFlag:c,children:a,props:u}=e,p=2===s;if(p&&o(i,t,n),(!p||xo(u))&&16&c)for(let f=0;f{16&v&&u(y,e,t,r,s,i,l,c)};g?b(n,a):p&&b(p,f)}else{t.el=e.el;const o=t.anchor=e.anchor,u=t.target=e.target,d=t.targetAnchor=e.targetAnchor,m=xo(e.props),v=m?n:u,y=m?o:d;if(i=i||Co(u),b?(f(e.dynamicChildren,b,v,r,s,i,l),So(e,t,!0)):c||p(e,t,v,y,r,s,i,l,!1),g)m||ko(t,n,o,a,1);else if((t.props&&t.props.to)!==(e.props&&e.props.to)){const e=t.target=wo(t.props,h);e&&ko(t,e,null,a,0)}else m&&ko(t,u,d,a,1)}},remove(e,t,n,o,{um:r,o:{remove:s}},i){const{shapeFlag:l,children:c,anchor:a,targetAnchor:u,target:p,props:f}=e;if(p&&s(u),(i||!xo(f))&&(s(a),16&l))for(let d=0;d0?Io||v:null,Bo(),Lo>0&&Io&&Io.push(e),e}function Ho(e,t,n,o,r){return Uo(Jo(e,t,n,o,r,!0))}function Do(e){return!!e&&!0===e.__v_isVNode}function Wo(e,t){return e.type===t.type&&e.key===t.key}const zo="__vInternal",Ko=({key:e})=>null!=e?e:null,Go=({ref:e})=>null!=e?A(e)||wt(e)||F(e)?{i:Lt,r:e}:e:null;function qo(e,t=null,n=null,o=0,r=null,s=(e===Fo?0:1),i=!1,l=!1){const c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Ko(t),ref:t&&Go(t),scopeId:jt,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetAnchor:null,staticCount:0,shapeFlag:s,patchFlag:o,dynamicProps:r,dynamicChildren:null,appContext:null};return l?(tr(c,n),128&s&&e.normalize(c)):n&&(c.shapeFlag|=A(n)?8:16),Lo>0&&!i&&Io&&(c.patchFlag>0||6&s)&&32!==c.patchFlag&&Io.push(c),c}const Jo=function(e,t=null,n=null,o=0,r=null,i=!1){e&&e!==Eo||(e=Mo);if(Do(e)){const o=Qo(e,t,!0);return n&&tr(o,n),o}l=e,F(l)&&"__vccOpts"in l&&(e=e.__vccOpts);var l;if(t){t=Zo(t);let{class:e,style:n}=t;e&&!A(e)&&(t.class=a(e)),O(n)&&(yt(n)&&!N(n)&&(n=C({},n)),t.style=s(n))}const c=A(e)?1:(e=>e.__isSuspense)(e)?128:(e=>e.__isTeleport)(e)?64:O(e)?4:F(e)?2:0;return qo(e,t,n,o,r,c,i,!0)};function Zo(e){return e?yt(e)||zo in e?C({},e):e:null}function Qo(e,t,n=!1){const{props:o,ref:r,patchFlag:s,children:i}=e,l=t?nr(o||{},t):o;return{__v_isVNode:!0,__v_skip:!0,type:e.type,props:l,key:l&&Ko(l),ref:t&&t.ref?n&&r?N(r)?r.concat(Go(t)):[r,Go(t)]:Go(t):r,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:i,target:e.target,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==Fo?-1===s?16:16|s:s,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:e.transition,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Qo(e.ssContent),ssFallback:e.ssFallback&&Qo(e.ssFallback),el:e.el,anchor:e.anchor}}function Xo(e=" ",t=0){return Jo(Ao,null,e,t)}function Yo(e){return null==e||"boolean"==typeof e?Jo(Mo):N(e)?Jo(Fo,null,e.slice()):"object"==typeof e?er(e):Jo(Ao,null,String(e))}function er(e){return null===e.el||e.memo?e:Qo(e)}function tr(e,t){let n=0;const{shapeFlag:o}=e;if(null==t)t=null;else if(N(t))n=16;else if("object"==typeof t){if(65&o){const n=t.default;return void(n&&(n._c&&(n._d=!1),tr(e,n()),n._c&&(n._d=!0)))}{n=32;const o=t._;o||zo in t?3===o&&Lt&&(1===Lt.slots._?t._=1:(t._=2,e.patchFlag|=1024)):t._ctx=Lt}}else F(t)?(t={default:t,_ctx:Lt},n=32):(t=String(t),64&o?(n=16,t=[Xo(t)]):n=8);e.children=t,e.shapeFlag|=n}function nr(...e){const t={};for(let n=0;n!Do(e)||e.type!==Mo&&!(e.type===Fo&&!or(e.children))))?e:null}const rr=e=>e?hr(e)?xr(e)||e.proxy:rr(e.parent):null,sr=C(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>rr(e.parent),$root:e=>rr(e.root),$emit:e=>e.emit,$options:e=>Un(e),$forceUpdate:e=>()=>Gr(e.update),$nextTick:e=>Kr.bind(e.proxy),$watch:e=>ss.bind(e)}),ir={get({_:e},t){const{ctx:n,setupState:o,data:r,props:s,accessCache:i,type:l,appContext:c}=e;let a;if("$"!==t[0]){const l=i[t];if(void 0!==l)switch(l){case 0:return o[t];case 1:return r[t];case 3:return n[t];case 2:return s[t]}else{if(o!==g&&T(o,t))return i[t]=0,o[t];if(r!==g&&T(r,t))return i[t]=1,r[t];if((a=e.propsOptions[0])&&T(a,t))return i[t]=2,s[t];if(n!==g&&T(n,t))return i[t]=3,n[t];Vn&&(i[t]=4)}}const u=sr[t];let p,f;return u?("$attrs"===t&&ye(e,0,t),u(e)):(p=l.__cssModules)&&(p=p[t])?p:n!==g&&T(n,t)?(i[t]=3,n[t]):(f=c.config.globalProperties,T(f,t)?f[t]:void 0)},set({_:e},t,n){const{data:o,setupState:r,ctx:s}=e;if(r!==g&&T(r,t))r[t]=n;else if(o!==g&&T(o,t))o[t]=n;else if(T(e.props,t))return!1;return("$"!==t[0]||!(t.slice(1)in e))&&(s[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:o,appContext:r,propsOptions:s}},i){let l;return void 0!==n[i]||e!==g&&T(e,i)||t!==g&&T(t,i)||(l=s[0])&&T(l,i)||T(o,i)||T(sr,i)||T(r.config.globalProperties,i)}},lr=C({},ir,{get(e,t){if(t!==Symbol.unscopables)return ir.get(e,t,e)},has:(e,t)=>"_"!==t[0]&&!n(t)}),cr=lo();let ar=0;let ur=null;const pr=()=>ur||Lt,fr=e=>{ur=e,e.scope.on()},dr=()=>{ur&&ur.scope.off(),ur=null};function hr(e){return 4&e.vnode.shapeFlag}let mr,gr,vr=!1;function yr(e,t,n){F(t)?e.render=t:O(t)&&(e.setupState=Rt(t)),_r(e)}function br(e){mr=e,gr=e=>{e.render._rc&&(e.withProxy=new Proxy(e.ctx,lr))}}function _r(e,t,n){const o=e.type;if(!e.render){if(mr&&!o.render){const t=o.template;if(t){const{isCustomElement:n,compilerOptions:r}=e.appContext.config,{delimiters:s,compilerOptions:i}=o,l=C(C({isCustomElement:n,delimiters:s},r),i);o.render=mr(t,l)}}e.render=o.render||y,gr&&gr(e)}fr(e),ge(),Bn(e),ve(),dr()}function Sr(e){const t=t=>{e.exposed=t||{}};let n;return{get attrs(){return n||(n=function(e){return new Proxy(e.attrs,{get:(t,n)=>(ye(e,0,"$attrs"),t[n])})}(e))},slots:e.slots,emit:e.emit,expose:t}}function xr(e){if(e.exposed)return e.exposeProxy||(e.exposeProxy=new Proxy(Rt(_t(e.exposed)),{get:(t,n)=>n in t?t[n]:n in sr?sr[n](e):void 0}))}const Cr=/(?:^|[-_])(\w)/g;function wr(e){return F(e)&&e.displayName||e.name}function kr(e,t,n=!1){let o=wr(t);if(!o&&t.__file){const e=t.__file.match(/([^/\\]+)\.\w+$/);e&&(o=e[1])}if(!o&&e&&e.parent){const n=e=>{for(const n in e)if(e[n]===t)return n};o=n(e.components||e.parent.type.components)||n(e.appContext.components)}return o?o.replace(Cr,(e=>e.toUpperCase())).replace(/[-_]/g,""):n?"App":"Anonymous"}const Tr=[];function Nr(e,...t){ge();const n=Tr.length?Tr[Tr.length-1].component:null,o=n&&n.appContext.config.warnHandler,r=function(){let e=Tr[Tr.length-1];if(!e)return[];const t=[];for(;e;){const n=t[0];n&&n.vnode===e?n.recurseCount++:t.push({vnode:e,recurseCount:0});const o=e.component&&e.component.parent;e=o&&o.vnode}return t}();if(o)Rr(o,n,11,[e+t.join(""),n&&n.proxy,r.map((({vnode:e})=>`at <${kr(n,e.type)}>`)).join("\n"),r]);else{const n=[`[Vue warn]: ${e}`,...t];r.length&&n.push("\n",...function(e){const t=[];return e.forEach(((e,n)=>{t.push(...0===n?[]:["\n"],...function({vnode:e,recurseCount:t}){const n=t>0?`... (${t} recursive calls)`:"",o=` at <${kr(e.component,e.type,!!e.component&&null==e.component.parent)}`,r=">"+n;return e.props?[o,...Er(e.props),r]:[o+r]}(e))})),t}(r)),console.warn(...n)}ve()}function Er(e){const t=[],n=Object.keys(e);return n.slice(0,3).forEach((n=>{t.push(...$r(n,e[n]))})),n.length>3&&t.push(" ..."),t}function $r(e,t,n){return A(t)?(t=JSON.stringify(t),n?t:[`${e}=${t}`]):"number"==typeof t||"boolean"==typeof t||null==t?n?t:[`${e}=${t}`]:wt(t)?(t=$r(e,bt(t.value),!0),n?t:[`${e}=Ref<`,t,">"]):F(t)?[`${e}=fn${t.name?`<${t.name}>`:""}`]:(t=bt(t),n?t:[`${e}=`,t])}function Rr(e,t,n,o){let r;try{r=o?e(...o):e()}catch(s){Ar(s,t,n)}return r}function Fr(e,t,n,o){if(F(e)){const r=Rr(e,t,n,o);return r&&P(r)&&r.catch((e=>{Ar(e,t,n)})),r}const r=[];for(let s=0;s>>1;Yr(Pr[o])Yr(e)-Yr(t))),Hr=0;Hrnull==e.id?1/0:e.id;function es(e){Or=!1,Mr=!0,Qr(e),Pr.sort(((e,t)=>Yr(e)-Yr(t)));try{for(Ir=0;Ire.value,c=!!e._shallow):gt(e)?(i=()=>e,o=!0):N(e)?(a=!0,c=e.some(gt),i=()=>e.map((e=>wt(e)?e.value:gt(e)?ls(e):F(e)?Rr(e,s,2):void 0))):i=F(e)?t?()=>Rr(e,s,2):()=>{if(!s||!s.isUnmounted)return l&&l(),Fr(e,s,3,[u])}:y,t&&o){const e=i;i=()=>ls(e())}let u=e=>{l=h.onStop=()=>{Rr(e,s,4)}},p=a?[]:ns;const f=()=>{if(h.active)if(t){const e=h.run();(o||c||(a?e.some(((e,t)=>q(e,p[t]))):q(e,p)))&&(l&&l(),Fr(t,s,3,[e,p===ns?void 0:p,u]),p=e)}else h.run()};let d;f.allowRecurse=!!t,d="sync"===r?f:"post"===r?()=>mo(f,s&&s.suspense):()=>{!s||s.isMounted?function(e){Jr(e,Br,Vr,Lr)}(f):f()};const h=new fe(i,d);return t?n?f():p=h.run():"post"===r?mo(h.run.bind(h),s&&s.suspense):h.run(),()=>{h.stop(),s&&s.scope&&w(s.scope.effects,h)}}function ss(e,t,n){const o=this.proxy,r=A(e)?e.includes(".")?is(o,e):()=>o[e]:e.bind(o,o);let s;F(t)?s=t:(s=t.handler,n=t);const i=ur;fr(this);const l=rs(r,s.bind(o),n);return i?fr(i):dr(),l}function is(e,t){const n=t.split(".");return()=>{let t=e;for(let e=0;e{ls(e,t)}));else if(B(e))for(const n in e)ls(e[n],t);return e}function cs(){const e=pr();return e.setupContext||(e.setupContext=Sr(e))}function as(e,t,n){const o=arguments.length;return 2===o?O(t)&&!N(t)?Do(t)?Jo(e,null,[t]):Jo(e,t):Jo(e,null,t):(o>3?n=Array.prototype.slice.call(arguments,2):3===o&&Do(n)&&(n=[n]),Jo(e,t,n))}const us=Symbol("");function ps(e,t){const n=e.memo;if(n.length!=t.length)return!1;for(let o=0;o0&&Io&&Io.push(e),!0}const fs="3.2.6",ds="undefined"!=typeof document?document:null,hs=new Map,ms={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,o)=>{const r=t?ds.createElementNS("http://www.w3.org/2000/svg",e):ds.createElement(e,n?{is:n}:void 0);return"select"===e&&o&&null!=o.multiple&&r.setAttribute("multiple",o.multiple),r},createText:e=>ds.createTextNode(e),createComment:e=>ds.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>ds.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},cloneNode(e){const t=e.cloneNode(!0);return"_value"in e&&(t._value=e._value),t},insertStaticContent(e,t,n,o){const r=n?n.previousSibling:t.lastChild;let s=hs.get(e);if(!s){const t=ds.createElement("template");if(t.innerHTML=o?`${e}`:e,s=t.content,o){const e=s.firstChild;for(;e.firstChild;)s.appendChild(e.firstChild);s.removeChild(e)}hs.set(e,s)}return t.insertBefore(s.cloneNode(!0),n),[r?r.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}};const gs=/\s*!important$/;function vs(e,t,n){if(N(n))n.forEach((n=>vs(e,t,n)));else if(t.startsWith("--"))e.setProperty(t,n);else{const o=function(e,t){const n=bs[t];if(n)return n;let o=D(t);if("filter"!==o&&o in e)return bs[t]=o;o=K(o);for(let r=0;rdocument.createEvent("Event").timeStamp&&(Ss=()=>performance.now());const e=navigator.userAgent.match(/firefox\/(\d+)/i);xs=!!(e&&Number(e[1])<=53)}let Cs=0;const ws=Promise.resolve(),ks=()=>{Cs=0};function Ts(e,t,n,o){e.addEventListener(t,n,o)}function Ns(e,t,n,o,r=null){const s=e._vei||(e._vei={}),i=s[t];if(o&&i)i.value=o;else{const[n,l]=function(e){let t;if(Es.test(e)){let n;for(t={};n=e.match(Es);)e=e.slice(0,e.length-n[0].length),t[n[0].toLowerCase()]=!0}return[z(e.slice(2)),t]}(t);if(o){Ts(e,n,s[t]=function(e,t){const n=e=>{const o=e.timeStamp||Ss();(xs||o>=n.attached-1)&&Fr(function(e,t){if(N(t)){const n=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0},t.map((e=>t=>!t._stopped&&e(t)))}return t}(e,n.value),t,5,[e])};return n.value=e,n.attached=(()=>Cs||(ws.then(ks),Cs=Ss()))(),n}(o,r),l)}else i&&(!function(e,t,n,o){e.removeEventListener(t,n,o)}(e,n,i,l),s[t]=void 0)}}const Es=/(?:Once|Passive|Capture)$/;const $s=/^on[a-z]/;function Rs(e,t){const n=dn(e);class o extends As{constructor(e){super(n,e,t)}}return o.def=n,o}const Fs="undefined"!=typeof HTMLElement?HTMLElement:class{};class As extends Fs{constructor(e,t={},n){super(),this._def=e,this._props=t,this._instance=null,this._connected=!1,this._resolved=!1,this.shadowRoot&&n?n(this._createVNode(),this.shadowRoot):this.attachShadow({mode:"open"});for(let o=0;o{for(const t of e)this._setAttr(t.attributeName)})).observe(this,{attributes:!0})}connectedCallback(){this._connected=!0,this._instance||(this._resolveDef(),Ei(this._createVNode(),this.shadowRoot))}disconnectedCallback(){this._connected=!1,Kr((()=>{this._connected||(Ei(null,this.shadowRoot),this._instance=null)}))}_resolveDef(){if(this._resolved)return;const e=e=>{this._resolved=!0;for(const r of Object.keys(this))"_"!==r[0]&&this._setProp(r,this[r]);const{props:t,styles:n}=e,o=t?N(t)?t:Object.keys(t):[];for(const r of o.map(D))Object.defineProperty(this,r,{get(){return this._getProp(r)},set(e){this._setProp(r,e)}});this._applyStyles(n)},t=this._def.__asyncLoader;t?t().then(e):e(this._def)}_setAttr(e){this._setProp(D(e),Q(this.getAttribute(e)),!1)}_getProp(e){return this._props[e]}_setProp(e,t,n=!0){t!==this._props[e]&&(this._props[e]=t,this._instance&&Ei(this._createVNode(),this.shadowRoot),n&&(!0===t?this.setAttribute(z(e),""):"string"==typeof t||"number"==typeof t?this.setAttribute(z(e),t+""):t||this.removeAttribute(z(e))))}_createVNode(){const e=Jo(this._def,C({},this._props));return this._instance||(e.ce=e=>{this._instance=e,e.isCE=!0,e.emit=(e,...t)=>{this.dispatchEvent(new CustomEvent(e,{detail:t}))};let t=this;for(;t=t&&(t.parentNode||t.host);)if(t instanceof As){e.parent=t._instance;break}}),e}_applyStyles(e){e&&e.forEach((e=>{const t=document.createElement("style");t.textContent=e,this.shadowRoot.appendChild(t)}))}}function Ms(e,t){if(128&e.shapeFlag){const n=e.suspense;e=n.activeBranch,n.pendingBranch&&!n.isHydrating&&n.effects.push((()=>{Ms(n.activeBranch,t)}))}for(;e.component;)e=e.component.subTree;if(1&e.shapeFlag&&e.el)Os(e.el,t);else if(e.type===Fo)e.children.forEach((e=>Ms(e,t)));else if(e.type===Oo){let{el:n,anchor:o}=e;for(;n&&(Os(n,t),n!==o);)n=n.nextSibling}}function Os(e,t){if(1===e.nodeType){const n=e.style;for(const e in t)n.setProperty(`--${e}`,t[e])}}const Ps="transition",Is="animation",Vs=(e,{slots:t})=>as(sn,Hs(e),t);Vs.displayName="Transition";const Bs={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},Ls=Vs.props=C({},sn.props,Bs),js=(e,t=[])=>{N(e)?e.forEach((e=>e(...t))):e&&e(...t)},Us=e=>!!e&&(N(e)?e.some((e=>e.length>1)):e.length>1);function Hs(e){const t={};for(const C in e)C in Bs||(t[C]=e[C]);if(!1===e.css)return t;const{name:n="v",type:o,duration:r,enterFromClass:s=`${n}-enter-from`,enterActiveClass:i=`${n}-enter-active`,enterToClass:l=`${n}-enter-to`,appearFromClass:c=s,appearActiveClass:a=i,appearToClass:u=l,leaveFromClass:p=`${n}-leave-from`,leaveActiveClass:f=`${n}-leave-active`,leaveToClass:d=`${n}-leave-to`}=e,h=function(e){if(null==e)return null;if(O(e))return[Ds(e.enter),Ds(e.leave)];{const t=Ds(e);return[t,t]}}(r),m=h&&h[0],g=h&&h[1],{onBeforeEnter:v,onEnter:y,onEnterCancelled:b,onLeave:_,onLeaveCancelled:S,onBeforeAppear:x=v,onAppear:w=y,onAppearCancelled:k=b}=t,T=(e,t,n)=>{zs(e,t?u:l),zs(e,t?a:i),n&&n()},N=(e,t)=>{zs(e,d),zs(e,f),t&&t()},E=e=>(t,n)=>{const r=e?w:y,i=()=>T(t,e,n);js(r,[t,i]),Ks((()=>{zs(t,e?c:s),Ws(t,e?u:l),Us(r)||qs(t,o,m,i)}))};return C(t,{onBeforeEnter(e){js(v,[e]),Ws(e,s),Ws(e,i)},onBeforeAppear(e){js(x,[e]),Ws(e,c),Ws(e,a)},onEnter:E(!1),onAppear:E(!0),onLeave(e,t){const n=()=>N(e,t);Ws(e,p),Xs(),Ws(e,f),Ks((()=>{zs(e,p),Ws(e,d),Us(_)||qs(e,o,g,n)})),js(_,[e,n])},onEnterCancelled(e){T(e,!1),js(b,[e])},onAppearCancelled(e){T(e,!0),js(k,[e])},onLeaveCancelled(e){N(e),js(S,[e])}})}function Ds(e){return Q(e)}function Ws(e,t){t.split(/\s+/).forEach((t=>t&&e.classList.add(t))),(e._vtc||(e._vtc=new Set)).add(t)}function zs(e,t){t.split(/\s+/).forEach((t=>t&&e.classList.remove(t)));const{_vtc:n}=e;n&&(n.delete(t),n.size||(e._vtc=void 0))}function Ks(e){requestAnimationFrame((()=>{requestAnimationFrame(e)}))}let Gs=0;function qs(e,t,n,o){const r=e._endId=++Gs,s=()=>{r===e._endId&&o()};if(n)return setTimeout(s,n);const{type:i,timeout:l,propCount:c}=Js(e,t);if(!i)return o();const a=i+"end";let u=0;const p=()=>{e.removeEventListener(a,f),s()},f=t=>{t.target===e&&++u>=c&&p()};setTimeout((()=>{u(n[e]||"").split(", "),r=o("transitionDelay"),s=o("transitionDuration"),i=Zs(r,s),l=o("animationDelay"),c=o("animationDuration"),a=Zs(l,c);let u=null,p=0,f=0;t===Ps?i>0&&(u=Ps,p=i,f=s.length):t===Is?a>0&&(u=Is,p=a,f=c.length):(p=Math.max(i,a),u=p>0?i>a?Ps:Is:null,f=u?u===Ps?s.length:c.length:0);return{type:u,timeout:p,propCount:f,hasTransform:u===Ps&&/\b(transform|all)(,|$)/.test(n.transitionProperty)}}function Zs(e,t){for(;e.lengthQs(t)+Qs(e[n]))))}function Qs(e){return 1e3*Number(e.slice(0,-1).replace(",","."))}function Xs(){return document.body.offsetHeight}const Ys=new WeakMap,ei=new WeakMap,ti={name:"TransitionGroup",props:C({},Ls,{tag:String,moveClass:String}),setup(e,{slots:t}){const n=pr(),o=on();let r,s;return Rn((()=>{if(!r.length)return;const t=e.moveClass||`${e.name||"v"}-move`;if(!function(e,t,n){const o=e.cloneNode();e._vtc&&e._vtc.forEach((e=>{e.split(/\s+/).forEach((e=>e&&o.classList.remove(e)))}));n.split(/\s+/).forEach((e=>e&&o.classList.add(e))),o.style.display="none";const r=1===t.nodeType?t:t.parentNode;r.appendChild(o);const{hasTransform:s}=Js(o);return r.removeChild(o),s}(r[0].el,n.vnode.el,t))return;r.forEach(ni),r.forEach(oi);const o=r.filter(ri);Xs(),o.forEach((e=>{const n=e.el,o=n.style;Ws(n,t),o.transform=o.webkitTransform=o.transitionDuration="";const r=n._moveCb=e=>{e&&e.target!==n||e&&!/transform$/.test(e.propertyName)||(n.removeEventListener("transitionend",r),n._moveCb=null,zs(n,t))};n.addEventListener("transitionend",r)}))})),()=>{const i=bt(e),l=Hs(i);let c=i.tag||Fo;r=s,s=t.default?fn(t.default()):[];for(let e=0;e{const t=e.props["onUpdate:modelValue"];return N(t)?e=>J(t,e):t};function ii(e){e.target.composing=!0}function li(e){const t=e.target;t.composing&&(t.composing=!1,function(e,t){const n=document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),e.dispatchEvent(n)}(t,"input"))}const ci={created(e,{modifiers:{lazy:t,trim:n,number:o}},r){e._assign=si(r);const s=o||r.props&&"number"===r.props.type;Ts(e,t?"change":"input",(t=>{if(t.target.composing)return;let o=e.value;n?o=o.trim():s&&(o=Q(o)),e._assign(o)})),n&&Ts(e,"change",(()=>{e.value=e.value.trim()})),t||(Ts(e,"compositionstart",ii),Ts(e,"compositionend",li),Ts(e,"change",li))},mounted(e,{value:t}){e.value=null==t?"":t},beforeUpdate(e,{value:t,modifiers:{lazy:n,trim:o,number:r}},s){if(e._assign=si(s),e.composing)return;if(document.activeElement===e){if(n)return;if(o&&e.value.trim()===t)return;if((r||"number"===e.type)&&Q(e.value)===t)return}const i=null==t?"":t;e.value!==i&&(e.value=i)}},ai={deep:!0,created(e,t,n){e._assign=si(n),Ts(e,"change",(()=>{const t=e._modelValue,n=hi(e),o=e.checked,r=e._assign;if(N(t)){const e=h(t,n),s=-1!==e;if(o&&!s)r(t.concat(n));else if(!o&&s){const n=[...t];n.splice(e,1),r(n)}}else if($(t)){const e=new Set(t);o?e.add(n):e.delete(n),r(e)}else r(mi(e,o))}))},mounted:ui,beforeUpdate(e,t,n){e._assign=si(n),ui(e,t,n)}};function ui(e,{value:t,oldValue:n},o){e._modelValue=t,N(t)?e.checked=h(t,o.props.value)>-1:$(t)?e.checked=t.has(o.props.value):t!==n&&(e.checked=d(t,mi(e,!0)))}const pi={created(e,{value:t},n){e.checked=d(t,n.props.value),e._assign=si(n),Ts(e,"change",(()=>{e._assign(hi(e))}))},beforeUpdate(e,{value:t,oldValue:n},o){e._assign=si(o),t!==n&&(e.checked=d(t,o.props.value))}},fi={deep:!0,created(e,{value:t,modifiers:{number:n}},o){const r=$(t);Ts(e,"change",(()=>{const t=Array.prototype.filter.call(e.options,(e=>e.selected)).map((e=>n?Q(hi(e)):hi(e)));e._assign(e.multiple?r?new Set(t):t:t[0])})),e._assign=si(o)},mounted(e,{value:t}){di(e,t)},beforeUpdate(e,t,n){e._assign=si(n)},updated(e,{value:t}){di(e,t)}};function di(e,t){const n=e.multiple;if(!n||N(t)||$(t)){for(let o=0,r=e.options.length;o-1:t.has(s);else if(d(hi(r),t))return void(e.selectedIndex!==o&&(e.selectedIndex=o))}n||-1===e.selectedIndex||(e.selectedIndex=-1)}}function hi(e){return"_value"in e?e._value:e.value}function mi(e,t){const n=t?"_trueValue":"_falseValue";return n in e?e[n]:t}const gi={created(e,t,n){vi(e,t,n,null,"created")},mounted(e,t,n){vi(e,t,n,null,"mounted")},beforeUpdate(e,t,n,o){vi(e,t,n,o,"beforeUpdate")},updated(e,t,n,o){vi(e,t,n,o,"updated")}};function vi(e,t,n,o,r){let s;switch(e.tagName){case"SELECT":s=fi;break;case"TEXTAREA":s=ci;break;default:switch(n.props&&n.props.type){case"checkbox":s=ai;break;case"radio":s=pi;break;default:s=ci}}const i=s[r];i&&i(e,t,n,o)}const yi=["ctrl","shift","alt","meta"],bi={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&0!==e.button,middle:e=>"button"in e&&1!==e.button,right:e=>"button"in e&&2!==e.button,exact:(e,t)=>yi.some((n=>e[`${n}Key`]&&!t.includes(n)))},_i={esc:"escape",space:" ",up:"arrow-up",left:"arrow-left",right:"arrow-right",down:"arrow-down",delete:"backspace"},Si={beforeMount(e,{value:t},{transition:n}){e._vod="none"===e.style.display?"":e.style.display,n&&t?n.beforeEnter(e):xi(e,t)},mounted(e,{value:t},{transition:n}){n&&t&&n.enter(e)},updated(e,{value:t,oldValue:n},{transition:o}){!t!=!n&&(o?t?(o.beforeEnter(e),xi(e,!0),o.enter(e)):o.leave(e,(()=>{xi(e,!1)})):xi(e,t))},beforeUnmount(e,{value:t}){xi(e,t)}};function xi(e,t){e.style.display=t?e._vod:"none"}const Ci=C({patchProp:(e,t,n,s,i=!1,l,c,a,u)=>{"class"===t?function(e,t,n){const o=e._vtc;o&&(t=(t?[t,...o]:[...o]).join(" ")),null==t?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}(e,s,i):"style"===t?function(e,t,n){const o=e.style;if(n)if(A(n)){if(t!==n){const t=o.display;o.cssText=n,"_vod"in e&&(o.display=t)}}else{for(const e in n)vs(o,e,n[e]);if(t&&!A(t))for(const e in t)null==n[e]&&vs(o,e,"")}else e.removeAttribute("style")}(e,n,s):S(t)?x(t)||Ns(e,t,0,s,c):("."===t[0]?(t=t.slice(1),1):"^"===t[0]?(t=t.slice(1),0):function(e,t,n,o){if(o)return"innerHTML"===t||"textContent"===t||!!(t in e&&$s.test(t)&&F(n));if("spellcheck"===t||"draggable"===t)return!1;if("form"===t)return!1;if("list"===t&&"INPUT"===e.tagName)return!1;if("type"===t&&"TEXTAREA"===e.tagName)return!1;if($s.test(t)&&A(n))return!1;return t in e}(e,t,s,i))?function(e,t,n,o,s,i,l){if("innerHTML"===t||"textContent"===t)return o&&l(o,s,i),void(e[t]=null==n?"":n);if("value"===t&&"PROGRESS"!==e.tagName){e._value=n;const o=null==n?"":n;return e.value!==o&&(e.value=o),void(null==n&&e.removeAttribute(t))}if(""===n||null==n){const o=typeof e[t];if("boolean"===o)return void(e[t]=r(n));if(null==n&&"string"===o)return e[t]="",void e.removeAttribute(t);if("number"===o){try{e[t]=0}catch(c){}return void e.removeAttribute(t)}}try{e[t]=n}catch(a){}}(e,t,s,l,c,a,u):("true-value"===t?e._trueValue=s:"false-value"===t&&(e._falseValue=s),function(e,t,n,s,i){if(s&&t.startsWith("xlink:"))null==n?e.removeAttributeNS(_s,t.slice(6,t.length)):e.setAttributeNS(_s,t,n);else{const s=o(t);null==n||s&&!r(n)?e.removeAttribute(t):e.setAttribute(t,s?"":n)}}(e,t,s,i))}},ms);let wi,ki=!1;function Ti(){return wi||(wi=go(Ci))}function Ni(){return wi=ki?wi:vo(Ci),ki=!0,wi}const Ei=(...e)=>{Ti().render(...e)},$i=(...e)=>{Ni().hydrate(...e)};function Ri(e){if(A(e)){return document.querySelector(e)}return e}function Fi(e){throw e}function Ai(e){}function Mi(e,t,n,o){const r=new SyntaxError(String(e));return r.code=e,r.loc=t,r}const Oi=Symbol(""),Pi=Symbol(""),Ii=Symbol(""),Vi=Symbol(""),Bi=Symbol(""),Li=Symbol(""),ji=Symbol(""),Ui=Symbol(""),Hi=Symbol(""),Di=Symbol(""),Wi=Symbol(""),zi=Symbol(""),Ki=Symbol(""),Gi=Symbol(""),qi=Symbol(""),Ji=Symbol(""),Zi=Symbol(""),Qi=Symbol(""),Xi=Symbol(""),Yi=Symbol(""),el=Symbol(""),tl=Symbol(""),nl=Symbol(""),ol=Symbol(""),rl=Symbol(""),sl=Symbol(""),il=Symbol(""),ll=Symbol(""),cl=Symbol(""),al=Symbol(""),ul=Symbol(""),pl=Symbol(""),fl=Symbol(""),dl=Symbol(""),hl=Symbol(""),ml=Symbol(""),gl=Symbol(""),vl=Symbol(""),yl=Symbol(""),bl=Symbol(""),_l={[Oi]:"Fragment",[Pi]:"Teleport",[Ii]:"Suspense",[Vi]:"KeepAlive",[Bi]:"BaseTransition",[Li]:"openBlock",[ji]:"createBlock",[Ui]:"createElementBlock",[Hi]:"createVNode",[Di]:"createElementVNode",[Wi]:"createCommentVNode",[zi]:"createTextVNode",[Ki]:"createStaticVNode",[Gi]:"resolveComponent",[qi]:"resolveDynamicComponent",[Ji]:"resolveDirective",[Zi]:"resolveFilter",[Qi]:"withDirectives",[Xi]:"renderList",[Yi]:"renderSlot",[el]:"createSlots",[tl]:"toDisplayString",[nl]:"mergeProps",[ol]:"normalizeClass",[rl]:"normalizeStyle",[sl]:"normalizeProps",[il]:"guardReactiveProps",[ll]:"toHandlers",[cl]:"camelize",[al]:"capitalize",[ul]:"toHandlerKey",[pl]:"setBlockTracking",[fl]:"pushScopeId",[dl]:"popScopeId",[hl]:"withScopeId",[ml]:"withCtx",[gl]:"unref",[vl]:"isRef",[yl]:"withMemo",[bl]:"isMemoSame"};const Sl={source:"",start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}};function xl(e,t,n,o,r,s,i,l=!1,c=!1,a=!1,u=Sl){return e&&(l?(e.helper(Li),e.helper(Ql(e.inSSR,a))):e.helper(Zl(e.inSSR,a)),i&&e.helper(Qi)),{type:13,tag:t,props:n,children:o,patchFlag:r,dynamicProps:s,directives:i,isBlock:l,disableTracking:c,isComponent:a,loc:u}}function Cl(e,t=Sl){return{type:17,loc:t,elements:e}}function wl(e,t=Sl){return{type:15,loc:t,properties:e}}function kl(e,t){return{type:16,loc:Sl,key:A(e)?Tl(e,!0):e,value:t}}function Tl(e,t=!1,n=Sl,o=0){return{type:4,loc:n,content:e,isStatic:t,constType:t?3:o}}function Nl(e,t=Sl){return{type:8,loc:t,children:e}}function El(e,t=[],n=Sl){return{type:14,loc:n,callee:e,arguments:t}}function $l(e,t,n=!1,o=!1,r=Sl){return{type:18,params:e,returns:t,newline:n,isSlot:o,loc:r}}function Rl(e,t,n,o=!0){return{type:19,test:e,consequent:t,alternate:n,newline:o,loc:Sl}}const Fl=e=>4===e.type&&e.isStatic,Al=(e,t)=>e===t||e===z(t);function Ml(e){return Al(e,"Teleport")?Pi:Al(e,"Suspense")?Ii:Al(e,"KeepAlive")?Vi:Al(e,"BaseTransition")?Bi:void 0}const Ol=/^\d|[^\$\w]/,Pl=e=>!Ol.test(e),Il=/[A-Za-z_$\xA0-\uFFFF]/,Vl=/[\.\?\w$\xA0-\uFFFF]/,Bl=/\s+[.[]\s*|\s*[.[]\s+/g,Ll=e=>{e=e.trim().replace(Bl,(e=>e.trim()));let t=0,n=[],o=0,r=0,s=null;for(let i=0;i4===e.key.type&&e.key.content===n))}e||s.properties.unshift(t),o=s}else o=El(n.helper(nl),[wl([t]),s]),r&&r.callee===il&&(r=i[i.length-2]);13===e.type?r?r.arguments[0]=o:e.props=o:r?r.arguments[0]=o:e.arguments[2]=o}function tc(e,t){return`_${t}_${e.replace(/[^\w]/g,((t,n)=>"-"===t?"_":e.charCodeAt(n).toString()))}`}function nc(e,{helper:t,removeHelper:n,inSSR:o}){e.isBlock||(e.isBlock=!0,n(Zl(o,e.isComponent)),t(Li),t(Ql(o,e.isComponent)))}const oc=/&(gt|lt|amp|apos|quot);/g,rc={gt:">",lt:"<",amp:"&",apos:"'",quot:'"'},sc={delimiters:["{{","}}"],getNamespace:()=>0,getTextMode:()=>0,isVoidTag:b,isPreTag:b,isCustomElement:b,decodeEntities:e=>e.replace(oc,((e,t)=>rc[t])),onError:Fi,onWarn:Ai,comments:!1};function ic(e,t={}){const n=function(e,t){const n=C({},sc);let o;for(o in t)n[o]=void 0===t[o]?sc[o]:t[o];return{options:n,column:1,line:1,offset:0,originalSource:e,source:e,inPre:!1,inVPre:!1,onWarn:n.onWarn}}(e,t),o=_c(n);return function(e,t=Sl){return{type:0,children:e,helpers:[],components:[],directives:[],hoists:[],imports:[],cached:0,temps:0,codegenNode:void 0,loc:t}}(lc(n,0,[]),Sc(n,o))}function lc(e,t,n){const o=xc(n),r=o?o.ns:0,s=[];for(;!Nc(e,t,n);){const i=e.source;let l;if(0===t||1===t)if(!e.inVPre&&Cc(i,e.options.delimiters[0]))l=vc(e,t);else if(0===t&&"<"===i[0])if(1===i.length);else if("!"===i[1])l=Cc(i,"\x3c!--")?uc(e):Cc(i,""===i[2]){wc(e,3);continue}if(/[a-z]/i.test(i[2])){hc(e,1,o);continue}l=pc(e)}else/[a-z]/i.test(i[1])?l=fc(e,n):"?"===i[1]&&(l=pc(e));if(l||(l=yc(e,t)),N(l))for(let e=0;e/.exec(e.source);if(o){n=e.source.slice(4,o.index);const t=e.source.slice(0,o.index);let r=1,s=0;for(;-1!==(s=t.indexOf("\x3c!--",r));)wc(e,s-r+1),r=s+1;wc(e,o.index+o[0].length-r+1)}else n=e.source.slice(4),wc(e,e.source.length);return{type:3,content:n,loc:Sc(e,t)}}function pc(e){const t=_c(e),n="?"===e.source[1]?1:2;let o;const r=e.source.indexOf(">");return-1===r?(o=e.source.slice(n),wc(e,e.source.length)):(o=e.source.slice(n,r),wc(e,r+1)),{type:3,content:o,loc:Sc(e,t)}}function fc(e,t){const n=e.inPre,o=e.inVPre,r=xc(t),s=hc(e,0,r),i=e.inPre&&!n,l=e.inVPre&&!o;if(s.isSelfClosing||e.options.isVoidTag(s.tag))return i&&(e.inPre=!1),l&&(e.inVPre=!1),s;t.push(s);const c=e.options.getTextMode(s,r),a=lc(e,c,t);if(t.pop(),s.children=a,Ec(e.source,s.tag))hc(e,1,r);else if(0===e.source.length&&"script"===s.tag.toLowerCase()){const e=a[0];e&&Cc(e.loc.source,"\x3c!--")}return s.loc=Sc(e,s.loc.start),i&&(e.inPre=!1),l&&(e.inVPre=!1),s}const dc=t("if,else,else-if,for,slot");function hc(e,t,n){const o=_c(e),r=/^<\/?([a-z][^\t\r\n\f />]*)/i.exec(e.source),s=r[1],i=e.options.getNamespace(s,n);wc(e,r[0].length),kc(e);const l=_c(e),c=e.source;e.options.isPreTag(s)&&(e.inPre=!0);let a=mc(e,t);0===t&&!e.inVPre&&a.some((e=>7===e.type&&"pre"===e.name))&&(e.inVPre=!0,C(e,l),e.source=c,a=mc(e,t).filter((e=>"v-pre"!==e.name)));let u=!1;if(0===e.source.length||(u=Cc(e.source,"/>"),wc(e,u?2:1)),1===t)return;let p=0;return e.inVPre||("slot"===s?p=2:"template"===s?a.some((e=>7===e.type&&dc(e.name)))&&(p=3):function(e,t,n){const o=n.options;if(o.isCustomElement(e))return!1;if("component"===e||/^[A-Z]/.test(e)||Ml(e)||o.isBuiltInComponent&&o.isBuiltInComponent(e)||o.isNativeTag&&!o.isNativeTag(e))return!0;for(let r=0;r0&&!Cc(e.source,">")&&!Cc(e.source,"/>");){if(Cc(e.source,"/")){wc(e,1),kc(e);continue}const r=gc(e,o);0===t&&n.push(r),/^[^\t\r\n\f />]/.test(e.source),kc(e)}return n}function gc(e,t){const n=_c(e),o=/^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(e.source)[0];t.has(o),t.add(o);{const e=/["'<]/g;let t;for(;t=e.exec(o););}let r;wc(e,o.length),/^[\t\r\n\f ]*=/.test(e.source)&&(kc(e),wc(e,1),kc(e),r=function(e){const t=_c(e);let n;const o=e.source[0],r='"'===o||"'"===o;if(r){wc(e,1);const t=e.source.indexOf(o);-1===t?n=bc(e,e.source.length,4):(n=bc(e,t,4),wc(e,1))}else{const t=/^[^\t\r\n\f >]+/.exec(e.source);if(!t)return;const o=/["'<=`]/g;let r;for(;r=o.exec(t[0]););n=bc(e,t[0].length,4)}return{content:n,isQuoted:r,loc:Sc(e,t)}}(e));const s=Sc(e,n);if(!e.inVPre&&/^(v-|:|\.|@|#)/.test(o)){const t=/(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(o);let i,l=Cc(o,"."),c=t[1]||(l||Cc(o,":")?"bind":Cc(o,"@")?"on":"slot");if(t[2]){const r="slot"===c,s=o.lastIndexOf(t[2]),l=Sc(e,Tc(e,n,s),Tc(e,n,s+t[2].length+(r&&t[3]||"").length));let a=t[2],u=!0;a.startsWith("[")?(u=!1,a.endsWith("]"),a=a.substr(1,a.length-2)):r&&(a+=t[3]||""),i={type:4,content:a,isStatic:u,constType:u?3:0,loc:l}}if(r&&r.isQuoted){const e=r.loc;e.start.offset++,e.start.column++,e.end=Ul(e.start,r.content),e.source=e.source.slice(1,-1)}const a=t[3]?t[3].substr(1).split("."):[];return l&&a.push("prop"),{type:7,name:c,exp:r&&{type:4,content:r.content,isStatic:!1,constType:0,loc:r.loc},arg:i,modifiers:a,loc:s}}return{type:6,name:o,value:r&&{type:2,content:r.content,loc:r.loc},loc:s}}function vc(e,t){const[n,o]=e.options.delimiters,r=e.source.indexOf(o,n.length);if(-1===r)return;const s=_c(e);wc(e,n.length);const i=_c(e),l=_c(e),c=r-n.length,a=e.source.slice(0,c),u=bc(e,c,t),p=u.trim(),f=u.indexOf(p);f>0&&Hl(i,a,f);return Hl(l,a,c-(u.length-p.length-f)),wc(e,o.length),{type:5,content:{type:4,isStatic:!1,constType:0,content:p,loc:Sc(e,i,l)},loc:Sc(e,s)}}function yc(e,t){const n=["<",e.options.delimiters[0]];3===t&&n.push("]]>");let o=e.source.length;for(let s=0;st&&(o=t)}const r=_c(e);return{type:2,content:bc(e,o,t),loc:Sc(e,r)}}function bc(e,t,n){const o=e.source.slice(0,t);return wc(e,t),2===n||3===n||-1===o.indexOf("&")?o:e.options.decodeEntities(o,4===n)}function _c(e){const{column:t,line:n,offset:o}=e;return{column:t,line:n,offset:o}}function Sc(e,t,n){return{start:t,end:n=n||_c(e),source:e.originalSource.slice(t.offset,n.offset)}}function xc(e){return e[e.length-1]}function Cc(e,t){return e.startsWith(t)}function wc(e,t){const{source:n}=e;Hl(e,n,t),e.source=n.slice(t)}function kc(e){const t=/^[\t\r\n\f ]+/.exec(e.source);t&&wc(e,t[0].length)}function Tc(e,t,n){return Ul(t,e.originalSource.slice(t.offset,n),n)}function Nc(e,t,n){const o=e.source;switch(t){case 0:if(Cc(o,"=0;--e)if(Ec(o,n[e].tag))return!0;break;case 1:case 2:{const e=xc(n);if(e&&Ec(o,e.tag))return!0;break}case 3:if(Cc(o,"]]>"))return!0}return!o}function Ec(e,t){return Cc(e,"]/.test(e[2+t.length]||">")}function $c(e,t){Fc(e,t,Rc(e,e.children[0]))}function Rc(e,t){const{children:n}=e;return 1===n.length&&1===t.type&&!Jl(t)}function Fc(e,t,n=!1){let o=!0;const{children:r}=e,s=r.length;let i=0;for(let l=0;l0){if(r<3&&(o=!1),r>=2){e.codegenNode.patchFlag="-1",e.codegenNode=t.hoist(e.codegenNode),i++;continue}}else{const n=e.codegenNode;if(13===n.type){const o=Vc(n);if((!o||512===o||1===o)&&Pc(e,t)>=2){const o=Ic(e);o&&(n.props=t.hoist(o))}n.dynamicProps&&(n.dynamicProps=t.hoist(n.dynamicProps))}}}else if(12===e.type){const n=Ac(e.content,t);n>0&&(n<3&&(o=!1),n>=2&&(e.codegenNode=t.hoist(e.codegenNode),i++))}if(1===e.type){const n=1===e.tagType;n&&t.scopes.vSlot++,Fc(e,t),n&&t.scopes.vSlot--}else if(11===e.type)Fc(e,t,1===e.children.length);else if(9===e.type)for(let n=0;n1)for(let r=0;r`_${_l[k.helper(e)]}`,replaceNode(e){k.parent.children[k.childIndex]=k.currentNode=e},removeNode(e){const t=e?k.parent.children.indexOf(e):k.currentNode?k.childIndex:-1;e&&e!==k.currentNode?k.childIndex>t&&(k.childIndex--,k.onNodeRemoved()):(k.currentNode=null,k.onNodeRemoved()),k.parent.children.splice(t,1)},onNodeRemoved:()=>{},addIdentifiers(e){},removeIdentifiers(e){},hoist(e){A(e)&&(e=Tl(e)),k.hoists.push(e);const t=Tl(`_hoisted_${k.hoists.length}`,!1,e.loc,2);return t.hoisted=e,t},cache:(e,t=!1)=>function(e,t,n=!1){return{type:20,index:e,value:t,isVNode:n,loc:Sl}}(k.cached++,e,t)};return k}function Lc(e,t){const n=Bc(e,t);jc(e,n),t.hoistStatic&&$c(e,n),t.ssr||function(e,t){const{helper:n}=t,{children:o}=e;if(1===o.length){const n=o[0];if(Rc(e,n)&&n.codegenNode){const o=n.codegenNode;13===o.type&&nc(o,t),e.codegenNode=o}else e.codegenNode=n}else if(o.length>1){let o=64;e.codegenNode=xl(t,n(Oi),void 0,e.children,o+"",void 0,void 0,!0,void 0,!1)}}(e,n),e.helpers=[...n.helpers.keys()],e.components=[...n.components],e.directives=[...n.directives],e.imports=n.imports,e.hoists=n.hoists,e.temps=n.temps,e.cached=n.cached}function jc(e,t){t.currentNode=e;const{nodeTransforms:n}=t,o=[];for(let s=0;s{n--};for(;nt===e:t=>e.test(t);return(e,o)=>{if(1===e.type){const{props:r}=e;if(3===e.tagType&&r.some(Gl))return;const s=[];for(let i=0;i`_${_l[e]}`,push(e,t){f.code+=e},indent(){d(++f.indentLevel)},deindent(e=!1){e?--f.indentLevel:d(--f.indentLevel)},newline(){d(f.indentLevel)}};function d(e){f.push("\n"+" ".repeat(e))}return f}(e,t);t.onContextCreated&&t.onContextCreated(n);const{mode:o,push:r,prefixIdentifiers:s,indent:i,deindent:l,newline:c,ssr:a}=n,u=e.helpers.length>0,p=!s&&"module"!==o;!function(e,t){const{push:n,newline:o,runtimeGlobalName:r}=t,s=r,i=e=>`${_l[e]}: _${_l[e]}`;if(e.helpers.length>0&&(n(`const _Vue = ${s}\n`),e.hoists.length)){n(`const { ${[Hi,Di,Wi,zi,Ki].filter((t=>e.helpers.includes(t))).map(i).join(", ")} } = _Vue\n`)}(function(e,t){if(!e.length)return;t.pure=!0;const{push:n,newline:o}=t;o(),e.forEach(((e,r)=>{e&&(n(`const _hoisted_${r+1} = `),Gc(e,t),o())})),t.pure=!1})(e.hoists,t),o(),n("return ")}(e,n);if(r(`function ${a?"ssrRender":"render"}(${(a?["_ctx","_push","_parent","_attrs"]:["_ctx","_cache"]).join(", ")}) {`),i(),p&&(r("with (_ctx) {"),i(),u&&(r(`const { ${e.helpers.map((e=>`${_l[e]}: _${_l[e]}`)).join(", ")} } = _Vue`),r("\n"),c())),e.components.length&&(Wc(e.components,"component",n),(e.directives.length||e.temps>0)&&c()),e.directives.length&&(Wc(e.directives,"directive",n),e.temps>0&&c()),e.temps>0){r("let ");for(let t=0;t0?", ":""}_temp${t}`)}return(e.components.length||e.directives.length||e.temps)&&(r("\n"),c()),a||r("return "),e.codegenNode?Gc(e.codegenNode,n):r("null"),p&&(l(),r("}")),l(),r("}"),{ast:e,code:n.code,preamble:"",map:n.map?n.map.toJSON():void 0}}function Wc(e,t,{helper:n,push:o,newline:r,isTS:s}){const i=n("component"===t?Gi:Ji);for(let l=0;l3||!1;t.push("["),n&&t.indent(),Kc(e,t,n),n&&t.deindent(),t.push("]")}function Kc(e,t,n=!1,o=!0){const{push:r,newline:s}=t;for(let i=0;ie||"null"))}([s,i,l,c,a]),t),n(")"),p&&n(")");u&&(n(", "),Gc(u,t),n(")"))}(e,t);break;case 14:!function(e,t){const{push:n,helper:o,pure:r}=t,s=A(e.callee)?e.callee:o(e.callee);r&&n(Hc);n(s+"(",e),Kc(e.arguments,t),n(")")}(e,t);break;case 15:!function(e,t){const{push:n,indent:o,deindent:r,newline:s}=t,{properties:i}=e;if(!i.length)return void n("{}",e);const l=i.length>1||!1;n(l?"{":"{ "),l&&o();for(let c=0;c "),(c||l)&&(n("{"),o());i?(c&&n("return "),N(i)?zc(i,t):Gc(i,t)):l&&Gc(l,t);(c||l)&&(r(),n("}"));a&&n(")")}(e,t);break;case 19:!function(e,t){const{test:n,consequent:o,alternate:r,newline:s}=e,{push:i,indent:l,deindent:c,newline:a}=t;if(4===n.type){const e=!Pl(n.content);e&&i("("),qc(n,t),e&&i(")")}else i("("),Gc(n,t),i(")");s&&l(),t.indentLevel++,s||i(" "),i("? "),Gc(o,t),t.indentLevel--,s&&a(),s||i(" "),i(": ");const u=19===r.type;u||t.indentLevel++;Gc(r,t),u||t.indentLevel--;s&&c(!0)}(e,t);break;case 20:!function(e,t){const{push:n,helper:o,indent:r,deindent:s,newline:i}=t;n(`_cache[${e.index}] || (`),e.isVNode&&(r(),n(`${o(pl)}(-1),`),i());n(`_cache[${e.index}] = `),Gc(e.value,t),e.isVNode&&(n(","),i(),n(`${o(pl)}(1),`),i(),n(`_cache[${e.index}]`),s());n(")")}(e,t);break;case 21:Kc(e.body,t,!0,!1)}}function qc(e,t){const{content:n,isStatic:o}=e;t.push(o?JSON.stringify(n):n,e)}function Jc(e,t){for(let n=0;nfunction(e,t,n,o){if(!("else"===t.name||t.exp&&t.exp.content.trim())){t.exp=Tl("true",!1,t.exp?t.exp.loc:e.loc)}if("if"===t.name){const r=Xc(e,t),s={type:9,loc:e.loc,branches:[r]};if(n.replaceNode(s),o)return o(s,r,!0)}else{const r=n.parent.children;let s=r.indexOf(e);for(;s-- >=-1;){const i=r[s];if(!i||2!==i.type||i.content.trim().length){if(i&&9===i.type){n.removeNode();const r=Xc(e,t);i.branches.push(r);const s=o&&o(i,r,!1);jc(r,n),s&&s(),n.currentNode=null}break}n.removeNode(i)}}}(e,t,n,((e,t,o)=>{const r=n.parent.children;let s=r.indexOf(e),i=0;for(;s-- >=0;){const e=r[s];e&&9===e.type&&(i+=e.branches.length)}return()=>{if(o)e.codegenNode=Yc(t,i,n);else{(function(e){for(;;)if(19===e.type){if(19!==e.alternate.type)return e;e=e.alternate}else 20===e.type&&(e=e.value)}(e.codegenNode)).alternate=Yc(t,i+e.branches.length-1,n)}}}))));function Xc(e,t){return{type:10,loc:e.loc,condition:"else"===t.name?void 0:t.exp,children:3!==e.tagType||Dl(e,"for")?[e]:e.children,userKey:Wl(e,"key")}}function Yc(e,t,n){return e.condition?Rl(e.condition,ea(e,t,n),El(n.helper(Wi),['""',"true"])):ea(e,t,n)}function ea(e,t,n){const{helper:o}=n,r=kl("key",Tl(`${t}`,!1,Sl,2)),{children:s}=e,i=s[0];if(1!==s.length||1!==i.type){if(1===s.length&&11===i.type){const e=i.codegenNode;return ec(e,r,n),e}{let t=64;return xl(n,o(Oi),wl([r]),s,t+"",void 0,void 0,!0,!1,!1,e.loc)}}{const e=i.codegenNode,t=14===(l=e).type&&l.callee===yl?l.arguments[1].returns:l;return 13===t.type&&nc(t,n),ec(t,r,n),e}var l}const ta=Uc("for",((e,t,n)=>{const{helper:o,removeHelper:r}=n;return function(e,t,n,o){if(!t.exp)return;const r=sa(t.exp);if(!r)return;const{scopes:s}=n,{source:i,value:l,key:c,index:a}=r,u={type:11,loc:t.loc,source:i,valueAlias:l,keyAlias:c,objectIndexAlias:a,parseResult:r,children:ql(e)?e.children:[e]};n.replaceNode(u),s.vFor++;const p=o&&o(u);return()=>{s.vFor--,p&&p()}}(e,t,n,(t=>{const s=El(o(Xi),[t.source]),i=Dl(e,"memo"),l=Wl(e,"key"),c=l&&(6===l.type?Tl(l.value.content,!0):l.exp),a=l?kl("key",c):null,u=4===t.source.type&&t.source.constType>0,p=u?64:l?128:256;return t.codegenNode=xl(n,o(Oi),void 0,s,p+"",void 0,void 0,!0,!u,!1,e.loc),()=>{let l;const p=ql(e),{children:f}=t,d=1!==f.length||1!==f[0].type,h=Jl(e)?e:p&&1===e.children.length&&Jl(e.children[0])?e.children[0]:null;if(h?(l=h.codegenNode,p&&a&&ec(l,a,n)):d?l=xl(n,o(Oi),a?wl([a]):void 0,e.children,"64",void 0,void 0,!0,void 0,!1):(l=f[0].codegenNode,p&&a&&ec(l,a,n),l.isBlock!==!u&&(l.isBlock?(r(Li),r(Ql(n.inSSR,l.isComponent))):r(Zl(n.inSSR,l.isComponent))),l.isBlock=!u,l.isBlock?(o(Li),o(Ql(n.inSSR,l.isComponent))):o(Zl(n.inSSR,l.isComponent))),i){const e=$l(la(t.parseResult,[Tl("_cached")]));e.body={type:21,body:[Nl(["const _memo = (",i.exp,")"]),Nl(["if (_cached",...c?[" && _cached.key === ",c]:[],` && ${n.helperString(bl)}(_cached, _memo)) return _cached`]),Nl(["const _item = ",l]),Tl("_item.memo = _memo"),Tl("return _item")],loc:Sl},s.arguments.push(e,Tl("_cache"),Tl(String(n.cached++)))}else s.arguments.push($l(la(t.parseResult),l,!0))}}))}));const na=/([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/,oa=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/,ra=/^\(|\)$/g;function sa(e,t){const n=e.loc,o=e.content,r=o.match(na);if(!r)return;const[,s,i]=r,l={source:ia(n,i.trim(),o.indexOf(i,s.length)),value:void 0,key:void 0,index:void 0};let c=s.trim().replace(ra,"").trim();const a=s.indexOf(c),u=c.match(oa);if(u){c=c.replace(oa,"").trim();const e=u[1].trim();let t;if(e&&(t=o.indexOf(e,a+c.length),l.key=ia(n,e,t)),u[2]){const r=u[2].trim();r&&(l.index=ia(n,r,o.indexOf(r,l.key?t+e.length:a+c.length)))}}return c&&(l.value=ia(n,c,a)),l}function ia(e,t,n){return Tl(t,!1,jl(e,n,t.length))}function la({value:e,key:t,index:n},o=[]){return function(e){let t=e.length;for(;t--&&!e[t];);return e.slice(0,t+1).map(((e,t)=>e||Tl("_".repeat(t+1),!1)))}([e,t,n,...o])}const ca=Tl("undefined",!1),aa=(e,t)=>{if(1===e.type&&(1===e.tagType||3===e.tagType)){const n=Dl(e,"slot");if(n)return t.scopes.vSlot++,()=>{t.scopes.vSlot--}}},ua=(e,t,n)=>$l(e,t,!1,!0,t.length?t[0].loc:n);function pa(e,t,n=ua){t.helper(ml);const{children:o,loc:r}=e,s=[],i=[];let l=t.scopes.vSlot>0||t.scopes.vFor>0;const c=Dl(e,"slot",!0);if(c){const{arg:e,exp:t}=c;e&&!Fl(e)&&(l=!0),s.push(kl(e||Tl("default",!0),n(t,o,r)))}let a=!1,u=!1;const p=[],f=new Set;for(let m=0;mkl("default",n(e,t,r));a?p.length&&p.some((e=>ha(e)))&&(u||s.push(e(void 0,p))):s.push(e(void 0,o))}const d=l?2:da(e.children)?3:1;let h=wl(s.concat(kl("_",Tl(d+"",!1))),r);return i.length&&(h=El(t.helper(el),[h,Cl(i)])),{slots:h,hasDynamicSlots:l}}function fa(e,t){return wl([kl("name",e),kl("fn",t)])}function da(e){for(let t=0;tfunction(){if(1!==(e=t.currentNode).type||0!==e.tagType&&1!==e.tagType)return;const{tag:n,props:o}=e,r=1===e.tagType;let s=r?function(e,t,n=!1){let{tag:o}=e;const r=_a(o),s=Wl(e,"is");if(s)if(r){const e=6===s.type?s.value&&Tl(s.value.content,!0):s.exp;if(e)return El(t.helper(qi),[e])}else 6===s.type&&s.value.content.startsWith("vue:")&&(o=s.value.content.slice(4));const i=!r&&Dl(e,"is");if(i&&i.exp)return El(t.helper(qi),[i.exp]);const l=Ml(o)||t.isBuiltInComponent(o);if(l)return n||t.helper(l),l;return t.helper(Gi),t.components.add(o),tc(o,"component")}(e,t):`"${n}"`;let i,l,c,a,u,p,f=0,d=O(s)&&s.callee===qi||s===Pi||s===Ii||!r&&("svg"===n||"foreignObject"===n||Wl(e,"key",!0));if(o.length>0){const n=va(e,t);i=n.props,f=n.patchFlag,u=n.dynamicPropNames;const o=n.directives;p=o&&o.length?Cl(o.map((e=>function(e,t){const n=[],o=ma.get(e);o?n.push(t.helperString(o)):(t.helper(Ji),t.directives.add(e.name),n.push(tc(e.name,"directive")));const{loc:r}=e;e.exp&&n.push(e.exp);e.arg&&(e.exp||n.push("void 0"),n.push(e.arg));if(Object.keys(e.modifiers).length){e.arg||(e.exp||n.push("void 0"),n.push("void 0"));const t=Tl("true",!1,r);n.push(wl(e.modifiers.map((e=>kl(e,t))),r))}return Cl(n,e.loc)}(e,t)))):void 0}if(e.children.length>0){s===Vi&&(d=!0,f|=1024);if(r&&s!==Pi&&s!==Vi){const{slots:n,hasDynamicSlots:o}=pa(e,t);l=n,o&&(f|=1024)}else if(1===e.children.length&&s!==Pi){const n=e.children[0],o=n.type,r=5===o||8===o;r&&0===Ac(n,t)&&(f|=1),l=r||2===o?n:e.children}else l=e.children}0!==f&&(c=String(f),u&&u.length&&(a=function(e){let t="[";for(let n=0,o=e.length;n{if(Fl(e)){const o=e.content,r=S(o);if(i||!r||"onclick"===o.toLowerCase()||"onUpdate:modelValue"===o||j(o)||(h=!0),r&&j(o)&&(g=!0),20===n.type||(4===n.type||8===n.type)&&Ac(n,t)>0)return;"ref"===o?p=!0:"class"===o?f=!0:"style"===o?d=!0:"key"===o||v.includes(o)||v.push(o),!i||"class"!==o&&"style"!==o||v.includes(o)||v.push(o)}else m=!0};for(let _=0;_1?El(t.helper(nl),c,s):c[0]):l.length&&(b=wl(ya(l),s)),m?u|=16:(f&&!i&&(u|=2),d&&!i&&(u|=4),v.length&&(u|=8),h&&(u|=32)),0!==u&&32!==u||!(p||g||a.length>0)||(u|=512),!t.inSSR&&b)switch(b.type){case 15:let e=-1,n=-1,o=!1;for(let t=0;t{if(Jl(e)){const{children:n,loc:o}=e,{slotName:r,slotProps:s}=function(e,t){let n,o='"default"';const r=[];for(let s=0;s0){const{props:o,directives:s}=va(e,t,r);n=o}return{slotName:o,slotProps:n}}(e,t),i=[t.prefixIdentifiers?"_ctx.$slots":"$slots",r];s&&i.push(s),n.length&&(s||i.push("{}"),i.push($l([],n,!1,!1,o))),t.scopeId&&!t.slotted&&(s||i.push("{}"),n.length||i.push("undefined"),i.push("true")),e.codegenNode=El(t.helper(Yi),i,o)}};const xa=/^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/,Ca=(e,t,n,o)=>{const{loc:r,modifiers:s,arg:i}=e;let l;if(4===i.type)if(i.isStatic){l=Tl(G(D(i.content)),!0,i.loc)}else l=Nl([`${n.helperString(ul)}(`,i,")"]);else l=i,l.children.unshift(`${n.helperString(ul)}(`),l.children.push(")");let c=e.exp;c&&!c.content.trim()&&(c=void 0);let a=n.cacheHandlers&&!c&&!n.inVOnce;if(c){const e=Ll(c.content),t=!(e||xa.test(c.content)),n=c.content.includes(";");(t||a&&e)&&(c=Nl([`${t?"$event":"(...args)"} => ${n?"{":"("}`,c,n?"}":")"]))}let u={props:[kl(l,c||Tl("() => {}",!1,r))]};return o&&(u=o(u)),a&&(u.props[0].value=n.cache(u.props[0].value)),u.props.forEach((e=>e.key.isHandlerKey=!0)),u},wa=(e,t,n)=>{const{exp:o,modifiers:r,loc:s}=e,i=e.arg;return 4!==i.type?(i.children.unshift("("),i.children.push(') || ""')):i.isStatic||(i.content=`${i.content} || ""`),r.includes("camel")&&(4===i.type?i.content=i.isStatic?D(i.content):`${n.helperString(cl)}(${i.content})`:(i.children.unshift(`${n.helperString(cl)}(`),i.children.push(")"))),n.inSSR||(r.includes("prop")&&ka(i,"."),r.includes("attr")&&ka(i,"^")),!o||4===o.type&&!o.content.trim()?{props:[kl(i,Tl("",!0,s))]}:{props:[kl(i,o)]}},ka=(e,t)=>{4===e.type?e.content=e.isStatic?t+e.content:`\`${t}\${${e.content}}\``:(e.children.unshift(`'${t}' + (`),e.children.push(")"))},Ta=(e,t)=>{if(0===e.type||1===e.type||11===e.type||10===e.type)return()=>{const n=e.children;let o,r=!1;for(let e=0;e7===e.type&&!t.directiveTransforms[e.name])))))for(let e=0;e{if(1===e.type&&Dl(e,"once",!0)){if(Na.has(e)||t.inVOnce)return;return Na.add(e),t.inVOnce=!0,t.helper(pl),()=>{t.inVOnce=!1;const e=t.currentNode;e.codegenNode&&(e.codegenNode=t.cache(e.codegenNode,!0))}}},$a=(e,t,n)=>{const{exp:o,arg:r}=e;if(!o)return Ra();const s=o.loc.source,i=4===o.type?o.content:s;if(!i.trim()||!Ll(i))return Ra();const l=r||Tl("modelValue",!0),c=r?Fl(r)?`onUpdate:${r.content}`:Nl(['"onUpdate:" + ',r]):"onUpdate:modelValue";let a;a=Nl([`${n.isTS?"($event: any)":"$event"} => (`,o," = $event)"]);const u=[kl(l,e.exp),kl(c,a)];if(e.modifiers.length&&1===t.tagType){const t=e.modifiers.map((e=>(Pl(e)?e:JSON.stringify(e))+": true")).join(", "),n=r?Fl(r)?`${r.content}Modifiers`:Nl([r,' + "Modifiers"']):"modelModifiers";u.push(kl(n,Tl(`{ ${t} }`,!1,e.loc,2)))}return Ra(u)};function Ra(e=[]){return{props:e}}const Fa=new WeakSet,Aa=(e,t)=>{if(1===e.type){const n=Dl(e,"memo");if(!n||Fa.has(e))return;return Fa.add(e),()=>{const o=e.codegenNode||t.currentNode.codegenNode;o&&13===o.type&&(1!==e.tagType&&nc(o,t),e.codegenNode=El(t.helper(yl),[n.exp,$l(void 0,o),"_cache",String(t.cached++)]))}}};function Ma(e,t={}){const n=t.onError||Fi,o="module"===t.mode;!0===t.prefixIdentifiers?n(Mi(45)):o&&n(Mi(46));t.cacheHandlers&&n(Mi(47)),t.scopeId&&!o&&n(Mi(48));const r=A(e)?ic(e,t):e,[s,i]=[[Ea,Qc,Aa,ta,Sa,ga,aa,Ta],{on:Ca,bind:wa,model:$a}];return Lc(r,C({},t,{prefixIdentifiers:false,nodeTransforms:[...s,...t.nodeTransforms||[]],directiveTransforms:C({},i,t.directiveTransforms||{})})),Dc(r,C({},t,{prefixIdentifiers:false}))}const Oa=Symbol(""),Pa=Symbol(""),Ia=Symbol(""),Va=Symbol(""),Ba=Symbol(""),La=Symbol(""),ja=Symbol(""),Ua=Symbol(""),Ha=Symbol(""),Da=Symbol("");var Wa;let za;Wa={[Oa]:"vModelRadio",[Pa]:"vModelCheckbox",[Ia]:"vModelText",[Va]:"vModelSelect",[Ba]:"vModelDynamic",[La]:"withModifiers",[ja]:"withKeys",[Ua]:"vShow",[Ha]:"Transition",[Da]:"TransitionGroup"},Object.getOwnPropertySymbols(Wa).forEach((e=>{_l[e]=Wa[e]}));const Ka=t("style,iframe,script,noscript",!0),Ga={isVoidTag:f,isNativeTag:e=>u(e)||p(e),isPreTag:e=>"pre"===e,decodeEntities:function(e,t=!1){return za||(za=document.createElement("div")),t?(za.innerHTML=`
`,za.children[0].getAttribute("foo")):(za.innerHTML=e,za.textContent)},isBuiltInComponent:e=>Al(e,"Transition")?Ha:Al(e,"TransitionGroup")?Da:void 0,getNamespace(e,t){let n=t?t.ns:0;if(t&&2===n)if("annotation-xml"===t.tag){if("svg"===e)return 1;t.props.some((e=>6===e.type&&"encoding"===e.name&&null!=e.value&&("text/html"===e.value.content||"application/xhtml+xml"===e.value.content)))&&(n=0)}else/^m(?:[ions]|text)$/.test(t.tag)&&"mglyph"!==e&&"malignmark"!==e&&(n=0);else t&&1===n&&("foreignObject"!==t.tag&&"desc"!==t.tag&&"title"!==t.tag||(n=0));if(0===n){if("svg"===e)return 1;if("math"===e)return 2}return n},getTextMode({tag:e,ns:t}){if(0===t){if("textarea"===e||"title"===e)return 1;if(Ka(e))return 2}return 0}},qa=(e,t)=>{const n=c(e);return Tl(JSON.stringify(n),!1,t,3)};const Ja=t("passive,once,capture"),Za=t("stop,prevent,self,ctrl,shift,alt,meta,exact,middle"),Qa=t("left,right"),Xa=t("onkeyup,onkeydown,onkeypress",!0),Ya=(e,t)=>Fl(e)&&"onclick"===e.content.toLowerCase()?Tl(t,!0):4!==e.type?Nl(["(",e,`) === "onClick" ? "${t}" : (`,e,")"]):e,eu=(e,t)=>{1!==e.type||0!==e.tagType||"script"!==e.tag&&"style"!==e.tag||t.removeNode()},tu=[e=>{1===e.type&&e.props.forEach(((t,n)=>{6===t.type&&"style"===t.name&&t.value&&(e.props[n]={type:7,name:"bind",arg:Tl("style",!0,t.loc),exp:qa(t.value.content,t.loc),modifiers:[],loc:t.loc})}))}],nu={cloak:()=>({props:[]}),html:(e,t,n)=>{const{exp:o,loc:r}=e;return t.children.length&&(t.children.length=0),{props:[kl(Tl("innerHTML",!0,r),o||Tl("",!0))]}},text:(e,t,n)=>{const{exp:o,loc:r}=e;return t.children.length&&(t.children.length=0),{props:[kl(Tl("textContent",!0),o?El(n.helperString(tl),[o],r):Tl("",!0))]}},model:(e,t,n)=>{const o=$a(e,t,n);if(!o.props.length||1===t.tagType)return o;const{tag:r}=t,s=n.isCustomElement(r);if("input"===r||"textarea"===r||"select"===r||s){let e=Ia,i=!1;if("input"===r||s){const n=Wl(t,"type");if(n){if(7===n.type)e=Ba;else if(n.value)switch(n.value.content){case"radio":e=Oa;break;case"checkbox":e=Pa;break;case"file":i=!0}}else(function(e){return e.props.some((e=>!(7!==e.type||"bind"!==e.name||e.arg&&4===e.arg.type&&e.arg.isStatic)))})(t)&&(e=Ba)}else"select"===r&&(e=Va);i||(o.needRuntime=n.helper(e))}return o.props=o.props.filter((e=>!(4===e.key.type&&"modelValue"===e.key.content))),o},on:(e,t,n)=>Ca(e,0,n,(t=>{const{modifiers:o}=e;if(!o.length)return t;let{key:r,value:s}=t.props[0];const{keyModifiers:i,nonKeyModifiers:l,eventOptionModifiers:c}=((e,t,n,o)=>{const r=[],s=[],i=[];for(let l=0;l({props:[],needRuntime:n.helper(Ua)})};const ou=Object.create(null);function ru(e,t){if(!A(e)){if(!e.nodeType)return y;e=e.innerHTML}const n=e,o=ou[n];if(o)return o;if("#"===e[0]){const t=document.querySelector(e);e=t?t.innerHTML:""}const{code:r}=function(e,t={}){return Ma(e,C({},Ga,t,{nodeTransforms:[eu,...tu,...t.nodeTransforms||[]],directiveTransforms:C({},nu,t.directiveTransforms||{}),transformHoist:null}))}(e,C({hoistStatic:!0,onError:void 0,onWarn:y},t)),s=new Function(r)();return s._rc=!0,ou[n]=s}return br(ru),e.BaseTransition=sn,e.Comment=Mo,e.EffectScope=ee,e.Fragment=Fo,e.KeepAlive=vn,e.ReactiveEffect=fe,e.Static=Oo,e.Suspense=Jt,e.Teleport=To,e.Text=Ao,e.Transition=Vs,e.TransitionGroup=ti,e.VueElement=As,e.callWithAsyncErrorHandling=Fr,e.callWithErrorHandling=Rr,e.camelize=D,e.capitalize=K,e.cloneVNode=Qo,e.compatUtils=null,e.compile=ru,e.computed=Pt,e.createApp=(...e)=>{const t=Ti().createApp(...e),{mount:n}=t;return t.mount=e=>{const o=Ri(e);if(!o)return;const r=t._component;F(r)||r.render||r.template||(r.template=o.innerHTML),o.innerHTML="";const s=n(o,!1,o instanceof SVGElement);return o instanceof Element&&(o.removeAttribute("v-cloak"),o.setAttribute("data-v-app","")),s},t},e.createBlock=Ho,e.createCommentVNode=function(e="",t=!1){return t?(Vo(),Ho(Mo,null,e)):Jo(Mo,null,e)},e.createElementBlock=function(e,t,n,o,r,s){return Uo(qo(e,t,n,o,r,s,!0))},e.createElementVNode=qo,e.createHydrationRenderer=vo,e.createRenderer=go,e.createSSRApp=(...e)=>{const t=Ni().createApp(...e),{mount:n}=t;return t.mount=e=>{const t=Ri(e);if(t)return n(t,!0,t instanceof SVGElement)},t},e.createSlots=function(e,t){for(let n=0;n{let e;return a||(e=a=t().catch((e=>{if(e=e instanceof Error?e:new Error(String(e)),l)return new Promise(((t,n)=>{l(e,(()=>t((u++,a=null,p()))),(()=>n(e)),u+1)}));throw e})).then((t=>e!==a&&a?a:(t&&(t.__esModule||"Module"===t[Symbol.toStringTag])&&(t=t.default),c=t,t))))};return dn({name:"AsyncComponentWrapper",__asyncLoader:p,get __asyncResolved(){return c},setup(){const e=ur;if(c)return()=>mn(c,e);const t=t=>{a=null,Ar(t,e,13,!o)};if(i&&e.suspense)return p().then((t=>()=>mn(t,e))).catch((e=>(t(e),()=>o?Jo(o,{error:e}):null)));const l=kt(!1),u=kt(),f=kt(!!r);return r&&setTimeout((()=>{f.value=!1}),r),null!=s&&setTimeout((()=>{if(!l.value&&!u.value){const e=new Error(`Async component timed out after ${s}ms.`);t(e),u.value=e}}),s),p().then((()=>{l.value=!0,e.parent&&gn(e.parent.vnode)&&Gr(e.parent.update)})).catch((e=>{t(e),u.value=e})),()=>l.value&&c?mn(c,e):u.value&&o?Jo(o,{error:u.value}):n&&!f.value?Jo(n):void 0}})},e.defineComponent=dn,e.defineCustomElement=Rs,e.defineEmits=function(){return null},e.defineExpose=function(e){},e.defineProps=function(){return null},e.defineSSRCustomElement=e=>Rs(e,$i),e.effect=function(e,t){e.effect&&(e=e.effect.fn);const n=new fe(e);t&&(C(n,t),t.scope&&te(n,t.scope)),t&&t.lazy||n.run();const o=n.run.bind(n);return o.effect=n,o},e.effectScope=function(e){return new ee(e)},e.getCurrentInstance=pr,e.getCurrentScope=function(){return X},e.getTransitionRawChildren=fn,e.guardReactiveProps=Zo,e.h=as,e.handleError=Ar,e.hydrate=$i,e.initCustomFormatter=function(){},e.inject=nn,e.isMemoSame=ps,e.isProxy=yt,e.isReactive=gt,e.isReadonly=vt,e.isRef=wt,e.isRuntimeOnly=()=>!mr,e.isVNode=Do,e.markRaw=_t,e.mergeDefaults=function(e,t){for(const n in t){const o=e[n];o?o.default=t[n]:null===o&&(e[n]={default:t[n]})}return e},e.mergeProps=nr,e.nextTick=Kr,e.normalizeClass=a,e.normalizeProps=function(e){if(!e)return null;let{class:t,style:n}=e;return t&&!A(t)&&(e.class=a(t)),n&&(e.style=s(n)),e},e.normalizeStyle=s,e.onActivated=bn,e.onBeforeMount=Nn,e.onBeforeUnmount=Fn,e.onBeforeUpdate=$n,e.onDeactivated=_n,e.onErrorCaptured=In,e.onMounted=En,e.onRenderTracked=Pn,e.onRenderTriggered=On,e.onScopeDispose=function(e){X&&X.cleanups.push(e)},e.onServerPrefetch=Mn,e.onUnmounted=An,e.onUpdated=Rn,e.openBlock=Vo,e.popScopeId=function(){jt=null},e.provide=tn,e.proxyRefs=Rt,e.pushScopeId=function(e){jt=e},e.queuePostFlushCb=Zr,e.reactive=ft,e.readonly=ht,e.ref=kt,e.registerRuntimeCompiler=br,e.render=Ei,e.renderList=function(e,t,n,o){let r;const s=n&&n[o];if(N(e)||A(e)){r=new Array(e.length);for(let n=0,o=e.length;nt(e,n,void 0,s&&s[n])));else{const n=Object.keys(e);r=new Array(n.length);for(let o=0,i=n.length;onull==e?"":N(e)||O(e)&&(e.toString===I||!F(e.toString))?JSON.stringify(e,m,2):String(e),e.toHandlerKey=G,e.toHandlers=function(e){const t={};for(const n in e)t[G(n)]=e[n];return t},e.toRaw=bt,e.toRef=Mt,e.toRefs=function(e){const t=N(e)?new Array(e.length):{};for(const n in e)t[n]=Mt(e,n);return t},e.transformVNodeArgs=function(e){},e.triggerRef=function(e){xt(e)},e.unref=Et,e.useAttrs=function(){return cs().attrs},e.useCssModule=function(e="$style"){return g},e.useCssVars=function(e){const t=pr();if(!t)return;const n=()=>Ms(t.subTree,e(t.proxy));ts(n),En((()=>{const e=new MutationObserver(n);e.observe(t.subTree.el.parentNode,{childList:!0}),An((()=>e.disconnect()))}))},e.useSSRContext=()=>{},e.useSlots=function(){return cs().slots},e.useTransitionState=on,e.vModelCheckbox=ai,e.vModelDynamic=gi,e.vModelRadio=pi,e.vModelSelect=fi,e.vModelText=ci,e.vShow=Si,e.version=fs,e.warn=Nr,e.watch=os,e.watchEffect=function(e,t){return rs(e,null,t)},e.watchPostEffect=ts,e.watchSyncEffect=function(e,t){return rs(e,null,{flush:"sync"})},e.withAsyncContext=function(e){const t=pr();let n=e();return dr(),P(n)&&(n=n.catch((e=>{throw fr(t),e}))),[n,()=>fr(t)]},e.withCtx=Ht,e.withDefaults=function(e,t){return null},e.withDirectives=function(e,t){if(null===Lt)return e;const n=Lt.proxy,o=e.dirs||(e.dirs=[]);for(let r=0;rn=>{if(!("key"in n))return;const o=z(n.key);return t.some((e=>e===o||_i[e]===o))?e(n):void 0},e.withMemo=function(e,t,n,o){const r=n[o];if(r&&ps(r,e))return r;const s=t();return s.memo=e.slice(),n[o]=s},e.withModifiers=(e,t)=>(n,...o)=>{for(let e=0;eHt,Object.defineProperty(e,"__esModule",{value:!0}),e}({}); diff --git a/sd_feed/newtype_v3/__init__.py b/sd_feed/newtype_v3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sd_feed/newtype_v3/__pycache__/__init__.cpython-310.pyc b/sd_feed/newtype_v3/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..932c687b29fc5bf99ff5342a079278948c22a0d2 Binary files /dev/null and b/sd_feed/newtype_v3/__pycache__/__init__.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/__pycache__/images.cpython-310.pyc b/sd_feed/newtype_v3/__pycache__/images.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..932cf9b20b636d0df57b42c2e5a33c723bd95d84 Binary files /dev/null and b/sd_feed/newtype_v3/__pycache__/images.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/__pycache__/locs.cpython-310.pyc b/sd_feed/newtype_v3/__pycache__/locs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2dbececee23760de433d5218e780e4c03aa9ae2f Binary files /dev/null and b/sd_feed/newtype_v3/__pycache__/locs.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/__pycache__/lora.cpython-310.pyc b/sd_feed/newtype_v3/__pycache__/lora.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ba92dde6284cf579e0efd19e69aa952407eba21 Binary files /dev/null and b/sd_feed/newtype_v3/__pycache__/lora.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/__pycache__/lora_types.cpython-310.pyc b/sd_feed/newtype_v3/__pycache__/lora_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41844583c10e748aee5a35809b255d1900967b10 Binary files /dev/null and b/sd_feed/newtype_v3/__pycache__/lora_types.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/__pycache__/newtype_v3.cpython-310.pyc b/sd_feed/newtype_v3/__pycache__/newtype_v3.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c0888b4d955d0cebeee1b7a39c03b922f9c944a Binary files /dev/null and b/sd_feed/newtype_v3/__pycache__/newtype_v3.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/__pycache__/users.cpython-310.pyc b/sd_feed/newtype_v3/__pycache__/users.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bd27939e53549eb2b6e2d6d36d2c6f14eff899d Binary files /dev/null and b/sd_feed/newtype_v3/__pycache__/users.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/images.py b/sd_feed/newtype_v3/images.py new file mode 100644 index 0000000000000000000000000000000000000000..13e1acf4cbdf05341e22d3cf30b98d1aa7eac297 --- /dev/null +++ b/sd_feed/newtype_v3/images.py @@ -0,0 +1,279 @@ +import json +import os +from typing import Dict, List, Optional +import re +import base64 +from io import BytesIO +from tempfile import _TemporaryFileWrapper +import traceback + +from modules.images import read_info_from_image +from newtype_v3.users import create_user +from newtype_v3.utils.string_utils import return_string_dict +from newtype_v3.locs import DEFAULT_LOC + +from PIL import Image +from modules.processing import StableDiffusionProcessing +import requests + + +def dumper(obj): + try: + return obj.toJSON() + except Exception: + try: + return obj.__dict__ + except Exception: + return str(obj) + + +def create_image(img: Image, user_id: str, process: StableDiffusionProcessing, info: Optional[str] = None, token: str = ''): + try: + if info: + data_dict = return_string_dict(info) + else: + applied_to_hires = ( + getattr(process, 'applied_old_hires_behavior_to') + if hasattr(process, 'applied_old_hires_behavior_to') + else None + ) + enable_hr = ( + getattr(process, 'enable_hr') + if hasattr(process, 'enable_hr') + else None + ) + + data_dict = { + 'all_negative_prompts': process.all_negative_prompts, + 'all_prompts': process.all_prompts, + 'all_seeds': process.all_seeds, + 'all_subseeds': process.all_subseeds, + 'applied_old_hires_behavior_to': applied_to_hires, + 'batch_size': process.batch_size, + 'cfg_scale': process.cfg_scale, + 'color_corrections': process.color_corrections, + 'ddim_discretize': process.ddim_discretize, + 'denoising_strength': process.denoising_strength, + 'disable_extra_networks': process.disable_extra_networks, + 'do_not_reload_embeddings': process.do_not_reload_embeddings, + 'do_not_save_grid': process.do_not_save_grid, + 'do_not_save_samples': process.do_not_save_samples, + 'enable_hr': enable_hr, + 'eta': process.eta, + 'extra_generation_params': process.extra_generation_params, + 'height': process.height, + 'iteration': process.iteration, + 'n_iter': process.n_iter, + 'negative_prompt': process.negative_prompt, + 'outpath_grids': process.outpath_grids, + 'outpath_samples': process.outpath_samples, + 'overlay_images': process.overlay_images, + 'override_settings': process.override_settings, + 'override_settings_restore_afterwards': + process.override_settings_restore_afterwards, + 'process': process.paste_to, + 'prompt': process.prompt, + 'prompt_for_display': process.prompt_for_display, + 'restore_faces': process.restore_faces, + 's_churn': process.s_churn, + 's_noise': process.s_noise, + 's_tmax': process.s_tmax, + 's_tmin': process.s_tmin, + 'sampler_name': process.sampler_name, + 'sampler_noise_scheduler_override': + process.sampler_noise_scheduler_override, + 'script_args': process.script_args, + 'scripts': [x.title() for x in process.scripts.scripts], + 'sd_model': process.sd_model.sd_checkpoint_info.title, + 'seed': process.seed, + 'seed_resize_from_h': process.seed_resize_from_h, + 'seed_resize_from_w': process.seed_resize_from_w, + 'steps': process.steps, + 'styles': process.styles, + 'subseed': process.subseed, + 'subseed_strength': process.subseed_strength, + } + for row in [ + 'hr_resize_x', + 'hr_resize_y', + 'hr_scale', + 'hr_second_pass_steps', + 'hr_upscale_to_x', + 'hr_upscale_to_y', + 'hr_upscaler', + 'tiling', + 'truncate_x', + 'truncate_y', + 'width' + ]: + value = ( + getattr(process, row) + if hasattr(process, row) + else None + ) + data_dict[row] = value + img.save(f'{DEFAULT_LOC}/temp.png', "PNG", optimize=True) + img.seek(0) + _ = requests.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/image', + data={ + 'userId': user_id, + 'metadata': json.dumps(data_dict, default=dumper) + }, + files={ + 'upload_file': open(f'{DEFAULT_LOC}/temp.png', 'rb') + }, + stream=True, + headers={ + 'Authorization': f'Token {token}' + } + ) + os.remove(f'{DEFAULT_LOC}/temp.png') + except Exception as e: + print(e) + pass + + +def create_image_from_string(img_string: str, user_id: str, token: str = ''): + try: + remove_image = False + if img_string.startswith("http") or img_string.startswith("file="): + file_loc = ( + re.search(r'file=(.*)', img_string).group(1) + .replace("%20", ' ') + ) + img = Image.open(file_loc) + text_info, extra_items = read_info_from_image(img) + data_dict = return_string_dict(text_info) + data_dict.update(extra_items) + else: + file_loc = f'{DEFAULT_LOC}/temp.png' + img_string = img_string.split(",")[1] + img = Image.open(BytesIO(base64.b64decode(img_string))) + img.save(file_loc, "PNG", optimize=True) + img.seek(0) + remove_image = True + + _ = requests.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/image', + data={ + 'userId': user_id, + 'metadata': json.dumps(data_dict, default=dumper) + }, + files={ + 'upload_file': open(file_loc, 'rb') + }, + stream=True, + headers={ + 'Authorization': f'Token {token}' + } + ) + try: + if remove_image: + os.remove(file_loc) + except Exception: + pass + return True + except Exception as e: + print(e, traceback.format_exc()) + return False + + +def create_image_to_image_file( + img_string: str, original_img_string: str, user_id: str, + token: str = '' +): + try: + remove_image = False + if img_string.startswith("http") or img_string.startswith("file="): + file_loc = ( + re.search(r'file=(.*)', img_string).group(1) + .replace("%20", ' ') + ) + img = Image.open(file_loc) + text_info, extra_items = read_info_from_image(img) + data_dict = return_string_dict(text_info) + data_dict.update(extra_items) + else: + file_loc = f'{DEFAULT_LOC}/temp.png' + img_string = img_string.split(",")[1] + img = Image.open(BytesIO(base64.b64decode(img_string))) + img.save(file_loc, "PNG", optimize=True) + img.seek(0) + remove_image = True + origin_loc = f'{DEFAULT_LOC}/temp2.png' + original_img_string = original_img_string.split(',')[1] + img = Image.open(BytesIO(base64.b64decode(original_img_string))) + img.save(origin_loc, "PNG", optimize=True) + _ = requests.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/image', + data={ + 'userId': user_id, + 'metadata': json.dumps(data_dict, default=dumper) + }, + files={ + 'upload_file': open(file_loc, 'rb'), + 'img_to_img_file': open(origin_loc, 'rb') + }, + stream=True, + headers={ + 'Authorization': f'Token {token}' + } + ) + try: + if remove_image: + os.remove(file_loc) + os.remove(origin_loc) + except Exception: + pass + return True + except Exception as e: + print('Image to image save error', e) + return False + + +def create_image_from_img(img: Image, user_id: str, data_dict: Dict, token: str = ''): + try: + file_loc = f'{DEFAULT_LOC}/temp.png' + img.save(file_loc, "PNG", optimize=True) + img.seek(0) + _ = requests.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/image/image', + data={ + 'userId': user_id, + 'metadata': json.dumps(data_dict, default=dumper) + }, + files={ + 'upload_file': open(file_loc, 'rb') + }, + stream=True, + headers={ + 'Authorization': f'Token {token}' + } + ) + os.remove(file_loc) + except Exception as e: + print(e) + pass + + +def create_multiple_file_uploads( + data: List[_TemporaryFileWrapper] +): + user_dict = create_user() + user_id = user_dict.get('userId') + for d in data: + try: + image = Image.open(BytesIO(d)) + textinfo, items = read_info_from_image(image) + if textinfo is not None: + data = return_string_dict(textinfo) + data.update(items) + else: + data = {} + create_image_from_img(image, user_id, data) + except Exception as e: + print(e) + pass + return [] + diff --git a/sd_feed/newtype_v3/locs.py b/sd_feed/newtype_v3/locs.py new file mode 100644 index 0000000000000000000000000000000000000000..7a546f4814ced53d3f86813ed0a11f90d74a27a7 --- /dev/null +++ b/sd_feed/newtype_v3/locs.py @@ -0,0 +1,10 @@ +import os + + +is_exists = os.path.exists('/content/repository/extensions-builtin') +is_exists_seconds = os.path.exists('/content/drive/MyDrive/SD/extensions/sd_feed/javascript') +SD_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +if is_exists and is_exists_seconds: + DEFAULT_LOC = '/content/drive/MyDrive/SD/extensions/sd_feed' +else: + DEFAULT_LOC = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) diff --git a/sd_feed/newtype_v3/lora.py b/sd_feed/newtype_v3/lora.py new file mode 100644 index 0000000000000000000000000000000000000000..467de4db528d6382619e147a562073fd0475e5d5 --- /dev/null +++ b/sd_feed/newtype_v3/lora.py @@ -0,0 +1,32 @@ +import re +import traceback +from typing import List, Dict +import requests +from newtype_v3.users import create_user_headers + + +def lora_string_list(prompt: str) -> List[str]: + data_list = [] + for x in re.findall(r'\', prompt): + data_list.append(x.split(':')[1]) + return data_list + + +def search_lora_list(lora_list: List[str]) -> List[Dict]: + try: + headers, user_dict = create_user_headers() + result_list = requests.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/lora/loras', + json={ + 'loraList': lora_list, + 'userId': user_dict.get("userId") + }, + headers=headers + ) + result = result_list.json() + if type(result) is list: + return result + raise ValueError(result) + except Exception as e: + print(e, traceback.format_exc()) + return False \ No newline at end of file diff --git a/sd_feed/newtype_v3/lora_types.py b/sd_feed/newtype_v3/lora_types.py new file mode 100644 index 0000000000000000000000000000000000000000..a0bf6fc014bfde039634d0615866367ac597ced0 --- /dev/null +++ b/sd_feed/newtype_v3/lora_types.py @@ -0,0 +1,7 @@ + + +SIMILAR: str = "SIMILAR" +SAME: str = "SAME" +NOT_FOUND: str = "NOT_FOUND" +ALREADY_EXISTS: str = "ALREADY_EXSITS" + diff --git a/sd_feed/newtype_v3/newtype_v3.py b/sd_feed/newtype_v3/newtype_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..2a7e1841658c326b3c486e0c0d20461d4b65605b --- /dev/null +++ b/sd_feed/newtype_v3/newtype_v3.py @@ -0,0 +1,293 @@ +import logging +from pathlib import Path +from typing import List, Tuple +import requests +import os + +import gradio as gr + +from modules import call_queue +from modules import scripts, script_callbacks +from modules.script_callbacks import ImageSaveParams +from modules import shared + +from newtype_v3.locs import DEFAULT_LOC +from newtype_v3.lora import search_lora_list, lora_string_list +from . import lora_types +from .users import create_user, create_user_headers +from .images import ( + create_image, create_image_from_string, create_image_to_image_file +) + + +logger = logging.getLogger(__name__) + +loaded_count = 0 + +base_dir = Path(scripts.basedir()) +all_btns: List[Tuple[gr.Button, ...]] = [] +share_image = False + + +def search_lora(prompt: str) -> List[str]: + if type(prompt) is not str: + prompt = prompt[0] + search_list = lora_string_list(prompt) + try: + list_of_dict = search_lora_list(search_list) + except Exception: + list_of_dict = [] + fname_list = os.listdir(shared.cmd_opts.lora_dir) + fname_text_list = [ + x.replace(".safetensors", '').replace('.ckpt', '').replace(".pt", '') + for x in fname_list + ] + searched_list = [ + x.get('fileName').replace(".safetensors", '').replace('.ckpt', '').replace(".pt", '') + for x in list_of_dict + ] + not_found_list = [{ + 'fileName': x, + 'downloadUrl': '', + 'status': lora_types.NOT_FOUND + } for x in search_list + if x.replace(".safetensor", '').replace('.ckpt', '').replace(".pt", '') + not in fname_text_list + and + x not in searched_list + ] + list_of_dict = list(filter(lambda x: x.get('fileName') not in fname_list, list_of_dict)) + list_of_dict = [ + { + 'fileName': x.get('fileName'), 'downloadUrl': x.get('downloadUrl'), + 'status': lora_types.SAME, + } + for x in list_of_dict + ] + return list_of_dict + not_found_list + + +def set_share_image(x): + global share_image + share_image = x + + +def save_files(image_file: str, outer_html) -> List[str]: + user_dict = create_user() + userId = user_dict.get('userId') + result = create_image_from_string( + image_file, + userId, + ) + result_string = "Success" if result else "Failed" + return [ + result_string + ] + + +def download_lora(link, fname): + # Code to handle file download + response = requests.get(link) + with open(f'{shared.cmd_opts.lora_dir}/{fname}', 'wb') as f: + f.write(response.content) + try: + headers, user_dict = create_user_headers() + _ = requests.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/lora/download', + json={ + 'userId': user_dict.get("userId") + }, + headers=headers + ) + except Exception: + pass + return ["Success"] + + +def save_imgto_img_file( + image_file: str, original_img_string: str, outer_html: str +): + user_dict = create_user() + userId = user_dict.get('userId') + token = user_dict.get('token', '') + result = create_image_to_image_file( + image_file, + original_img_string, + userId, + token=token + ) + result_string = "Success" if result else "Failed" + return [result_string] + + +def register_png_posturl() -> None: + def on_img_save_url(image_save_params: ImageSaveParams) -> None: + try: + global share_image + if share_image: + user_dict = create_user() + userId = user_dict.get('userId') + create_image( + image_save_params.image, + userId, + image_save_params.p, + info=image_save_params.pnginfo.get("parameters") if image_save_params.pnginfo else None, + token=user_dict.get('token', ''), + ) + except Exception: + logger.exception("Error save data") + script_callbacks.on_image_saved(on_img_save_url) + + +class Script(scripts.Script): + def __init__(self): + global loaded_count + + loaded_count += 1 + + # This is a hack to make sure that the script is only loaded once + # Auto1111 calls the script twice, once for the txt2img and once for + # img2img + # These callbacks should only be registered once. + + # When the Reload UI button in the settings tab is pressed, the script + # is loaded twice again + # Therefore we only register callbacks every second time the script is + # loaded + if loaded_count % 2 == 0: + return + register_png_posturl() + + def title(self): + return "Feed" + + def show(self, is_img2img): + return scripts.AlwaysVisible + + def process( + self, + p, + *args, + **kwargs + ): + return p + + def after_component(self, component, **kwargs): + if isinstance(component, gr.HTML): + if component.elem_id in {'html_info_txt2img'}: + with open(f'{DEFAULT_LOC}/html/potd.html', encoding='utf-8') as f: + gr.HTML( + f.read(), + elem_id="best-product-tab", + ) + + if component.elem_id in {'txt2img_override_settings'}: + with gr.Accordion('Lora Downloads', open=True): + with gr.Column(): + with gr.Row(): + lora_save = gr.Button( + 'Search Lora', elem_id='lora_search_button' + ) + # JS에서 브라우저에있는데이터를 save_files함수로 전송 + js_string = """(a)=>{ + const container = gradioApp().querySelector('#txt2img_prompt'); + const textArea = container.getElementsByTagName("textarea")[0]; + return [textArea.value]; + }""" + txtArea = gr.TextArea( + '', + elem_id="table-data", + visible=False + ) + lora_download = gr.Button( + '', elem_id='lora_download_btn', + visible=False + ) + download_results = gr.Textbox( + "", + label="", + visible=True + ) + with open(f'{DEFAULT_LOC}/html/lora.html', encoding='utf-8') as f: + gr.HTML(f.read(), elem_id="lora-elem") + lora_save.click( + fn=call_queue.wrap_gradio_call(search_lora), + _js=js_string, + inputs=[lora_save], + outputs=txtArea, + show_progress=True, + ) + download_js_string = """(a)=>{ + const container = gradioApp().querySelector('#lora-download-url'); + const lorafname = gradioApp().querySelector('#lora-filename'); + return [container.value, lorafname.value]; + }""" + lora_download.click( + fn=call_queue.wrap_gradio_call(download_lora), + _js=download_js_string, + inputs=[lora_download, lora_download], + outputs=[download_results], + show_progress=True, + ) + + if isinstance(component, gr.Gallery): + if component.elem_id in {'txt2img_gallery'}: + with gr.Accordion('Feed Settings', open=True): + with gr.Column(): + with gr.Row(): + save = gr.Button( + 'Share', elem_id='save_txt2_image' + ) + with open(f'{DEFAULT_LOC}/html/profile.html', encoding='utf-8') as f: + gr.HTML(f.read(), elem_id="feed-profile-tab") + # JS에서 브라우저에있는데이터를 save_files함수로 전송 + js_string = """(a)=>{ + const el = gradioApp().querySelector('#txt2img_gallery'); + const imgList = el.getElementsByTagName('img'); + const htmlInfoTxtImg = gradioApp().querySelector('#html_info_txt2img'); + return [imgList[0]['src'], htmlInfoTxtImg.outerHTML]; + }""" + txt_to_txt_result = gr.Textbox( + "", + label="", + visible=True + ) + save.click( + fn=call_queue.wrap_gradio_call(save_files), + _js=js_string, + inputs=[save, save], + outputs=[txt_to_txt_result], + show_progress=True, + ) + if component.elem_id in {'img2img_gallery'}: + with gr.Accordion('Feed Settings', open=True): + with gr.Column(): + save = gr.Button('Share', elem_id='save_img2_image') + img_to_img_result = gr.Textbox( + "", + label="", + visible=True + ) + # JS에서 브라우저에있는데이터를 save_files함수로 전송 + js_string = """(a)=>{ + const el = gradioApp().querySelector('#img2img_gallery'); + const elOrigin = gradioApp().querySelector("#img2img_image"); + const imgList = el.getElementsByTagName('img'); + const originImgList = elOrigin.getElementsByTagName('img'); + const htmlInfoTxtImg = gradioApp().querySelector('#html_info_img2img'); + return [imgList[0]['src'], originImgList[0]['src'], htmlInfoTxtImg.outerHTML]; + }""" + save.click( + fn=call_queue.wrap_gradio_call( + save_imgto_img_file + ), + _js=js_string, + inputs=[save, save, save], + outputs=[ + img_to_img_result + ], + show_progress=True, + ) + + def ui(self, is_img2img): + return [] diff --git a/sd_feed/newtype_v3/tabs/__init__.py b/sd_feed/newtype_v3/tabs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..819b14f7f78e784a4475acfb2f81a5b646c166fb --- /dev/null +++ b/sd_feed/newtype_v3/tabs/__init__.py @@ -0,0 +1,6 @@ +from . import feed + + +__all__ = [ + feed, +] \ No newline at end of file diff --git a/sd_feed/newtype_v3/tabs/__pycache__/__init__.cpython-310.pyc b/sd_feed/newtype_v3/tabs/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa1ff678df1306eef586c5f3e41e64234299318b Binary files /dev/null and b/sd_feed/newtype_v3/tabs/__pycache__/__init__.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/tabs/__pycache__/feed.cpython-310.pyc b/sd_feed/newtype_v3/tabs/__pycache__/feed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60ec15ea09579bc8c798decbbe7dffbd5100d4ad Binary files /dev/null and b/sd_feed/newtype_v3/tabs/__pycache__/feed.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/tabs/feed.py b/sd_feed/newtype_v3/tabs/feed.py new file mode 100644 index 0000000000000000000000000000000000000000..532c6d392134f6cc663c9ec5ba7b3c1452ef0ca3 --- /dev/null +++ b/sd_feed/newtype_v3/tabs/feed.py @@ -0,0 +1,26 @@ +import gradio as gr + +from newtype_v3.users import create_user +from newtype_v3.locs import DEFAULT_LOC + + +def on_ui_tabs(): + user_dict = create_user() + userId = user_dict.get("userId") + token = user_dict.get("token") + script_html = f""" + + + """ + iframe_html = ( + f"""""" + ) + with gr.Blocks() as newtype_tab: + with gr.Group(elem_id="dynamic-prompting"): + with gr.Row(): + with gr.Column(): + gr.HTML(iframe_html, elem_id="html_id") + with open(f'{DEFAULT_LOC}/html/feedtab.html', encoding='utf-8') as f: + gr.HTML(f.read(), elem_id="vue-elem") + return (newtype_tab, "Feed", "newtype_tab"), diff --git a/sd_feed/newtype_v3/users.py b/sd_feed/newtype_v3/users.py new file mode 100644 index 0000000000000000000000000000000000000000..96ed317d2dffc1c47545ffacc943aa2cc413c78b --- /dev/null +++ b/sd_feed/newtype_v3/users.py @@ -0,0 +1,48 @@ +import json +from typing import Dict, Tuple +import uuid +import requests +from newtype_v3.locs import DEFAULT_LOC + +def create_user() -> Dict: + try: + with open(f'{DEFAULT_LOC}/user.json') as f: + user_dict = json.load(f) + user_id = user_dict.get('userId') + if not user_dict.get("token"): + post_dict = { + 'userId': user_id, + 'useAuth': True, + } + response = requests.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/user/user', + json=post_dict + ) + token = response.json().get('token') + user_dict['token'] = token + with open(f'{DEFAULT_LOC}/user.json', 'w') as f: + json.dump(user_dict, f, sort_keys=True, indent=4) + return user_dict + except Exception: + userId = str(uuid.uuid4()) + user_dict = { + 'userId': userId, + 'useAuth': True, + } + response = requests.post( + 'https://newtypev3-server-vjiloyvjvq-an.a.run.app/user/user', + json=user_dict + ) + token = response.json().get('token') + user_dict['token'] = token + with open(f'{DEFAULT_LOC}/user.json', 'w') as f: + json.dump(user_dict, f, sort_keys=True, indent=4) + return user_dict + + +def create_user_headers() -> Tuple[Dict, Dict]: + user_dict = create_user() + headers = { + "Authorization": f"Token {user_dict['token']}", + } + return headers, user_dict \ No newline at end of file diff --git a/sd_feed/newtype_v3/utils/__init__.py b/sd_feed/newtype_v3/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sd_feed/newtype_v3/utils/__pycache__/__init__.cpython-310.pyc b/sd_feed/newtype_v3/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27a31e629ad7b0a5f76c041d7d47989ef8acc6e9 Binary files /dev/null and b/sd_feed/newtype_v3/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/utils/__pycache__/string_utils.cpython-310.pyc b/sd_feed/newtype_v3/utils/__pycache__/string_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec44ead30e50d09d12042e12bd149dc187fa1124 Binary files /dev/null and b/sd_feed/newtype_v3/utils/__pycache__/string_utils.cpython-310.pyc differ diff --git a/sd_feed/newtype_v3/utils/string_utils.py b/sd_feed/newtype_v3/utils/string_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f69b725a48ec2314fb69b839cd8befe1fe5f5649 --- /dev/null +++ b/sd_feed/newtype_v3/utils/string_utils.py @@ -0,0 +1,40 @@ +import re +from typing import Optional, Dict +from copy import deepcopy +from PIL import Image +from modules.generation_parameters_copypaste import parse_generation_parameters + + +def return_file_loc(image_src: str) -> Image: + if image_src.startswith("http") or image_src.startswith("file="): + file_loc = ( + re.search(r'file=(.*)', image_src).group(1) + .replace("%20", ' ') + ) + return Image.open(file_loc) + + +def return_string_dict(image_src: str) -> Dict: + try: + original_data_dict = parse_generation_parameters(image_src) + data_dict = deepcopy(original_data_dict) + for key in original_data_dict.keys(): + if key.lower() == 'model': + data_dict['sd_model'] = data_dict[key] + if key.lower() == 'steps': + data_dict['n_iter'] = data_dict[key] + if key.lower() == 'negative prompt': + data_dict['negative_prompt'] = data_dict[key] + if key.lower() == 'negative prompt': + data_dict['negative_prompt'] = data_dict[key] + if key.lower() == 'cfg scale': + data_dict['cfg_scale'] = data_dict[key] + if key.lower() == 'seed': + data_dict['seed'] = data_dict[key] + if key.lower() == 'prompt': + data_dict['prompt'] = data_dict[key] + if key.lower() == 'sampler': + data_dict['sampler'] = data_dict[key] + return data_dict + except Exception: + return {} diff --git a/sd_feed/requirements.txt b/sd_feed/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8341f535a6dcd8e521a790dfb2515d7d90e5a50d --- /dev/null +++ b/sd_feed/requirements.txt @@ -0,0 +1,2 @@ +browsercookie +bs4 \ No newline at end of file diff --git a/sd_feed/scripts/__pycache__/main.cpython-310.pyc b/sd_feed/scripts/__pycache__/main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c1fd49c1d9e49f8eeb870781850609824668fdc Binary files /dev/null and b/sd_feed/scripts/__pycache__/main.cpython-310.pyc differ diff --git a/sd_feed/scripts/main.py b/sd_feed/scripts/main.py new file mode 100644 index 0000000000000000000000000000000000000000..b4527ec7b56ad177a90f72dbde8949efcd36ab59 --- /dev/null +++ b/sd_feed/scripts/main.py @@ -0,0 +1,22 @@ +import os +from modules import script_callbacks +from newtype_v3.tabs import feed +from newtype_v3.locs import is_exists, is_exists_seconds +from newtype_v3.newtype_v3 import Script +import shutil + +__all__ = ["Script"] +script_callbacks.on_ui_tabs(feed.on_ui_tabs) + + +if is_exists and is_exists_seconds: + shutil.copytree( + '/content/drive/MyDrive/SD/extensions/sd_feed/javascript', + '/content/repository/extensions-builtin/prompt-bracket-checker/javascript', + dirs_exist_ok=True + ) + if not os.path.exists('/content/repository/extensions-builtin/LDSR/style.css'): + shutil.copy( + '/content/drive/MyDrive/SD/extensions/sd_feed/style.css', + '/content/repository/extensions-builtin/LDSR/style.css' + ) \ No newline at end of file diff --git a/sd_feed/style.css b/sd_feed/style.css new file mode 100644 index 0000000000000000000000000000000000000000..01c4cd5d2d047baf5b8adee88a4cecb014e05ef5 --- /dev/null +++ b/sd_feed/style.css @@ -0,0 +1,625 @@ + +body { + min-height: 1000px; +} +#columns { + column-count: 4; + width: 100%; + max-width: 1100px; + margin: 50px auto; + column-gap: 4px; +} +.page-max-width{ + max-width: 1100px !important; + width:100%; +} +.private-upload{ + width:25%; +} +.item-author{ + color:white !important; +} +@media screen and (max-width: 820px){ + .private-upload{ + width:100%; + max-width:420px; + } + #columns { + column-count: 2 !important; + } +} + + + @media screen and (max-width: 750px) { + #columns { column-gap: 0px; } + #columns figure { width: 100%; } + } + .product-heart-button{ + position:absolute; + right:20px; + } + + .product-slider { + position: relative; +} +#columns { + column-count: 4; + overflow: auto; + +} +.filter-selector-tab{ + display:flex; +} +.profile { + max-width: 800px; + margin: 0 auto; + font-family: Arial, sans-serif; + color: #333; +} + +.header { + display: flex; + flex-direction: column; + align-items: center; + padding: 30px; + background-color: #f7f7f7; +} + +.header img { + width: 150px; + height: 150px; + border-radius: 50%; + object-fit: cover; + object-position: center; + margin-bottom: 20px; +} +.header h1 { + font-size: 36px; +} +.rounded-pill{ + border-radius: 50rem; +} +.btn:not(:disabled):not(.disabled) { + cursor: pointer; +} +.px-4 { + padding-right: 1.5rem!important; + padding-left: 1.5rem!important; +} +.border-secondary { + --bs-border-opacity: 1; + border-color: rgba(108,117,125,1)!important; +} +@font-face { + font-family: 'Material Icons'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/s/materialicons/v140/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2) format('woff2'); +} + +.material-icons { + font-family: 'Material Icons'; + font-weight: normal; + font-style: normal; + font-size: 24px; + line-height: 1; + letter-spacing: normal; + text-transform: none; + display: inline-block; + white-space: nowrap; + word-wrap: normal; + direction: ltr; + -webkit-font-feature-settings: 'liga'; + -webkit-font-smoothing: antialiased; +} +.btn { + --bs-btn-padding-x: 0.75rem; + --bs-btn-padding-y: 0.375rem; + --bs-btn-font-family: ; + --bs-btn-font-size: 1rem; + --bs-btn-font-weight: 400; + --bs-btn-line-height: 1.5; + --bs-btn-color: #212529; + --bs-btn-bg: transparent; + --bs-btn-border-width: 1px; + --bs-btn-border-color: transparent; + --bs-btn-border-radius: 0.375rem; + --bs-btn-hover-border-color: transparent; + --bs-btn-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15),0 1px 1px rgba(0, 0, 0, 0.075); + --bs-btn-disabled-opacity: 0.65; + --bs-btn-focus-box-shadow: 0 0 0 0.25rem rgba(var(--bs-btn-focus-shadow-rgb), .5); + display: inline-block; + padding: var(--bs-btn-padding-y) var(--bs-btn-padding-x); + font-family: var(--bs-btn-font-family); + font-size: var(--bs-btn-font-size); + font-weight: var(--bs-btn-font-weight); + line-height: var(--bs-btn-line-height); + color: var(--bs-btn-color); + text-align: center; + text-decoration: none; + vertical-align: middle; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; + border: var(--bs-btn-border-width) solid var(--bs-btn-border-color); + border-radius: var(--bs-btn-border-radius); + background-color: var(--bs-btn-bg); + transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; + display:flex; +} +#feed-profile-tab{ + display:flex; + align-items:center; +} +.feed-tab-header{ + border-bottom:1px solid var(--border-color-primary) +} +.feed-tab-default { + width:100%; + margin-bottom: -1px; + border: 1px solid transparent; + border-color: transparent; + border-bottom: none; + border-top-right-radius: var(--container-radius) !important; + border-top-left-radius: var(--container-radius) !important; + padding: var(--size-1) var(--size-4) !important; + color: var(--body-text-color-subdued) !important; + font-weight: var(--section-header-text-weight) !important; + font-size: var(--section-header-text-size) !important; +} +.selected.feed-tab-default { + border-color: var(--border-color-primary); + background: var(--background-fill-primary); + color: var(--body-text-color) !important; + font-weight:700; + border-bottom:1px solid white; +} +.feed-tab-class{ + display:flex; + justify-content:space-between; + width:70%; +} +.feed-tab-class-search{ + display:flex; + align-items: center; +} + +#best-product-tab{ + background: var(--panel-background-fill); +} +.potd{ + font-weight: var(--section-header-text-weight); + font-size: var(--section-header-text-size); + margin-bottom:5px; +} + +.pinterest-gallery { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + margin: 0 auto; + max-width: 1600px; + padding: 0 8px; +} + +.pinterest-column-gallery { + flex-wrap: wrap; + margin: 0 auto; + max-width: 1600px; + padding: 0 8px; +} + +.pinterest-item { + width: calc(25% - 3px); + margin-bottom: 20px; + box-sizing: border-box; + position: relative; +} +@media screen and (max-width: 1380px){ + .pinterest-item{ + width: calc(50% - 3px) !important; + } +} +.pinterest-column-item{ + width:100%; + margin-bottom: 4px; + box-sizing: border-box; + position: relative; +} +.pinterest-column-item img { + width: 100%; + height: auto; + display: block; +} +.pinterest-item img { + width: 100%; + height: auto; + display: block; + cursor: pointer; + pointer-events: auto; +} +.item-overlay { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 32px; + opacity: 0.8; + background-color: rgba(0, 0, 0, 0.7); + display:flex; + align-items:center; + justify-content: space-between; +} + +.item-overlay p { + color: #FFFFFF !important; + right: 5px; + top:5px; + position: absolute; + font-size: var(--text-md); + font-weight: var(--body-text-weight); + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + max-width:60%; +} +.liked-button-div{ + color: #FFFFFF !important; + font-size: var(--text-md); + font-weight: var(--body-text-weight); + left: 5px; + top:5px; + display: flex; + flex-direction: row; + align-items: center; + padding: 2px 3px; + gap: 4px; + min-width: 42px; + max-width:62px; + height: 20px; + border-radius: 2px; + margin-left:5px; +} +.liked-button-div button{ + color: #FFFFFF !important; +} +.already-liked-div{ + background: linear-gradient(180deg, #3041E0 0%, #9330E0 100%); +} +.not-liked-div{ + background: #4B5057 +} +#prompt-input{ + border: 1px solid #ccc; + border-radius: 5px; + transition: border-color 0.2s ease-in-out; + color: var(--body-text-color) !important; + background: var(--input-background-fill); +} +#prompt-input:focus { + border-color: skyblue; + outline: none; +} +.btn-write-row{ + box-sizing: border-box; + +/* Auto layout */ + +display: flex; +flex-direction: column; +align-items: center; +padding: 0px; +gap: 12px; +border-radius: 5px; + +/* Inside auto layout */ + +flex: none; +order: 0; +flex-grow: 0; +font-size: 14px; + +} +.btn-cancel{ + + width: 66px; + height: 30px; + border: 1px solid white !important; + line-height: 17px !important; + text-align: center !important; + color: #FFFFFF !important; + align-items: center !important; + justify-content: center !important; + margin-right:10px !important; +} +.btn-save{ + color: #4B5057 !important; + background: #888D96 !important; + width: 85px !important; + height: 30px !important; + align-items: center !important; + justify-content: center !important; +} +.promptModal{ + position: fixed; + z-index: 999; + left: 0; + top: 0; + width: 100%; + height: 100%; + overflow: auto; + background: var(--input-background-fill); + overflow:scroll; +} +.prompt-modal-page{ + display:flex; + justify-content: center; + flex-wrap: wrap; +} +.prompt-modal-image{ + max-width: calc(100% - 400px); + margin: auto; + flex-basis: 100%; + background-size: cover; + background-position: center; + display:flex; + height:100vh; + justify-content: center; + align-items:center; + margin-top:0px; +} +.prompt-modal-image img{ + max-width:720px; + max-height:100vh; +} +@media screen and (max-width: 420px) { + .prompt-modal-image{ + margin-bottom: 0px; + height:100%; + max-width:100%; + + } + .prompt-modal-image img{ + height:60vh; + } + .prompt-modal-image img{ + max-width:320px; + } +} +.prompt-modal-sidebar{ + max-width:400px; + flex-basis: 100%; + background-color: rgba(47, 49, 50, 0.8); + color: white; +} +.modal-sidebar-header{ + display: flex; + align-items: center; + justify-content: space-between; + color:white; + font-weight: 400; + font-size: 24.3293px; + padding-top:12px; + padding-bottom:12px; + border: 1px solid #AFB6BD; +} +.modal-like-wrapper{ + min-width:70px; + max-width:100px; + display:flex; + align-items: center; + justify-content: center; +} +.modal-writer{ + font-family: 'Inter'; + font-style: normal; + font-weight: 700 !important; + font-size: 14px !important; + /* identical to box height */ + color: #FFFFFF !important; +} +.modal-writer-time{ + font-weight: 300 !important; + font-size: 14px !important; + /* identical to box height */ + text-align: right; + color: #FFFFFF !important; +} +.modal-writer-type{ + color: white !important; + border: 1px solid white; + border-radius: 5px !important; + background-color: #AFB6BD !important; + resize: none !important; + overflow: hidden !important; + padding: 10px !important; + width: 95% !important; + min-height: 39.35px !important; + transition: height 0.3s ease-in-out !important; + margin: 10px !important; +} +.profile-writer-type{ + border: 1px solid white; + border-radius: 5px !important; + resize: none !important; + overflow: hidden !important; + padding: 10px !important; + width: 95% !important; + min-height: 39.35px !important; + transition: height 0.3s ease-in-out !important; + margin: 10px !important; +} +.write-row-button{ + display:flex; + justify-content: flex-end; + width: 95%; +} +.big-liked-button-div button{ + height: 38.73px; + color: #FFFFFF !important; + left: 5px; + top:5px; + display: flex; + flex-direction: row; + align-items: center; + padding: 2px 3px; + gap: 4px; + width:100%; + border-radius: 4.86585px; +} +.modal-writer-wrapper-exit{ + margin-right:10px !important; +} +.prompt-modal-content { + background-color: white; + margin: 15% auto; + padding: 20px; + border-radius: 5px; + width: 50%; + text-align: center; + position: relative; /* Add position relative */ + color: black; +} +.prompt-modal-close{ + font-size:50px; + color: black !important; +} +.prompt-modal-table{ + margin-top: 20px; + width: 100%; + border-collapse: collapse; + text-align: left; +} + +.prompt-modal-table td, .prompt-modal-table th { + padding: 5px; + border: 1px solid #ccc; + color: black !important; +} +.prompt-send-to{ + display:flex; + justify-content: center; + margin-top:10px; +} +.btn-send-to { + color: white !important; + padding: 14px 20px !important; + border: none !important; + cursor: pointer !important; + margin-bottom:0px !important; + border: 1px solid #AFB6BD !important; + border-radius: 5px !important; +} + +.btn-send-to-img { + right: 20px; + margin-right: 20px !important; +} + +.btn-send-to-text { + margin-right:10px !important; +} +.toggle-btn { + display: inline-block; + position: relative; + width: 50px; + height: 24px; +} +.tag-button-selected{ + background-color: #131313 !important; + color: #FFFFFF !important; +} +.tag-button-unselected{ + color: #888D96 !important; + background-color:#4B5057 !important; +} +.tag-button{ + display: inline-block; + border: none; + padding: 4px 32px !important; + text-align: center !important; + text-decoration: none !important; + display: inline-block !important; + font-size: 16px !important; + border-radius: 4px !important; + transition-duration: 0.4s; + cursor: pointer; + box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2) !important; +} +.toggle-letter { + display: inline-block; + position: absolute; + top: 0; + left: -80px; + width: 80px; + height: 24px; + line-height: 24px; + text-align: center; + font-weight: bold; + font-size: 14px; + color: #333; +} + +.toggle-btn input[type="checkbox"] { + opacity: 0; + width: 0; + height: 0; +} +.slider { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: #ccc; + border-radius: 24px; + transition: .4s; +} +.slider,.slider:before { + position: absolute; + transition: .4s +} +.slider:before { + position: absolute; + content: ""; + height: 16px; + width: 16px; + left: 4px; + bottom: 4px; + background-color: white; + border-radius: 50%; + transition: .4s; +} + +input:checked + .slider { + background-color: green; +} +input:checked + .slider:before { + transform: translateX(26px); +} +.slider.round { + border-radius: 24px; +} + +.slider.round:before { + border-radius: 50%; +} +.redline-text { + border-bottom: 1px solid red; +} +.redline-overlay { + position: absolute; + bottom: 0; + left: 0; + width: 100%; + height: 83px; + pointer-events: none; +} +.redline-section { + position: absolute; + bottom: 0; + height: 2px; + background-color: red; +} \ No newline at end of file diff --git a/sd_feed/user.json b/sd_feed/user.json new file mode 100644 index 0000000000000000000000000000000000000000..e8d9e1b8d121bb080965011cfea7836c7533d4e6 --- /dev/null +++ b/sd_feed/user.json @@ -0,0 +1,5 @@ +{ + "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI4NTBlNDYxZi0yODMwLTRlOGEtOTZkZS1mN2U3ZGIyZjA3MmIifQ.0WyeDuxcyUMrF7Va5eP2Lbd6gpfvMM81J9ugZQ-VT-Q", + "useAuth": true, + "userId": "850e461f-2830-4e8a-96de-f7e7db2f072b" +} \ No newline at end of file diff --git a/stable-diffusion-webui-composable-lora/.gitignore b/stable-diffusion-webui-composable-lora/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b6e47617de110dea7ca47e087ff1347cc2646eda --- /dev/null +++ b/stable-diffusion-webui-composable-lora/.gitignore @@ -0,0 +1,129 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/stable-diffusion-webui-composable-lora/LICENSE b/stable-diffusion-webui-composable-lora/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..89a316444f791f06fb819b7e708698271ac2d91b --- /dev/null +++ b/stable-diffusion-webui-composable-lora/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 opparco + +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. diff --git a/stable-diffusion-webui-composable-lora/README.md b/stable-diffusion-webui-composable-lora/README.md new file mode 100644 index 0000000000000000000000000000000000000000..67c18fec20ed7cb64a6eac7c8661bf96c94fc48c --- /dev/null +++ b/stable-diffusion-webui-composable-lora/README.md @@ -0,0 +1,25 @@ +# Composable LoRA +This extension replaces the built-in LoRA forward procedure. + +## Features +### Compatible with Composable-Diffusion +By associating LoRA's insertion position in the prompt with "AND" syntax, LoRA's scope of influence is limited to a specific subprompt. + +### Eliminate the impact on negative prompts +With the built-in LoRA, negative prompts are always affected by LoRA. This often has a negative impact on the output. +So this extension offers options to eliminate the negative effects. + +## How to use +### Enabled +When checked, Composable LoRA is enabled. + +### Use Lora in uc text model encoder +Enable LoRA for uncondition (negative prompt) text model encoder. +With this disabled, you can expect better output. + +### Use Lora in uc diffusion model +Enable LoRA for uncondition (negative prompt) diffusion model (denoiser). +With this disabled, you can expect better output. + +## compatibilities +--always-batch-cond-uncond must be enabled with --medvram or --lowvram diff --git a/stable-diffusion-webui-composable-lora/__pycache__/composable_lora.cpython-310.pyc b/stable-diffusion-webui-composable-lora/__pycache__/composable_lora.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d16039a45cc744310ab0c866cab239ef2e6966f Binary files /dev/null and b/stable-diffusion-webui-composable-lora/__pycache__/composable_lora.cpython-310.pyc differ diff --git a/stable-diffusion-webui-composable-lora/composable_lora.py b/stable-diffusion-webui-composable-lora/composable_lora.py new file mode 100644 index 0000000000000000000000000000000000000000..6258df18a4e462c9a5e38adf651a92bc10191d95 --- /dev/null +++ b/stable-diffusion-webui-composable-lora/composable_lora.py @@ -0,0 +1,165 @@ +from typing import List, Dict +import re +import torch + +from modules import extra_networks, shared + +re_AND = re.compile(r"\bAND\b") + + +def load_prompt_loras(prompt: str): + prompt_loras.clear() + subprompts = re_AND.split(prompt) + tmp_prompt_loras = [] + for i, subprompt in enumerate(subprompts): + loras = {} + _, extra_network_data = extra_networks.parse_prompt(subprompt) + for params in extra_network_data['lora']: + name = params.items[0] + multiplier = float(params.items[1]) if len(params.items) > 1 else 1.0 + loras[name] = multiplier + + tmp_prompt_loras.append(loras) + prompt_loras.extend(tmp_prompt_loras * num_batches) + + +def reset_counters(): + global text_model_encoder_counter + global diffusion_model_counter + + # reset counter to uc head + text_model_encoder_counter = -1 + diffusion_model_counter = 0 + + +def lora_forward(compvis_module, input, res): + global text_model_encoder_counter + global diffusion_model_counter + + import lora + + if len(lora.loaded_loras) == 0: + return res + + lora_layer_name: str | None = getattr(compvis_module, 'lora_layer_name', None) + if lora_layer_name is None: + return res + + num_loras = len(lora.loaded_loras) + if text_model_encoder_counter == -1: + text_model_encoder_counter = len(prompt_loras) * num_loras + + # print(f"lora.forward lora_layer_name={lora_layer_name} in.shape={input.shape} res.shape={res.shape} num_batches={num_batches} num_prompts={num_prompts}") + + for lora in lora.loaded_loras: + module = lora.modules.get(lora_layer_name, None) + if module is None: + continue + + if shared.opts.lora_apply_to_outputs and res.shape == input.shape: + patch = module.up(module.down(res)) + else: + patch = module.up(module.down(input)) + + alpha = module.alpha / module.up.weight.shape[1] if module.alpha else 1.0 + + num_prompts = len(prompt_loras) + + # print(f"lora.name={lora.name} lora.mul={lora.multiplier} alpha={alpha} pat.shape={patch.shape}") + + if enabled: + if lora_layer_name.startswith("transformer_"): # "transformer_text_model_encoder_" + # + if 0 <= text_model_encoder_counter // num_loras < len(prompt_loras): + # c + loras = prompt_loras[text_model_encoder_counter // num_loras] + multiplier = loras.get(lora.name, 0.0) + if multiplier != 0.0: + # print(f"c #{text_model_encoder_counter // num_loras} lora.name={lora.name} mul={multiplier}") + res += multiplier * alpha * patch + else: + # uc + if opt_uc_text_model_encoder and lora.multiplier != 0.0: + # print(f"uc #{text_model_encoder_counter // num_loras} lora.name={lora.name} lora.mul={lora.multiplier}") + res += lora.multiplier * alpha * patch + + if lora_layer_name.endswith("_11_mlp_fc2"): # last lora_layer_name of text_model_encoder + text_model_encoder_counter += 1 + # c1 c1 c2 c2 .. .. uc uc + if text_model_encoder_counter == (len(prompt_loras) + num_batches) * num_loras: + text_model_encoder_counter = 0 + + elif lora_layer_name.startswith("diffusion_model_"): # "diffusion_model_" + + if res.shape[0] == num_batches * num_prompts + num_batches: + # tensor.shape[1] == uncond.shape[1] + tensor_off = 0 + uncond_off = num_batches * num_prompts + for b in range(num_batches): + # c + for p, loras in enumerate(prompt_loras): + multiplier = loras.get(lora.name, 0.0) + if multiplier != 0.0: + # print(f"tensor #{b}.{p} lora.name={lora.name} mul={multiplier}") + res[tensor_off] += multiplier * alpha * patch[tensor_off] + tensor_off += 1 + + # uc + if opt_uc_diffusion_model and lora.multiplier != 0.0: + # print(f"uncond lora.name={lora.name} lora.mul={lora.multiplier}") + res[uncond_off] += lora.multiplier * alpha * patch[uncond_off] + uncond_off += 1 + else: + # tensor.shape[1] != uncond.shape[1] + cur_num_prompts = res.shape[0] + base = (diffusion_model_counter // cur_num_prompts) // num_loras * cur_num_prompts + if 0 <= base < len(prompt_loras): + # c + for off in range(cur_num_prompts): + loras = prompt_loras[base + off] + multiplier = loras.get(lora.name, 0.0) + if multiplier != 0.0: + # print(f"c #{base + off} lora.name={lora.name} mul={multiplier}", lora_layer_name=lora_layer_name) + res[off] += multiplier * alpha * patch[off] + else: + # uc + if opt_uc_diffusion_model and lora.multiplier != 0.0: + # print(f"uc {lora_layer_name} lora.name={lora.name} lora.mul={lora.multiplier}") + res += lora.multiplier * alpha * patch + + if lora_layer_name.endswith("_11_1_proj_out"): # last lora_layer_name of diffusion_model + diffusion_model_counter += cur_num_prompts + # c1 c2 .. uc + if diffusion_model_counter >= (len(prompt_loras) + num_batches) * num_loras: + diffusion_model_counter = 0 + else: + # default + if lora.multiplier != 0.0: + # print(f"default {lora_layer_name} lora.name={lora.name} lora.mul={lora.multiplier}") + res += lora.multiplier * alpha * patch + else: + # default + if lora.multiplier != 0.0: + # print(f"DEFAULT {lora_layer_name} lora.name={lora.name} lora.mul={lora.multiplier}") + res += lora.multiplier * alpha * patch + + return res + + +def lora_Linear_forward(self, input): + return lora_forward(self, input, torch.nn.Linear_forward_before_lora(self, input)) + + +def lora_Conv2d_forward(self, input): + return lora_forward(self, input, torch.nn.Conv2d_forward_before_lora(self, input)) + + +enabled = False +opt_uc_text_model_encoder = False +opt_uc_diffusion_model = False +verbose = True + +num_batches: int = 0 +prompt_loras: List[Dict[str, float]] = [] +text_model_encoder_counter: int = -1 +diffusion_model_counter: int = 0 diff --git a/stable-diffusion-webui-composable-lora/scripts/__pycache__/composable_lora_script.cpython-310.pyc b/stable-diffusion-webui-composable-lora/scripts/__pycache__/composable_lora_script.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87dddd5d508f28236a54d659474e255b76dc5214 Binary files /dev/null and b/stable-diffusion-webui-composable-lora/scripts/__pycache__/composable_lora_script.cpython-310.pyc differ diff --git a/stable-diffusion-webui-composable-lora/scripts/composable_lora_script.py b/stable-diffusion-webui-composable-lora/scripts/composable_lora_script.py new file mode 100644 index 0000000000000000000000000000000000000000..65ff699fb5d2fa2d47396c4809aa61b0716cc353 --- /dev/null +++ b/stable-diffusion-webui-composable-lora/scripts/composable_lora_script.py @@ -0,0 +1,57 @@ +# +# Composable-Diffusion with Lora +# +import torch +import gradio as gr + +import composable_lora +import modules.scripts as scripts +from modules import script_callbacks +from modules.processing import StableDiffusionProcessing + + +def unload(): + torch.nn.Linear.forward = torch.nn.Linear_forward_before_lora + torch.nn.Conv2d.forward = torch.nn.Conv2d_forward_before_lora + + +if not hasattr(torch.nn, 'Linear_forward_before_lora'): + torch.nn.Linear_forward_before_lora = torch.nn.Linear.forward + +if not hasattr(torch.nn, 'Conv2d_forward_before_lora'): + torch.nn.Conv2d_forward_before_lora = torch.nn.Conv2d.forward + +torch.nn.Linear.forward = composable_lora.lora_Linear_forward +torch.nn.Conv2d.forward = composable_lora.lora_Conv2d_forward + +script_callbacks.on_script_unloaded(unload) + + +class ComposableLoraScript(scripts.Script): + def title(self): + return "Composable Lora" + + def show(self, is_img2img): + return scripts.AlwaysVisible + + def ui(self, is_img2img): + with gr.Group(): + with gr.Accordion("Composable Lora", open=False): + enabled = gr.Checkbox(value=False, label="Enabled") + opt_uc_text_model_encoder = gr.Checkbox(value=False, label="Use Lora in uc text model encoder") + opt_uc_diffusion_model = gr.Checkbox(value=False, label="Use Lora in uc diffusion model") + + return [enabled, opt_uc_text_model_encoder, opt_uc_diffusion_model] + + def process(self, p: StableDiffusionProcessing, enabled: bool, opt_uc_text_model_encoder: bool, opt_uc_diffusion_model: bool): + composable_lora.enabled = enabled + composable_lora.opt_uc_text_model_encoder = opt_uc_text_model_encoder + composable_lora.opt_uc_diffusion_model = opt_uc_diffusion_model + + composable_lora.num_batches = p.batch_size + + prompt = p.all_prompts[0] + composable_lora.load_prompt_loras(prompt) + + def process_batch(self, p: StableDiffusionProcessing, *args, **kwargs): + composable_lora.reset_counters() diff --git a/stable-diffusion-webui-images-browser/.gitignore b/stable-diffusion-webui-images-browser/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f7bc0025490a2cfa74da7d7cdb034e819daea73c --- /dev/null +++ b/stable-diffusion-webui-images-browser/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +path_recorder.txt +__pycache__ +*.json +*.sqlite3 +*.log diff --git a/stable-diffusion-webui-images-browser/README.md b/stable-diffusion-webui-images-browser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c4849f3219ebb94727c36ed1b16d087391829e1f --- /dev/null +++ b/stable-diffusion-webui-images-browser/README.md @@ -0,0 +1,61 @@ +## stable-diffusion-webui-images-browser + +A custom extension for [AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui). + +This is an image browser for browsing past generated pictures, view their generated informations, send that information to txt2img, img2img and others, collect images to your "favorites" folder and delete the images you no longer need. + +## Installation + +The extension can be installed directly from within the **Extensions** tab within the Webui. + +You can also install it manually by running the following command from within the webui directory: + + git clone https://github.com/AlUlkesh/stable-diffusion-webui-images-browser/ extensions/stable-diffusion-webui-images-browser + +and restart your stable-diffusion-webui, then you can see the new tab "Image Browser". + +Please be aware that when scanning a directory for the first time, the png-cache will be built. This can take several minutes, depending on the amount of images. + +## Recent updates +- Image Reward scoring +- Size tooltip for thumbnails +- Optimized images in the thumbnail interface +- Send to ControlNet +- Hidable UI components +- Send to openOutpaint +- Regex search +- Maximum aesthetic_score filter +- Save ranking to EXIF option +- Maintenance tab +- Custom tabs +- Copy/Move to directory +- Keybindings +- Additional sorting and filtering by EXIF data including .txt file information +- Recyle bin option +- Add/Remove from saved directories, via buttons +- New dropdown with subdirs +- Option to not show the images from subdirs +- Refresh button +- Sort order +- View and save favorites with individual folder depth +- Now also supports jpg + +Please also check the [discussions](https://github.com/AlUlkesh/stable-diffusion-webui-images-browser/discussions) for major update information. + +## Keybindings +| Key | Explanation | +|---------|-------------| +| `0-5` | Ranks the current image, with 0 being the last option (None) | +| `F` | Adds the current image to Favorites | +| `R` | Refreshes the image gallery | +| `Delete` | Deletes the current image | +| `Ctrl + Arrow Left` | Goes to the previous page of images | +| `Ctrl + Arrow Right` | Goes to the next page of images | + +(Ctrl can be changed in settings) + +## Credit + +Credit goes to the original maintainer of this extension: https://github.com/yfszzx and to major contributors https://github.com/Klace and https://github.com/EllangoK + +Image Reward: https://github.com/THUDM/ImageReward diff --git a/stable-diffusion-webui-images-browser/install.py b/stable-diffusion-webui-images-browser/install.py new file mode 100644 index 0000000000000000000000000000000000000000..cd16ab2c93b38bab5657aa3b7ed8c14f70628697 --- /dev/null +++ b/stable-diffusion-webui-images-browser/install.py @@ -0,0 +1,9 @@ +import launch +import os + +if not launch.is_installed("send2trash"): + launch.run_pip("install Send2Trash", "Send2Trash requirement for image browser") + +if not launch.is_installed("ImageReward"): + req_IR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "req_IR.txt") + launch.run_pip(f'install -r "{req_IR}" --no-deps image-reward', 'ImageReward requirement for image browser') diff --git a/stable-diffusion-webui-images-browser/javascript/image_browser.js b/stable-diffusion-webui-images-browser/javascript/image_browser.js new file mode 100644 index 0000000000000000000000000000000000000000..dbcb93037b3bc9d04f20c9654fbac171b579c57e --- /dev/null +++ b/stable-diffusion-webui-images-browser/javascript/image_browser.js @@ -0,0 +1,770 @@ +let image_browser_state = "free" +let image_browser_webui_ready = false +let image_browser_started = false +let image_browser_console_log = "" +let image_browser_debug = false +let image_browser_img_show_in_progress = false + +function image_browser_delay(ms){return new Promise(resolve => setTimeout(resolve, ms))} + +onUiLoaded(image_browser_start_it_up) + +async function image_browser_wait_for_webui() { + if (image_browser_debug) console.log("image_browser_wait_for_webui:start") + await image_browser_delay(500) + sd_model = gradioApp().getElementById("setting_sd_model_checkpoint") + if (!sd_model.querySelector(".eta-bar")) { + image_browser_webui_ready = true + image_browser_start() + } else { + // Set timeout for MutationObserver + const startTime = Date.now() + // 40 seconds in milliseconds + const timeout = 40000 + const webuiObserver = new MutationObserver(function(mutationsList) { + if (image_browser_debug) console.log("webuiObserver:start") + let found = false + outerLoop: for (let i = 0; i < mutationsList.length; i++) { + let mutation = mutationsList[i]; + if (mutation.type === "childList") { + for (let j = 0; j < mutation.removedNodes.length; j++) { + let node = mutation.removedNodes[j]; + if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains("eta-bar")) { + found = true + break outerLoop; + } + } + } + } + if (found || (Date.now() - startTime > timeout)) { + image_browser_webui_ready = true + webuiObserver.disconnect() + if (image_browser_debug) console.log("webuiObserver:end") + image_browser_start() + } + }) + webuiObserver.observe(gradioApp(), { childList:true, subtree:true }) + } + if (image_browser_debug) console.log("image_browser_wait_for_webui:end") +} + +async function image_browser_start_it_up() { + if (image_browser_debug) console.log("image_browser_start_it_up:start") + container = gradioApp().getElementById("image_browser_tabs_container") + let controls = container.querySelectorAll('[id*="_control_"]') + controls.forEach(function(control) { + control.style.pointerEvents = "none" + control.style.cursor = "not-allowed" + control.style.opacity = "0.65" + }) + let warnings = container.querySelectorAll('[id*="_warning_box"]') + warnings.forEach(function(warning) { + warning.innerHTML = '

Waiting for webui...' + }) + + image_browser_wait_for_webui() + if (image_browser_debug) console.log("image_browser_start_it_up:end") +} + +async function image_browser_lock(reason) { + if (image_browser_debug) console.log("image_browser_lock:start") + // Wait until lock removed + let i = 0 + while (image_browser_state != "free") { + await image_browser_delay(200) + i = i + 1 + if (i === 150) { + throw new Error("Still locked after 30 seconds. Please Reload UI.") + } + } + // Lock + image_browser_state = reason + if (image_browser_debug) console.log("image_browser_lock:end") +} + +async function image_browser_unlock() { + if (image_browser_debug) console.log("image_browser_unlock:start") + image_browser_state = "free" + if (image_browser_debug) console.log("image_browser_unlock:end") +} + +const image_browser_click_image = async function() { + if (image_browser_debug) console.log("image_browser_click_image:start") + await image_browser_lock("image_browser_click_image") + const tab_base_tag = image_browser_current_tab() + const container = gradioApp().getElementById(tab_base_tag + "_image_browser_container") + let child = this + let index = 0 + while((child = child.previousSibling) != null) { + index = index + 1 + } + const set_btn = container.querySelector(".image_browser_set_index") + let curr_idx + try { + curr_idx = set_btn.getAttribute("img_index") + } catch (e) { + curr_idx = -1 + } + if (curr_idx != index) { + set_btn.setAttribute("img_index", index) + } + await image_browser_unlock() + set_btn.click() + if (image_browser_debug) console.log("image_browser_click_image:end") +} + +async function image_browser_get_current_img(tab_base_tag, img_index, page_index, filenames, turn_page_switch, image_gallery) { + if (image_browser_debug) console.log("image_browser_get_current_img:start") + await image_browser_lock("image_browser_get_current_img") + img_index = gradioApp().getElementById(tab_base_tag + '_image_browser_set_index').getAttribute("img_index") + gradioApp().dispatchEvent(new Event("image_browser_get_current_img")) + await image_browser_unlock() + if (image_browser_debug) console.log("image_browser_get_current_img:end") + return [ + tab_base_tag, + img_index, + page_index, + filenames, + turn_page_switch, + image_gallery + ] +} + +async function image_browser_refresh_current_page_preview() { + if (image_browser_debug) console.log("image_browser_refresh_current_page_preview:start") + await image_browser_delay(200) + const preview_div = gradioApp().querySelector('.preview') + if (preview_div === null) { + if (image_browser_debug) console.log("image_browser_refresh_current_page_preview:end") + return + } + const tab_base_tag = image_browser_current_tab() + const gallery = gradioApp().querySelector(`#${tab_base_tag}_image_browser`) + const set_btn = gallery.querySelector(".image_browser_set_index") + const curr_idx = parseInt(set_btn.getAttribute("img_index")) + // no loading animation, so click immediately + const gallery_items = gallery.querySelectorAll(".thumbnail-item") + const curr_image = gallery_items[curr_idx] + curr_image.click() + if (image_browser_debug) console.log("image_browser_refresh_current_page_preview:end") +} + +async function image_browser_turnpage(tab_base_tag) { + if (image_browser_debug) console.log("image_browser_turnpage:start") + while (!image_browser_started) { + await image_browser_delay(200) + } + const gallery = gradioApp().querySelector(`#${tab_base_tag}_image_browser`) + let clear + try { + clear = gallery.querySelector("button[aria-label='Clear']") + if (clear) { + clear.click() + } + } catch (e) { + console.error(e) + } + if (image_browser_debug) console.log("image_browser_turnpage:end") +} + +const image_browser_get_current_img_handler = (del_img_btn) => { + if (image_browser_debug) console.log("image_browser_get_current_img_handler:start") + // Prevent delete button spam + del_img_btn.style.pointerEvents = "auto" + del_img_btn.style.cursor = "default" + del_img_btn.style.opacity = "1" + if (image_browser_debug) console.log("image_browser_get_current_img_handler:end") +} + +async function image_browser_select_image(tab_base_tag, img_index, select_image) { + if (image_browser_debug) console.log("image_browser_select_image:start") + if (select_image) { + await image_browser_lock("image_browser_select_image") + const del_img_btn = gradioApp().getElementById(tab_base_tag + "_image_browser_del_img_btn") + // Prevent delete button spam + del_img_btn.style.pointerEvents = "none" + del_img_btn.style.cursor = "not-allowed" + del_img_btn.style.opacity = "0.65" + + const gallery = gradioApp().getElementById(tab_base_tag + "_image_browser_gallery") + const gallery_items = gallery.querySelectorAll(".thumbnail-item") + if (img_index >= gallery_items.length || gallery_items.length == 0) { + const refreshBtn = gradioApp().getElementById(tab_base_tag + "_image_browser_renew_page") + refreshBtn.dispatchEvent(new Event("click")) + } else { + const curr_image = gallery_items[img_index] + curr_image.click() + } + await image_browser_unlock() + + // Prevent delete button spam + gradioApp().removeEventListener("image_browser_get_current_img", () => image_browser_get_current_img_handler(del_img_btn)) + gradioApp().addEventListener("image_browser_get_current_img", () => image_browser_get_current_img_handler(del_img_btn)) + } + if (image_browser_debug) console.log("image_browser_select_image:end") +} + +async function image_browser_gototab(tabname) { + if (image_browser_debug) console.log("image_browser_gototab:start") + await image_browser_lock("image_browser_gototab") + + tabNav = gradioApp().querySelector(".tab-nav") + const tabNavChildren = tabNav.children + let tabNavButtonNum + if (typeof tabname === "number") { + let buttonCnt = 0 + for (let i = 0; i < tabNavChildren.length; i++) { + if (tabNavChildren[i].tagName === "BUTTON") { + if (buttonCnt === tabname) { + tabNavButtonNum = i + break + } + buttonCnt++ + } + } + } else { + for (let i = 0; i < tabNavChildren.length; i++) { + if (tabNavChildren[i].tagName === "BUTTON" && tabNavChildren[i].textContent.trim() === tabname) { + tabNavButtonNum = i + break + } + } + } + let tabNavButton = tabNavChildren[tabNavButtonNum] + tabNavButton.click() + + // Wait for click-action to complete + const startTime = Date.now() + // 60 seconds in milliseconds + const timeout = 60000 + + await image_browser_delay(100) + while (!tabNavButton.classList.contains("selected")) { + tabNavButton = tabNavChildren[tabNavButtonNum] + if (Date.now() - startTime > timeout) { + throw new Error("image_browser_gototab: 60 seconds have passed") + } + await image_browser_delay(200) + } + + await image_browser_unlock() + if (image_browser_debug) console.log("image_browser_gototab:end") +} + +async function image_browser_get_image_for_ext(tab_base_tag, image_index) { + if (image_browser_debug) console.log("image_browser_get_image_for_ext:start") + const image_browser_image = gradioApp().querySelectorAll(`#${tab_base_tag}_image_browser_gallery .thumbnail-item`)[image_index] + + const canvas = document.createElement("canvas") + const image = document.createElement("img") + image.src = image_browser_image.querySelector("img").src + + await image.decode() + + canvas.width = image.width + canvas.height = image.height + + canvas.getContext("2d").drawImage(image, 0, 0) + + if (image_browser_debug) console.log("image_browser_get_image_for_ext:end") + return canvas.toDataURL() +} + +function image_browser_openoutpaint_send(tab_base_tag, image_index, image_browser_prompt, image_browser_neg_prompt, name = "WebUI Resource") { + if (image_browser_debug) console.log("image_browser_openoutpaint_send:start") + image_browser_get_image_for_ext(tab_base_tag, image_index) + .then((dataURL) => { + // Send to openOutpaint + openoutpaint_send_image(dataURL, name) + + // Send prompt to openOutpaint + const tab = get_uiCurrentTabContent().id + + const prompt = image_browser_prompt + const negPrompt = image_browser_neg_prompt + openoutpaint.frame.contentWindow.postMessage({ + key: openoutpaint.key, + type: "openoutpaint/set-prompt", + prompt, + negPrompt, + }) + + // Change Tab + image_browser_gototab("openOutpaint") + }) + if (image_browser_debug) console.log("image_browser_openoutpaint_send:end") +} + +async function image_browser_controlnet_send(toTabNum, tab_base_tag, image_index, controlnetNum, controlnetType) { + if (image_browser_debug) console.log("image_browser_controlnet_send:start") + // Logic originally based on github.com/fkunn1326/openpose-editor + const dataURL = await image_browser_get_image_for_ext(tab_base_tag, image_index) + const blob = await (await fetch(dataURL)).blob() + const dt = new DataTransfer() + dt.items.add(new File([blob], "ImageBrowser.png", { type: blob.type })) + const list = dt.files + + await image_browser_gototab(toTabNum) + const current_tabid = image_browser_webui_current_tab() + const current_tab = current_tabid.replace("tab_", "") + const tab_controlnet = gradioApp().getElementById(current_tab + "_controlnet") + let accordion = tab_controlnet.querySelector("#controlnet > .label-wrap > .icon") + if (accordion.style.transform.includes("rotate(90deg)")) { + accordion.click() + // Wait for click-action to complete + const startTime = Date.now() + // 60 seconds in milliseconds + const timeout = 60000 + + await image_browser_delay(100) + while (accordion.style.transform.includes("rotate(90deg)")) { + accordion = tab_controlnet.querySelector("#controlnet > .label-wrap > .icon") + if (Date.now() - startTime > timeout) { + throw new Error("image_browser_controlnet_send/accordion: 60 seconds have passed") + } + await image_browser_delay(200) + } + } + + let inputImage + let inputContainer + if (controlnetType == "single") { + inputImage = gradioApp().getElementById(current_tab + "_controlnet_ControlNet_input_image") + } else { + const tabs = gradioApp().getElementById(current_tab + "_controlnet_tabs") + const tab_num = (parseInt(controlnetNum) + 1).toString() + tab_button = tabs.querySelector(".tab-nav > button:nth-child(" + tab_num + ")") + tab_button.click() + // Wait for click-action to complete + const startTime = Date.now() + // 60 seconds in milliseconds + const timeout = 60000 + + await image_browser_delay(100) + while (!tab_button.classList.contains("selected")) { + tab_button = tabs.querySelector(".tab-nav > button:nth-child(" + tab_num + ")") + if (Date.now() - startTime > timeout) { + throw new Error("image_browser_controlnet_send/tabs: 60 seconds have passed") + } + await image_browser_delay(200) + } + inputImage = gradioApp().getElementById(current_tab + "_controlnet_ControlNet-" + controlnetNum.toString() + "_input_image") + } + try { + inputContainer = inputImage.querySelector('div[data-testid="image"]') + } catch (e) {} + + const input = inputContainer.querySelector("input[type='file']") + + let clear + try { + clear = inputContainer.querySelector("button[aria-label='Clear']") + if (clear) { + clear.click() + } + } catch (e) { + console.error(e) + } + + try { + // Wait for click-action to complete + const startTime = Date.now() + // 60 seconds in milliseconds + const timeout = 60000 + while (clear) { + clear = inputContainer.querySelector("button[aria-label='Clear']") + if (Date.now() - startTime > timeout) { + throw new Error("image_browser_controlnet_send/clear: 60 seconds have passed") + } + await image_browser_delay(200) + } + } catch (e) { + console.error(e) + } + + input.value = "" + input.files = list + const event = new Event("change", { "bubbles": true, "composed": true }) + input.dispatchEvent(event) + if (image_browser_debug) console.log("image_browser_controlnet_send:end") +} + +function image_browser_controlnet_send_txt2img(tab_base_tag, image_index, controlnetNum, controlnetType) { + image_browser_controlnet_send(0, tab_base_tag, image_index, controlnetNum, controlnetType) +} + +function image_browser_controlnet_send_img2img(tab_base_tag, image_index, controlnetNum, controlnetType) { + image_browser_controlnet_send(1, tab_base_tag, image_index, controlnetNum, controlnetType) +} + +function image_browser_class_add(tab_base_tag) { + gradioApp().getElementById(tab_base_tag + '_image_browser').classList.add("image_browser_container") + gradioApp().getElementById(tab_base_tag + '_image_browser_set_index').classList.add("image_browser_set_index") + gradioApp().getElementById(tab_base_tag + '_image_browser_del_img_btn').classList.add("image_browser_del_img_btn") + gradioApp().getElementById(tab_base_tag + '_image_browser_gallery').classList.add("image_browser_gallery") +} + +function btnClickHandler(tab_base_tag, btn) { + if (image_browser_debug) console.log("btnClickHandler:start") + const tabs_box = gradioApp().getElementById("image_browser_tabs_container") + if (!tabs_box.classList.contains(tab_base_tag)) { + gradioApp().getElementById(tab_base_tag + "_image_browser_renew_page").click() + tabs_box.classList.add(tab_base_tag) + } + if (image_browser_debug) console.log("btnClickHandler:end") +} + +function image_browser_init() { + if (image_browser_debug) console.log("image_browser_init:start") + const tab_base_tags = gradioApp().getElementById("image_browser_tab_base_tags_list") + if (tab_base_tags) { + const image_browser_tab_base_tags_list = tab_base_tags.querySelector("textarea").value.split(",") + image_browser_tab_base_tags_list.forEach(function(tab_base_tag) { + image_browser_class_add(tab_base_tag) + }) + + const tab_btns = gradioApp().getElementById("image_browser_tabs_container").querySelector("div").querySelectorAll("button") + tab_btns.forEach(function(btn, i) { + const tab_base_tag = image_browser_tab_base_tags_list[i] + btn.setAttribute("tab_base_tag", tab_base_tag) + btn.removeEventListener('click', () => btnClickHandler(tab_base_tag, btn)) + btn.addEventListener('click', () => btnClickHandler(tab_base_tag, btn)) + }) + //preload + if (gradioApp().getElementById("image_browser_preload").querySelector("input").checked) { + setTimeout(function(){tab_btns[0].click()}, 100) + } + } + image_browser_keydown() + + const image_browser_swipe = gradioApp().getElementById("image_browser_swipe").getElementsByTagName("input")[0] + if (image_browser_swipe.checked) { + image_browser_touch() + } + if (image_browser_debug) console.log("image_browser_init:end") +} + +async function image_browser_wait_for_gallery_btn(tab_base_tag){ + if (image_browser_debug) console.log("image_browser_wait_for_gallery_btn:start") + await image_browser_delay(100) + while (!gradioApp().getElementById(image_browser_current_tab() + "_image_browser_gallery").getElementsByClassName("thumbnail-item")) { + await image_browser_delay(200) + } + if (image_browser_debug) console.log("image_browser_wait_for_gallery_btn:end") +} + +function image_browser_hijack_console_log() { + (function () { + const oldLog = console.log + console.log = function (message) { + const formattedTime = new Date().toISOString().slice(0, -5).replace(/[TZ]/g, ' ').trim().replace(/\s+/g, '-').replace(/:/g, '-') + image_browser_console_log = image_browser_console_log + formattedTime + " " + "image_browser.js: " + message + "\n" + oldLog.apply(console, arguments) + } + })() + image_browser_debug = true +} + +function get_js_logs() { + log_to_py = image_browser_console_log + image_browser_console_log = "" + return log_to_py +} + +function isNumeric(str) { + if (typeof str != "string") return false + return !isNaN(str) && !isNaN(parseFloat(str)) +} + +function image_browser_start() { + if (image_browser_debug) console.log("image_browser_start:start") + image_browser_init() + const mutationObserver = new MutationObserver(function(mutationsList) { + const tab_base_tags = gradioApp().getElementById("image_browser_tab_base_tags_list") + if (tab_base_tags) { + const image_browser_tab_base_tags_list = tab_base_tags.querySelector("textarea").value.split(",") + image_browser_tab_base_tags_list.forEach(function(tab_base_tag) { + image_browser_class_add(tab_base_tag) + const tab_gallery_items = gradioApp().querySelectorAll('#' + tab_base_tag + '_image_browser .thumbnail-item') + + const image_browser_img_info_json = gradioApp().getElementById(tab_base_tag + "_image_browser_img_info").querySelector('[data-testid="textbox"]').value + const image_browser_img_info = JSON.parse(image_browser_img_info_json) + const filenames = Object.keys(image_browser_img_info) + + tab_gallery_items.forEach(function(gallery_item, i) { + gallery_item.removeEventListener('click', image_browser_click_image, true) + gallery_item.addEventListener('click', image_browser_click_image, true) + + const filename = filenames[i] + try { + let x = image_browser_img_info[filename].x + let y = image_browser_img_info[filename].y + if (isNumeric(x) && isNumeric(y)) { + gallery_item.title = x + "x" + y + } + } catch (e) {} + + document.onkeyup = async function(e) { + if (!image_browser_active()) { + if (image_browser_debug) console.log("image_browser_start:end") + return + } + const current_tab = image_browser_current_tab() + image_browser_wait_for_gallery_btn(current_tab).then(() => { + let gallery_btn + gallery_btn = gradioApp().getElementById(current_tab + "_image_browser_gallery").querySelector(".thumbnail-item .selected") + gallery_btn = gallery_btn && gallery_btn.length > 0 ? gallery_btn[0] : null + if (gallery_btn) { + image_browser_click_image.call(gallery_btn) + } + }) + } + }) + + const cls_btn = gradioApp().getElementById(tab_base_tag + '_image_browser_gallery').querySelector("svg") + if (cls_btn) { + cls_btn.removeEventListener('click', () => image_browser_renew_page(tab_base_tag), false) + cls_btn.addEventListener('click', () => image_browser_renew_page(tab_base_tag), false) + } + }) + const debug_level_option = gradioApp().getElementById("image_browser_debug_level_option").querySelector("textarea").value + if ((debug_level_option == 'javascript' || debug_level_option == 'capture') && !image_browser_debug) { + image_browser_hijack_console_log() + } + } + }) + mutationObserver.observe(gradioApp(), { childList:true, subtree:true }) + image_browser_started = true + image_browser_activate_controls() + if (image_browser_debug) console.log("image_browser_start:end") +} + +async function image_browser_activate_controls() { + if (image_browser_debug) console.log("image_browser_activate_controls:start") + await image_browser_delay(500) + container = gradioApp().getElementById("image_browser_tabs_container") + let controls = container.querySelectorAll('[id*="_control_"]') + controls.forEach(function(control) { + control.style.pointerEvents = "auto" + control.style.cursor = "default" + control.style.opacity = "1" + }) + let warnings = container.querySelectorAll('[id*="_warning_box"]') + warnings.forEach(function(warning) { + warning.innerHTML = "

 " + }) + if (image_browser_debug) console.log("image_browser_activate_controls:end") +} + +function image_browser_img_show_progress_update() { + image_browser_img_show_in_progress = false +} + +function image_browser_renew_page(tab_base_tag) { + if (image_browser_debug) console.log("image_browser_renew_page:start") + gradioApp().getElementById(tab_base_tag + '_image_browser_renew_page').click() + if (image_browser_debug) console.log("image_browser_renew_page:end") +} + +function image_browser_current_tab() { + if (image_browser_debug) console.log("image_browser_current_tab:start") + const tabs = gradioApp().getElementById("image_browser_tabs_container").querySelectorAll('[id$="_image_browser_container"]') + const tab_base_tags = gradioApp().getElementById("image_browser_tab_base_tags_list") + const image_browser_tab_base_tags_list = tab_base_tags.querySelector("textarea").value.split(",").sort((a, b) => b.length - a.length) + for (const element of tabs) { + if (element.style.display === "block") { + const id = element.id + const tab_base_tag = image_browser_tab_base_tags_list.find(element => id.startsWith(element)) || null + if (image_browser_debug) console.log("image_browser_current_tab:end") + return tab_base_tag + } + } + if (image_browser_debug) console.log("image_browser_current_tab:end") +} + +function image_browser_webui_current_tab() { + if (image_browser_debug) console.log("image_browser_webui_current_tab:start") + const tabs = gradioApp().getElementById("tabs").querySelectorAll('[id^="tab_"]') + let id + for (const element of tabs) { + if (element.style.display === "block") { + id = element.id + break + } + } + if (image_browser_debug) console.log("image_browser_webui_current_tab:end") + return id +} + +function image_browser_active() { + if (image_browser_debug) console.log("image_browser_active:start") + const ext_active = gradioApp().getElementById("tab_image_browser") + if (image_browser_debug) console.log("image_browser_active:end") + return ext_active && ext_active.style.display !== "none" +} + +async function image_browser_delete_key(tab_base_tag) { + // Wait for img_show to end + const startTime = Date.now() + // 60 seconds in milliseconds + const timeout = 60000 + + await image_browser_delay(100) + while (image_browser_img_show_in_progress) { + if (Date.now() - startTime > timeout) { + throw new Error("image_browser_delete_key: 60 seconds have passed") + } + await image_browser_delay(200) + } + + const deleteBtn = gradioApp().getElementById(tab_base_tag + "_image_browser_del_img_btn") + deleteBtn.dispatchEvent(new Event("click")) +} + +function image_browser_keydown() { + if (image_browser_debug) console.log("image_browser_keydown:start") + gradioApp().addEventListener("keydown", function(event) { + // If we are not on the Image Browser Extension, dont listen for keypresses + if (!image_browser_active()) { + if (image_browser_debug) console.log("image_browser_keydown:end") + return + } + + // If the user is typing in an input field, dont listen for keypresses + let target + if (!event.composed) { // We shouldn't get here as the Shadow DOM is always active, but just in case + target = event.target + } else { + target = event.composedPath()[0] + } + if (!target || target.nodeName === "INPUT" || target.nodeName === "TEXTAREA") { + if (image_browser_debug) console.log("image_browser_keydown:end") + return + } + + const tab_base_tag = image_browser_current_tab() + + // Listens for keypresses 0-5 and updates the corresponding ranking (0 is the last option, None) + if (event.code >= "Digit0" && event.code <= "Digit5") { + const selectedValue = event.code.charAt(event.code.length - 1) + const radioInputs = gradioApp().getElementById(tab_base_tag + "_control_image_browser_ranking").getElementsByTagName("input") + for (const input of radioInputs) { + if (input.value === selectedValue || (selectedValue === '0' && input === radioInputs[radioInputs.length - 1])) { + input.checked = true + input.dispatchEvent(new Event("change")) + break + } + } + } + + const mod_keys = gradioApp().querySelector(`#${tab_base_tag}_image_browser_mod_keys textarea`).value + let modifiers_pressed = false + if (mod_keys.indexOf("C") !== -1 && mod_keys.indexOf("S") !== -1) { + if (event.ctrlKey && event.shiftKey) { + modifiers_pressed = true + } + } else if (mod_keys.indexOf("S") !== -1) { + if (!event.ctrlKey && event.shiftKey) { + modifiers_pressed = true + } + } else { + if (event.ctrlKey && !event.shiftKey) { + modifiers_pressed = true + } + } + + let modifiers_none = false + if (!event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey) { + modifiers_none = true + } + + if (event.code == "KeyF" && modifiers_none) { + if (tab_base_tag == "image_browser_tab_favorites") { + if (image_browser_debug) console.log("image_browser_keydown:end") + return + } + const favoriteBtn = gradioApp().getElementById(tab_base_tag + "_image_browser_favorites_btn") + favoriteBtn.dispatchEvent(new Event("click")) + } + + if (event.code == "KeyR" && modifiers_none) { + const refreshBtn = gradioApp().getElementById(tab_base_tag + "_image_browser_renew_page") + refreshBtn.dispatchEvent(new Event("click")) + } + + if (event.code == "Delete" && modifiers_none) { + image_browser_delete_key(tab_base_tag) + } + + if (event.code == "ArrowLeft" && modifiers_pressed) { + const prevBtn = gradioApp().getElementById(tab_base_tag + "_control_image_browser_prev_page") + prevBtn.dispatchEvent(new Event("click")) + } + + if (event.code == "ArrowLeft" && modifiers_none) { + image_browser_img_show_in_progress = true + const tab_base_tag = image_browser_current_tab() + const set_btn = gradioApp().querySelector(`#${tab_base_tag}_image_browser .image_browser_set_index`) + const curr_idx = parseInt(set_btn.getAttribute("img_index")) + set_btn.setAttribute("img_index", curr_idx - 1) + image_browser_refresh_current_page_preview() + } + + if (event.code == "ArrowRight" && modifiers_pressed) { + const nextBtn = gradioApp().getElementById(tab_base_tag + "_control_image_browser_next_page") + nextBtn.dispatchEvent(new Event("click")) + } + + if (event.code == "ArrowRight" && modifiers_none) { + image_browser_img_show_in_progress = true + const tab_base_tag = image_browser_current_tab() + const set_btn = gradioApp().querySelector(`#${tab_base_tag}_image_browser .image_browser_set_index`) + const curr_idx = parseInt(set_btn.getAttribute("img_index")) + set_btn.setAttribute("img_index", curr_idx + 1) + image_browser_refresh_current_page_preview() + } + }) + if (image_browser_debug) console.log("image_browser_keydown:end") +} + +function image_browser_touch() { + if (image_browser_debug) console.log("image_browser_touch:start") + let touchStartX = 0 + let touchEndX = 0 + gradioApp().addEventListener("touchstart", function(event) { + if (!image_browser_active()) { + if (image_browser_debug) console.log("image_browser_touch:end") + return + } + touchStartX = event.touches[0].clientX; + }) + gradioApp().addEventListener("touchend", function(event) { + if (!image_browser_active()) { + if (image_browser_debug) console.log("image_browser_touch:end") + return + } + touchEndX = event.changedTouches[0].clientX + const touchDiffX = touchStartX - touchEndX + if (touchDiffX > 50) { + const tab_base_tag = image_browser_current_tab() + const set_btn = gradioApp().querySelector(`#${tab_base_tag}_image_browser .image_browser_set_index`) + const curr_idx = parseInt(set_btn.getAttribute("img_index")) + if (curr_idx >= 1) { + set_btn.setAttribute("img_index", curr_idx - 1) + image_browser_refresh_current_page_preview() + } + } else if (touchDiffX < -50) { + const tab_base_tag = image_browser_current_tab() + const gallery = gradioApp().querySelector(`#${tab_base_tag}_image_browser`) + const gallery_items = gallery.querySelectorAll(".thumbnail-item") + const thumbnails = gallery_items.length / 2 + const set_btn = gradioApp().querySelector(`#${tab_base_tag}_image_browser .image_browser_set_index`) + const curr_idx = parseInt(set_btn.getAttribute("img_index")) + if (curr_idx + 1 < thumbnails) { + set_btn.setAttribute("img_index", curr_idx + 1) + image_browser_refresh_current_page_preview() + } + } + }) + if (image_browser_debug) console.log("image_browser_touch:end") +} diff --git a/stable-diffusion-webui-images-browser/req_IR.txt b/stable-diffusion-webui-images-browser/req_IR.txt new file mode 100644 index 0000000000000000000000000000000000000000..81ef8ecc4be54d719bbb8737e50cdb8d538355ee --- /dev/null +++ b/stable-diffusion-webui-images-browser/req_IR.txt @@ -0,0 +1 @@ +fairscale diff --git a/stable-diffusion-webui-images-browser/scripts/__pycache__/image_browser.cpython-310.pyc b/stable-diffusion-webui-images-browser/scripts/__pycache__/image_browser.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2303182f5e1058c9b0ad48b8160e5bf086ff803b Binary files /dev/null and b/stable-diffusion-webui-images-browser/scripts/__pycache__/image_browser.cpython-310.pyc differ diff --git a/stable-diffusion-webui-images-browser/scripts/image_browser.py b/stable-diffusion-webui-images-browser/scripts/image_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..69bacf93e93441964e40e07cf89a65c5e5ee55df --- /dev/null +++ b/stable-diffusion-webui-images-browser/scripts/image_browser.py @@ -0,0 +1,1717 @@ +import gradio as gr +import csv +import importlib +import json +import logging +import math +import os +import platform +import random +import re +import shutil +import stat +import subprocess as sp +import sys +import tempfile +import time +import torch +import traceback +import hashlib +import modules.extras +import modules.images +import modules.ui +from datetime import datetime +from modules import paths, shared, script_callbacks, scripts, images +from modules.shared import opts, cmd_opts +from modules.ui_common import plaintext_to_html +from modules.ui_components import ToolButton, DropdownMulti +from PIL import Image, UnidentifiedImageError +from packaging import version +from pathlib import Path +from typing import List, Tuple +from itertools import chain +from io import StringIO + +try: + from scripts.wib import wib_db +except ModuleNotFoundError: + sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "scripts"))) + from wib import wib_db + +try: + from send2trash import send2trash + send2trash_installed = True +except ImportError: + print("Image Browser: send2trash is not installed. recycle bin cannot be used.") + send2trash_installed = False + +try: + import ImageReward + image_reward_installed = True +except ImportError: + print("Image Browser: ImageReward is not installed, cannot be used.") + image_reward_installed = False + +# Force reload wib_db, as it doesn't get reloaded otherwise, if an extension update is started from webui +importlib.reload(wib_db) + +yappi_do = False + +components_list = ["Sort by", "Filename keyword search", "EXIF keyword search", "Ranking Filter", "Aesthestic Score", "Generation Info", "File Name", "File Time", "Open Folder", "Send to buttons", "Copy to directory", "Gallery Controls Bar", "Ranking Bar", "Delete Bar", "Additional Generation Info"] + +num_of_imgs_per_page = 0 +loads_files_num = 0 +image_ext_list = [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".svg"] +finfo_aes = {} +finfo_image_reward = {} +exif_cache = {} +finfo_exif = {} +aes_cache = {} +image_reward_cache = {} +none_select = "Nothing selected" +refresh_symbol = '\U0001f504' # 🔄 +up_symbol = '\U000025b2' # ▲ +down_symbol = '\U000025bc' # ▼ +caution_symbol = '\U000026a0' # ⚠ +folder_symbol = '\U0001f4c2' # 📂 +current_depth = 0 +init = True +copy_move = ["Move", "Copy"] +copied_moved = ["Moved", "Copied"] +np = "negative_prompt: " +openoutpaint = False +controlnet = False +js_dummy_return = None +log_file = os.path.join(scripts.basedir(), "image_browser.log") +image_reward_model = None + +def check_image_browser_active_tabs(): + # Check if Maintenance tab has been added to settings in addition to as a mandatory tab. If so, remove. + if hasattr(opts, "image_browser_active_tabs"): + active_tabs_no_maint = re.sub(r",\s*Maintenance", "", opts.image_browser_active_tabs) + if len(active_tabs_no_maint) != len(opts.image_browser_active_tabs): + shared.opts.__setattr__("image_browser_active_tabs", active_tabs_no_maint) + shared.opts.save(shared.config_filename) + +favorite_tab_name = "Favorites" +default_tab_options = ["txt2img", "img2img", "txt2img-grids", "img2img-grids", "Extras", favorite_tab_name, "Others"] +check_image_browser_active_tabs() +tabs_list = [tab.strip() for tab in chain.from_iterable(csv.reader(StringIO(opts.image_browser_active_tabs))) if tab] if hasattr(opts, "image_browser_active_tabs") else default_tab_options +try: + if opts.image_browser_enable_maint: + tabs_list.append("Maintenance") # mandatory tab +except AttributeError: + tabs_list.append("Maintenance") # mandatory tab + +path_maps = { + "txt2img": opts.outdir_samples or opts.outdir_txt2img_samples, + "img2img": opts.outdir_samples or opts.outdir_img2img_samples, + "txt2img-grids": opts.outdir_grids or opts.outdir_txt2img_grids, + "img2img-grids": opts.outdir_grids or opts.outdir_img2img_grids, + "Extras": opts.outdir_samples or opts.outdir_extras_samples, + favorite_tab_name: opts.outdir_save +} + +class ImageBrowserTab(): + + seen_base_tags = set() + + def __init__(self, name: str): + self.name: str = os.path.basename(name) if os.path.isdir(name) else name + self.path: str = os.path.realpath(path_maps.get(name, name)) + self.base_tag: str = f"image_browser_tab_{self.get_unique_base_tag(self.remove_invalid_html_tag_chars(self.name).lower())}" + + def remove_invalid_html_tag_chars(self, tag: str) -> str: + # Removes any character that is not a letter, a digit, a hyphen, or an underscore + removed = re.sub(r'[^a-zA-Z0-9\-_]', '', tag) + return removed + + def get_unique_base_tag(self, base_tag: str) -> str: + counter = 1 + while base_tag in self.seen_base_tags: + match = re.search(r'_(\d+)$', base_tag) + if match: + counter = int(match.group(1)) + 1 + base_tag = re.sub(r'_(\d+)$', f"_{counter}", base_tag) + else: + base_tag = f"{base_tag}_{counter}" + counter += 1 + self.seen_base_tags.add(base_tag) + return base_tag + + def __str__(self): + return f"Name: {self.name} / Path: {self.path} / Base tag: {self.base_tag} / Seen base tags: {self.seen_base_tags}" + +tabs_list = [ImageBrowserTab(tab) for tab in tabs_list] + +debug_level_types = ["none", "warning log", "debug log", "javascript log", "capture logs to file"] + +debug_levels_list = [] +for i in range(len(debug_level_types)): + level = debug_level_types[i].split(" ")[0] + text = str(i) + " - " + debug_level_types[i] + debug_levels_list.append((level, text)) + +def debug_levels(arg_value=None, arg_level=None, arg_text=None): + if arg_value is not None: + return arg_value, debug_levels_list[arg_value] + elif arg_level is not None: + for i, (level, text) in enumerate(debug_levels_list): + if level == arg_level: + return i, debug_levels_list[i] + elif arg_text is not None: + for i, (level, text) in enumerate(debug_levels_list): + if text == arg_text: + return i, debug_levels_list[i] + +# Logging +logger = None +def restart_debug(parameter): + global logger + logger = logging.getLogger(__name__) + logger.disabled = False + logger_mode = logging.ERROR + level_value = 0 + capture_level_value = 99 + if hasattr(opts, "image_browser_debug_level"): + warning_level_value, (warning_level, warning_level_text) = debug_levels(arg_level="warning") + debug_level_value, (debug_level, debug_level_text) = debug_levels(arg_level="debug") + capture_level_value, (capture_level, capture_level_text) = debug_levels(arg_level="capture") + level_value, (level, level_text) = debug_levels(arg_text=opts.image_browser_debug_level) + if level_value >= debug_level_value: + logger_mode = logging.DEBUG + elif level_value >= warning_level_value: + logger_mode = logging.WARNING + logger.setLevel(logger_mode) + if (logger.hasHandlers()): + logger.handlers.clear() + console_handler = logging.StreamHandler() + console_handler.setLevel(logger_mode) + formatter = logging.Formatter(f'%(asctime)s image_browser.py: %(message)s', datefmt='%Y-%m-%d-%H:%M:%S') + console_handler.setFormatter(formatter) + logger.addHandler(console_handler) + if level_value >= capture_level_value: + try: + os.unlink(log_file) + except FileNotFoundError: + pass + file_handler = logging.FileHandler(log_file) + file_handler.setLevel(logger_mode) + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) + logger.warning(f"debug_level: {level_value}") + # Debug logging + if logger.getEffectiveLevel() == logging.DEBUG: + if parameter != "startup": + logging.disable(logging.NOTSET) + + logger.debug(f"{sys.executable} {sys.version}") + logger.debug(f"{platform.system()} {platform.version()}") + try: + git = os.environ.get('GIT', "git") + webui_commit_hash = os.popen(f"{git} rev-parse HEAD").read().strip() + sm_hashes = os.popen(f"{git} submodule").read() + sm_hashes_lines = sm_hashes.splitlines() + image_browser_commit_hash = f"image_browser_commit_hash not found: {sm_hashes}" + for sm_hashes_line in sm_hashes_lines: + if "images-browser" in sm_hashes_line.lower(): + image_browser_commit_hash = sm_hashes_line[1:41] + break + except Exception as e: + webui_commit_hash = e + image_browser_commit_hash = e + logger.debug(f"Webui {webui_commit_hash}") + logger.debug(f"Image Browser {image_browser_commit_hash}") + logger.debug(f"Gradio {gr.__version__}") + logger.debug(f"{paths.script_path}") + with open(cmd_opts.ui_config_file, "r") as f: + logger.debug(f.read()) + with open(cmd_opts.ui_settings_file, "r") as f: + logger.debug(f.read()) + logger.debug(os.path.realpath(__file__)) + logger.debug([str(tab) for tab in tabs_list]) + maint_last_msg = "Debug restarted" + + return parameter, maint_last_msg + +restart_debug("startup") + +def delete_recycle(filename): + if opts.image_browser_delete_recycle and send2trash_installed: + send2trash(filename) + else: + file = Path(filename) + file.unlink() + return + +def img_path_subdirs_get(img_path): + subdirs = [] + subdirs.append(none_select) + for item in os.listdir(img_path): + item_path = os.path.join(img_path, item) + if os.path.isdir(item_path): + subdirs.append(item_path) + return gr.update(choices=subdirs) + +def img_path_add_remove(img_dir, path_recorder, add_remove, img_path_depth): + img_dir = os.path.realpath(img_dir) + if add_remove == "add" or (add_remove == "remove" and img_dir in path_recorder): + if add_remove == "add": + path_recorder[img_dir] = { + "depth": int(img_path_depth), + "path_display": f"{img_dir} [{int(img_path_depth)}]" + } + wib_db.update_path_recorder(img_dir, path_recorder[img_dir]["depth"], path_recorder[img_dir]["path_display"]) + else: + del path_recorder[img_dir] + wib_db.delete_path_recorder(img_dir) + path_recorder_formatted = [value.get("path_display") for key, value in path_recorder.items()] + path_recorder_formatted = sorted(path_recorder_formatted, key=lambda x: natural_keys(x.lower())) + + if add_remove == "remove": + selected = path_recorder[list(path_recorder.keys())[0]]["path_display"] + else: + selected = path_recorder[img_dir]["path_display"] + return path_recorder, gr.update(choices=path_recorder_formatted, value=selected) + +def sort_order_flip(turn_page_switch, sort_order): + if sort_order == up_symbol: + sort_order = down_symbol + else: + sort_order = up_symbol + return 1, -turn_page_switch, sort_order + +def read_path_recorder(): + path_recorder = wib_db.load_path_recorder() + path_recorder_formatted = [value.get("path_display") for key, value in path_recorder.items()] + path_recorder_formatted = sorted(path_recorder_formatted, key=lambda x: natural_keys(x.lower())) + path_recorder_unformatted = list(path_recorder.keys()) + path_recorder_unformatted = sorted(path_recorder_unformatted, key=lambda x: natural_keys(x.lower())) + + return path_recorder, path_recorder_formatted, path_recorder_unformatted + +def pure_path(path): + if path == []: + return path, 0 + match = re.search(r" \[(\d+)\]$", path) + if match: + path = path[:match.start()] + depth = int(match.group(1)) + else: + depth = 0 + path = os.path.realpath(path) + return path, depth + +def browser2path(img_path_browser): + img_path, _ = pure_path(img_path_browser) + return img_path + +def totxt(file): + base, _ = os.path.splitext(file) + file_txt = base + '.txt' + + return file_txt + +def tab_select(): + path_recorder, path_recorder_formatted, path_recorder_unformatted = read_path_recorder() + return path_recorder, gr.update(choices=path_recorder_unformatted) + +def js_logs_output(js_log): + logger.debug(f"js_log: {js_log}") + return js_log + +def ranking_filter_settings(page_index, turn_page_switch, ranking_filter): + if ranking_filter == "Min-max": + interactive = True + else: + interactive = False + page_index = 1 + turn_page_switch = -turn_page_switch + return page_index, turn_page_switch, gr.update(interactive=interactive), gr.update(interactive=interactive) + +def reduplicative_file_move(src, dst): + def same_name_file(basename, path): + name, ext = os.path.splitext(basename) + f_list = os.listdir(path) + max_num = 0 + for f in f_list: + if len(f) <= len(basename): + continue + f_ext = f[-len(ext):] if len(ext) > 0 else "" + if f[:len(name)] == name and f_ext == ext: + if f[len(name)] == "(" and f[-len(ext)-1] == ")": + number = f[len(name)+1:-len(ext)-1] + if number.isdigit(): + if int(number) > max_num: + max_num = int(number) + return f"{name}({max_num + 1}){ext}" + name = os.path.basename(src) + save_name = os.path.join(dst, name) + src_txt_exists = False + if opts.image_browser_txt_files: + src_txt = totxt(src) + if os.path.exists(src_txt): + src_txt_exists = True + if not os.path.exists(save_name): + if opts.image_browser_copy_image: + shutil.copy2(src, dst) + if opts.image_browser_txt_files and src_txt_exists: + shutil.copy2(src_txt, dst) + else: + shutil.move(src, dst) + if opts.image_browser_txt_files and src_txt_exists: + shutil.move(src_txt, dst) + else: + name = same_name_file(name, dst) + if opts.image_browser_copy_image: + shutil.copy2(src, os.path.join(dst, name)) + if opts.image_browser_txt_files and src_txt_exists: + shutil.copy2(src_txt, totxt(os.path.join(dst, name))) + else: + shutil.move(src, os.path.join(dst, name)) + if opts.image_browser_txt_files and src_txt_exists: + shutil.move(src_txt, totxt(os.path.join(dst, name))) + +def save_image(file_name, filenames, page_index, turn_page_switch, dest_path): + if file_name is not None and os.path.exists(file_name): + reduplicative_file_move(file_name, dest_path) + message = f"

{copied_moved[opts.image_browser_copy_image]} to {dest_path}
" + if not opts.image_browser_copy_image: + # Force page refresh with checking filenames + filenames = [] + turn_page_switch = -turn_page_switch + else: + message = "
Image not found (may have been already moved)
" + + return message, filenames, page_index, turn_page_switch + +def delete_image(tab_base_tag_box, delete_num, name, filenames, image_index, visible_num, delete_confirm, turn_page_switch, image_page_list): + logger.debug("delete_image") + refresh = False + delete_num = int(delete_num) + image_index = int(image_index) + visible_num = int(visible_num) + image_page_list = json.loads(image_page_list) + new_file_list = [] + new_image_page_list = [] + if name == "": + refresh = True + else: + try: + index_files = list(filenames).index(name) + + index_on_page = image_page_list.index(name) + except ValueError as e: + print(traceback.format_exc(), file=sys.stderr) + # Something went wrong, force a page refresh + refresh = True + if not refresh: + if not delete_confirm: + delete_num = min(visible_num - index_on_page, delete_num) + new_file_list = filenames[:index_files] + filenames[index_files + delete_num:] + new_image_page_list = image_page_list[:index_on_page] + image_page_list[index_on_page + delete_num:] + + for i in range(index_files, index_files + delete_num): + if os.path.exists(filenames[i]): + if opts.image_browser_delete_message: + print(f"Deleting file {filenames[i]}") + delete_recycle(filenames[i]) + visible_num -= 1 + if opts.image_browser_txt_files: + txt_file = totxt(filenames[i]) + if os.path.exists(txt_file): + delete_recycle(txt_file) + else: + print(f"File does not exist {filenames[i]}") + # If we reach this point (which we shouldn't), things are messed up, better force a page refresh + refresh = True + + if refresh: + turn_page_switch = -turn_page_switch + select_image = False + else: + select_image = True + + return new_file_list, 1, turn_page_switch, visible_num, new_image_page_list, select_image, json.dumps(new_image_page_list) + +def traverse_all_files(curr_path, image_list, tab_base_tag_box, img_path_depth) -> List[Tuple[str, os.stat_result, str, int]]: + global current_depth + logger.debug(f"curr_path: {curr_path}") + if curr_path == "": + return image_list + f_list = [(os.path.join(curr_path, entry.name), entry.stat()) for entry in os.scandir(curr_path)] + for f_info in f_list: + fname, fstat = f_info + if os.path.splitext(fname)[1] in image_ext_list: + image_list.append(f_info) + elif stat.S_ISDIR(fstat.st_mode): + if (opts.image_browser_with_subdirs and tab_base_tag_box != "image_browser_tab_others") or (tab_base_tag_box == "image_browser_tab_others" and img_path_depth != 0 and (current_depth < img_path_depth or img_path_depth < 0)): + current_depth = current_depth + 1 + image_list = traverse_all_files(fname, image_list, tab_base_tag_box, img_path_depth) + current_depth = current_depth - 1 + return image_list + +def cache_exif(fileinfos): + global finfo_exif, exif_cache, finfo_aes, aes_cache, finfo_image_reward, image_reward_cache + + if yappi_do: + import yappi + import pandas as pd + yappi.set_clock_type("wall") + yappi.start() + + cache_exif_start = time.time() + new_exif = 0 + new_aes = 0 + conn, cursor = wib_db.transaction_begin() + for fi_info in fileinfos: + if any(fi_info[0].endswith(ext) for ext in image_ext_list): + found_exif = False + found_aes = False + if fi_info[0] in exif_cache: + finfo_exif[fi_info[0]] = exif_cache[fi_info[0]] + found_exif = True + if fi_info[0] in aes_cache: + finfo_aes[fi_info[0]] = aes_cache[fi_info[0]] + found_aes = True + if fi_info[0] in image_reward_cache: + finfo_image_reward[fi_info[0]] = image_reward_cache[fi_info[0]] + if not found_exif or not found_aes: + finfo_exif[fi_info[0]] = "0" + exif_cache[fi_info[0]] = "0" + finfo_aes[fi_info[0]] = "0" + aes_cache[fi_info[0]] = "0" + try: + image = Image.open(fi_info[0]) + (_, allExif, allExif_html) = modules.extras.run_pnginfo(image) + image.close() + except SyntaxError: + allExif = False + logger.warning(f"Extension and content don't match: {fi_info[0]}") + except UnidentifiedImageError as e: + allExif = False + logger.warning(f"UnidentifiedImageError: {e}") + except Image.DecompressionBombError as e: + allExif = False + logger.warning(f"DecompressionBombError: {e}: {fi_info[0]}") + except PermissionError as e: + allExif = False + logger.warning(f"PermissionError: {e}: {fi_info[0]}") + except FileNotFoundError as e: + allExif = False + logger.warning(f"FileNotFoundError: {e}: {fi_info[0]}") + except OSError as e: + if e.errno == 22: + logger.warning(f"Caught OSError with error code 22: {fi_info[0]}") + else: + raise + if allExif: + finfo_exif[fi_info[0]] = allExif + exif_cache[fi_info[0]] = allExif + wib_db.update_exif_data(conn, fi_info[0], allExif) + new_exif = new_exif + 1 + + m = re.search("(?:aesthetic_score:|Score:) (\d+.\d+)", allExif) + if m: + aes_value = m.group(1) + else: + aes_value = "0" + finfo_aes[fi_info[0]] = aes_value + aes_cache[fi_info[0]] = aes_value + wib_db.update_exif_data_by_key(conn, fi_info[0], "aesthetic_score", aes_value) + new_aes = new_aes + 1 + else: + try: + filename = os.path.splitext(fi_info[0])[0] + ".txt" + geninfo = "" + with open(filename) as f: + for line in f: + geninfo += line + finfo_exif[fi_info[0]] = geninfo + exif_cache[fi_info[0]] = geninfo + wib_db.update_exif_data_by_key(conn, fi_info[0], geninfo) + new_exif = new_exif + 1 + + m = re.search("(?:aesthetic_score:|Score:) (\d+.\d+)", geninfo) + if m: + aes_value = m.group(1) + else: + aes_value = "0" + finfo_aes[fi_info[0]] = aes_value + aes_cache[fi_info[0]] = aes_value + wib_db.update_exif_data_by_key(conn, fi_info[0], "aesthetic_score", aes_value) + new_aes = new_aes + 1 + except Exception: + logger.warning(f"cache_exif: No EXIF in image or txt file for {fi_info[0]}") + # Saved with defaults to not scan it again next time + finfo_exif[fi_info[0]] = "0" + exif_cache[fi_info[0]] = "0" + allExif = "0" + wib_db.update_exif_data(conn, fi_info[0], allExif) + new_exif = new_exif + 1 + + aes_value = "0" + finfo_aes[fi_info[0]] = aes_value + aes_cache[fi_info[0]] = aes_value + wib_db.update_exif_data_by_key(conn, fi_info[0], "aesthetic_score", aes_value) + new_aes = new_aes + 1 + wib_db.transaction_end(conn, cursor) + + if yappi_do: + yappi.stop() + pd.set_option('display.float_format', lambda x: '%.6f' % x) + yappi_stats = yappi.get_func_stats().strip_dirs() + data = [(s.name, s.ncall, s.tsub, s.ttot, s.ttot/s.ncall) for s in yappi_stats] + df = pd.DataFrame(data, columns=['name', 'ncall', 'tsub', 'ttot', 'tavg']) + print(df.to_string(index=False)) + yappi.get_thread_stats().print_all() + + cache_exif_end = time.time() + logger.debug(f"cache_exif: {new_exif}/{len(fileinfos)} cache_aes: {new_aes}/{len(fileinfos)} {round(cache_exif_end - cache_exif_start, 1)} seconds") + +def exif_rebuild(maint_wait): + global finfo_exif, exif_cache, finfo_aes, aes_cache, finfo_image_reward, image_reward_cache + if opts.image_browser_scan_exif: + logger.debug("Rebuild start") + exif_dirs = wib_db.get_exif_dirs() + finfo_aes = {} + finfo_image_reward = {} + exif_cache = {} + finfo_exif = {} + aes_cache = {} + image_reward_cache = {} + for key, value in exif_dirs.items(): + if os.path.exists(key): + print(f"Rebuilding {key}") + fileinfos = traverse_all_files(key, [], "", 0) + cache_exif(fileinfos) + logger.debug("Rebuild end") + maint_last_msg = "Rebuild finished" + else: + maint_last_msg = "Exif cache not enabled in settings" + + return maint_wait, maint_last_msg + +def exif_delete_0(maint_wait): + global finfo_exif, exif_cache, finfo_aes, aes_cache + if opts.image_browser_scan_exif: + conn, cursor = wib_db.transaction_begin() + wib_db.delete_exif_0(cursor) + wib_db.transaction_end(conn, cursor) + finfo_aes = {} + finfo_exif = {} + exif_cache = wib_db.load_exif_data(exif_cache) + aes_cache = wib_db.load_aes_data(aes_cache) + maint_last_msg = "Delete finished" + else: + maint_last_msg = "Exif cache not enabled in settings" + + return maint_wait, maint_last_msg + +def exif_update_dirs(maint_update_dirs_from, maint_update_dirs_to, maint_wait): + global exif_cache, aes_cache, image_reward_cache + if maint_update_dirs_from == "": + maint_last_msg = "From is empty" + elif maint_update_dirs_to == "": + maint_last_msg = "To is empty" + else: + maint_update_dirs_from = os.path.realpath(maint_update_dirs_from) + maint_update_dirs_to = os.path.realpath(maint_update_dirs_to) + rows = 0 + conn, cursor = wib_db.transaction_begin() + wib_db.update_path_recorder_mult(cursor, maint_update_dirs_from, maint_update_dirs_to) + rows = rows + cursor.rowcount + wib_db.update_exif_data_mult(cursor, maint_update_dirs_from, maint_update_dirs_to) + rows = rows + cursor.rowcount + wib_db.update_ranking_mult(cursor, maint_update_dirs_from, maint_update_dirs_to) + rows = rows + cursor.rowcount + wib_db.transaction_end(conn, cursor) + if rows == 0: + maint_last_msg = "No rows updated" + else: + maint_last_msg = f"{rows} rows updated. Please reload UI!" + + return maint_wait, maint_last_msg + +def reapply_ranking(path_recorder, maint_wait): + dirs = {} + + for tab in tabs_list: + if os.path.exists(tab.path): + dirs[tab.path] = tab.path + + for key in path_recorder: + if os.path.exists(key): + dirs[key] = key + + conn, cursor = wib_db.transaction_begin() + + # Traverse all known dirs, check if missing rankings are due to moved files + for key in dirs.keys(): + fileinfos = traverse_all_files(key, [], "", 0) + for (file, _) in fileinfos: + # Is there a ranking for this full filepath + ranking_by_file = wib_db.get_ranking_by_file(cursor, file) + if ranking_by_file is None: + name = os.path.basename(file) + (ranking_by_name, alternate_hash) = wib_db.get_ranking_by_name(cursor, name) + # Is there a ranking only for the filename + if ranking_by_name is not None: + hash = wib_db.get_hash(file) + (alternate_file, alternate_ranking) = ranking_by_name + if alternate_ranking is not None: + (alternate_hash,) = alternate_hash + # Does the found filename's file have no hash or the same hash? + if alternate_hash is None or hash == alternate_hash: + if os.path.exists(alternate_file): + # Insert ranking as a copy of the found filename's ranking + wib_db.insert_ranking(cursor, file, alternate_ranking, hash) + else: + # Replace ranking of the found filename + wib_db.replace_ranking(cursor, file, alternate_file, hash) + + wib_db.transaction_end(conn, cursor) + maint_last_msg = "Rankings reapplied" + + return maint_wait, maint_last_msg + +def atof(text): + try: + retval = float(text) + except ValueError: + retval = text + return retval + +def natural_keys(text): + ''' + alist.sort(key=natural_keys) sorts in human order + http://nedbatchelder.com/blog/200712/human_sorting.html + (See Toothy's implementation in the comments) + float regex comes from https://stackoverflow.com/a/12643073/190597 + ''' + return [ atof(c) for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text) ] + +def open_folder(path): + if os.path.exists(path): + # Code from ui_common.py + if not shared.cmd_opts.hide_ui_dir_config: + if platform.system() == "Windows": + os.startfile(path) + elif platform.system() == "Darwin": + sp.Popen(["open", path]) + elif "microsoft-standard-WSL2" in platform.uname().release: + sp.Popen(["wsl-open", path]) + else: + sp.Popen(["xdg-open", path]) + +def check_ext(ext): + found = False + scripts_list = scripts.list_scripts("scripts", ".py") + for scriptfile in scripts_list: + if ext in scriptfile.basedir.lower(): + found = True + break + return found + +def exif_search(needle, haystack, use_regex, case_sensitive): + found = False + if use_regex: + if case_sensitive: + pattern = re.compile(needle, re.DOTALL) + else: + pattern = re.compile(needle, re.DOTALL | re.IGNORECASE) + if pattern.search(haystack) is not None: + found = True + else: + if not case_sensitive: + haystack = haystack.lower() + needle = needle.lower() + if needle in haystack: + found = True + return found + +def get_all_images(dir_name, sort_by, sort_order, keyword, tab_base_tag_box, img_path_depth, ranking_filter, ranking_filter_min, ranking_filter_max, aes_filter_min, aes_filter_max, score_type, exif_keyword, negative_prompt_search, use_regex, case_sensitive): + global current_depth + logger.debug("get_all_images") + current_depth = 0 + fileinfos = traverse_all_files(dir_name, [], tab_base_tag_box, img_path_depth) + keyword = keyword.strip(" ") + + if opts.image_browser_scan_exif: + cache_exif(fileinfos) + + if len(keyword) != 0: + fileinfos = [x for x in fileinfos if keyword.lower() in x[0].lower()] + filenames = [finfo[0] for finfo in fileinfos] + + if opts.image_browser_scan_exif: + conn, cursor = wib_db.transaction_begin() + if len(exif_keyword) != 0: + if use_regex: + regex_error = False + try: + test_re = re.compile(exif_keyword, re.DOTALL) + except re.error as e: + regex_error = True + print(f"Regex error: {e}") + if (use_regex and not regex_error) or not use_regex: + if negative_prompt_search == "Yes": + fileinfos = [x for x in fileinfos if exif_search(exif_keyword, finfo_exif[x[0]], use_regex, case_sensitive)] + else: + result = [] + for file_info in fileinfos: + file_name = file_info[0] + file_exif = finfo_exif[file_name] + file_exif_lc = file_exif.lower() + start_index = file_exif_lc.find(np) + end_index = file_exif.find("\n", start_index) + if negative_prompt_search == "Only": + start_index = start_index + len(np) + sub_string = file_exif[start_index:end_index].strip() + if exif_search(exif_keyword, sub_string, use_regex, case_sensitive): + result.append(file_info) + else: + sub_string = file_exif[start_index:end_index].strip() + file_exif = file_exif.replace(sub_string, "") + + if exif_search(exif_keyword, file_exif, use_regex, case_sensitive): + result.append(file_info) + fileinfos = result + filenames = [finfo[0] for finfo in fileinfos] + wib_db.fill_work_files(cursor, fileinfos) + if len(aes_filter_min) != 0 or len(aes_filter_max) != 0: + try: + aes_filter_min_num = float(aes_filter_min) + except ValueError: + aes_filter_min_num = sys.float_info.min + try: + aes_filter_max_num = float(aes_filter_max) + except ValueError: + aes_filter_max_num = sys.float_info.max + + fileinfos = wib_db.filter_aes(cursor, fileinfos, aes_filter_min_num, aes_filter_max_num, score_type) + filenames = [finfo[0] for finfo in fileinfos] + if ranking_filter != "All": + ranking_filter_min_num = 1 + ranking_filter_max_num = 5 + if ranking_filter == "Min-max": + try: + ranking_filter_min_num = int(ranking_filter_min) + except ValueError: + ranking_filter_min_num = 0 + try: + ranking_filter_max_num = int(ranking_filter_max) + except ValueError: + ranking_filter_max_num = 0 + if ranking_filter_min_num < 1: + ranking_filter_min_num = 1 + if ranking_filter_max_num < 1 or ranking_filter_max_num > 5: + ranking_filter_max_num = 5 + + fileinfos = wib_db.filter_ranking(cursor, fileinfos, ranking_filter, ranking_filter_min_num, ranking_filter_max_num) + filenames = [finfo[0] for finfo in fileinfos] + + wib_db.transaction_end(conn, cursor) + + if sort_by == "date": + if sort_order == up_symbol: + fileinfos = sorted(fileinfos, key=lambda x: x[1].st_mtime) + else: + fileinfos = sorted(fileinfos, key=lambda x: -x[1].st_mtime) + filenames = [finfo[0] for finfo in fileinfos] + elif sort_by == "path name": + if sort_order == up_symbol: + fileinfos = sorted(fileinfos) + else: + fileinfos = sorted(fileinfos, reverse=True) + filenames = [finfo[0] for finfo in fileinfos] + elif sort_by == "random": + random.shuffle(fileinfos) + filenames = [finfo[0] for finfo in fileinfos] + elif sort_by == "ranking": + finfo_ranked = {} + for fi_info in fileinfos: + finfo_ranked[fi_info[0]], _ = get_ranking(fi_info[0]) + if sort_order == up_symbol: + fileinfos = dict(sorted(finfo_ranked.items(), key=lambda x: (x[1], x[0]))) + else: + fileinfos = dict(reversed(sorted(finfo_ranked.items(), key=lambda x: (x[1], x[0])))) + filenames = [finfo for finfo in fileinfos] + else: + sort_values = {} + exif_info = dict(finfo_exif) + if exif_info: + for k, v in exif_info.items(): + match = re.search(r'(?<='+ sort_by + ":" ').*?(?=(,|$))', v, flags=re.DOTALL|re.IGNORECASE) + if match: + sort_values[k] = match.group().strip() + else: + sort_values[k] = "0" + if sort_by == "aesthetic_score" or sort_by == "ImageRewardScore" or sort_by == "cfg scale": + sort_float = True + else: + sort_float = False + + if sort_order == down_symbol: + if sort_float: + fileinfos = [x for x in fileinfos if sort_values[x[0]] != "0"] + fileinfos.sort(key=lambda x: float(sort_values[x[0]]), reverse=True) + fileinfos = dict(fileinfos) + else: + fileinfos = dict(reversed(sorted(fileinfos, key=lambda x: natural_keys(sort_values[x[0]])))) + else: + if sort_float: + fileinfos = [x for x in fileinfos if sort_values[x[0]] != "0"] + fileinfos.sort(key=lambda x: float(sort_values[x[0]])) + fileinfos = dict(fileinfos) + else: + fileinfos = dict(sorted(fileinfos, key=lambda x: natural_keys(sort_values[x[0]]))) + filenames = [finfo for finfo in fileinfos] + else: + filenames = [finfo for finfo in fileinfos] + return filenames + +def get_image_thumbnail(image_list): + logger.debug("get_image_thumbnail") + optimized_cache = os.path.join(tempfile.gettempdir(),"optimized") + os.makedirs(optimized_cache,exist_ok=True) + thumbnail_list = [] + for image_path in image_list: + image_path_hash = hashlib.md5(image_path.encode("utf-8")).hexdigest() + cache_image_path = os.path.join(optimized_cache, image_path_hash + ".jpg") + if os.path.isfile(cache_image_path): + thumbnail_list.append(cache_image_path) + else: + try: + image = Image.open(image_path) + except OSError: + # If PIL cannot open the image, use the original path + thumbnail_list.append(image_path) + continue + width, height = image.size + left = (width - min(width, height)) / 2 + top = (height - min(width, height)) / 2 + right = (width + min(width, height)) / 2 + bottom = (height + min(width, height)) / 2 + thumbnail = image.crop((left, top, right, bottom)) + thumbnail.thumbnail((opts.image_browser_thumbnail_size, opts.image_browser_thumbnail_size)) + if thumbnail.mode != "RGB": + thumbnail = thumbnail.convert("RGB") + try: + thumbnail.save(cache_image_path, "JPEG") + thumbnail_list.append(cache_image_path) + except FileNotFoundError: + # Cannot save cache, use PIL object + thumbnail_list.append(thumbnail) + return thumbnail_list + +def set_tooltip_info(image_list): + image_browser_img_info = {} + conn, cursor = wib_db.transaction_begin() + for filename in image_list: + x, y = wib_db.select_x_y(cursor, filename) + image_browser_img_info[filename] = {"x": x, "y": y} + wib_db.transaction_end(conn, cursor) + image_browser_img_info_json = json.dumps(image_browser_img_info) + return image_browser_img_info_json + +def get_image_page(img_path, page_index, filenames, keyword, sort_by, sort_order, tab_base_tag_box, img_path_depth, ranking_filter, ranking_filter_min, ranking_filter_max, aes_filter_min, aes_filter_max, score_type, exif_keyword, negative_prompt_search, use_regex, case_sensitive, image_reward_button): + logger.debug("get_image_page") + if img_path == "": + return [], page_index, [], "", "", "", 0, "", None, "", "[]", image_reward_button + + # Set temp_dir from webui settings, so gradio uses it + if shared.opts.temp_dir != "": + tempfile.tempdir = shared.opts.temp_dir + + img_path, _ = pure_path(img_path) + filenames = get_all_images(img_path, sort_by, sort_order, keyword, tab_base_tag_box, img_path_depth, ranking_filter, ranking_filter_min, ranking_filter_max, aes_filter_min, aes_filter_max, score_type, exif_keyword, negative_prompt_search, use_regex, case_sensitive) + page_index = int(page_index) + length = len(filenames) + max_page_index = math.ceil(length / num_of_imgs_per_page) + page_index = max_page_index if page_index == -1 else page_index + page_index = 1 if page_index < 1 else page_index + page_index = max_page_index if page_index > max_page_index else page_index + idx_frm = (page_index - 1) * num_of_imgs_per_page + image_list = filenames[idx_frm:idx_frm + num_of_imgs_per_page] + + if opts.image_browser_scan_exif and opts.image_browser_img_tooltips: + image_browser_img_info = set_tooltip_info(image_list) + else: + image_browser_img_info = "[]" + + if opts.image_browser_use_thumbnail: + thumbnail_list = get_image_thumbnail(image_list) + else: + thumbnail_list = image_list + + visible_num = num_of_imgs_per_page if idx_frm + num_of_imgs_per_page < length else length % num_of_imgs_per_page + visible_num = num_of_imgs_per_page if visible_num == 0 else visible_num + + load_info = "
" + load_info += f"{length} images in this directory, divided into {int((length + 1) // num_of_imgs_per_page + 1)} pages" + load_info += "
" + + return filenames, gr.update(value=page_index, label=f"Page Index ({page_index}/{max_page_index})"), thumbnail_list, "", "", "", visible_num, load_info, None, json.dumps(image_list), image_browser_img_info, gr.update(visible=True) + +def get_current_file(tab_base_tag_box, num, page_index, filenames): + file = filenames[int(num) + int((page_index - 1) * num_of_imgs_per_page)] + return file + +def show_image_info(tab_base_tag_box, num, page_index, filenames, turn_page_switch, image_gallery): + logger.debug(f"show_image_info: tab_base_tag_box, num, page_index, len(filenames), num_of_imgs_per_page: {tab_base_tag_box}, {num}, {page_index}, {len(filenames)}, {num_of_imgs_per_page}") + if len(filenames) == 0: + # This should only happen if webui was stopped and started again and the user clicks on one of the still displayed images. + # The state with the filenames will be empty then. In that case we return None to prevent further errors and force a page refresh. + turn_page_switch = -turn_page_switch + file = None + tm = None + info = "" + else: + file_num = int(num) + int( + (page_index - 1) * num_of_imgs_per_page) + if file_num >= len(filenames): + # Last image to the right is deleted, page refresh + turn_page_switch = -turn_page_switch + file = None + tm = None + info = "" + else: + file = filenames[file_num] + tm = "
" + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(file))) + "
" + try: + with Image.open(file) as image: + _, geninfo, info = modules.extras.run_pnginfo(image) + except UnidentifiedImageError as e: + info = "" + logger.warning(f"UnidentifiedImageError: {e}") + if opts.image_browser_use_thumbnail: + image_gallery = [image['name'] for image in image_gallery] + image_gallery[int(num)] = filenames[file_num] + return file, tm, num, file, turn_page_switch, info, image_gallery + else: + return file, tm, num, file, turn_page_switch, info + +def change_dir(img_dir, path_recorder, load_switch, img_path_browser, img_path_depth, img_path): + warning = None + img_path, _ = pure_path(img_path) + img_path_depth_org = img_path_depth + if img_dir == none_select: + return warning, gr.update(visible=False), img_path_browser, path_recorder, load_switch, img_path, img_path_depth + else: + img_dir, img_path_depth = pure_path(img_dir) + if warning is None: + try: + if os.path.exists(img_dir): + try: + f = os.listdir(img_dir) + except: + warning = f"'{img_dir} is not a directory" + else: + warning = "The directory does not exist" + except: + warning = "The format of the directory is incorrect" + if warning is None: + return "", gr.update(visible=True), img_path_browser, path_recorder, img_dir, img_dir, img_path_depth + else: + return warning, gr.update(visible=False), img_path_browser, path_recorder, load_switch, img_path, img_path_depth_org + +def update_move_text_one(btn): + btn_text = " ".join(btn.split()[1:]) + return f"{copy_move[opts.image_browser_copy_image]} {btn_text}" + +def update_move_text(favorites_btn, to_dir_btn): + return update_move_text_one(favorites_btn), update_move_text_one(to_dir_btn) + +def get_ranking(filename): + ranking_value = wib_db.select_ranking(filename) + return ranking_value, None + +def img_file_name_changed(img_file_name, favorites_btn, to_dir_btn): + ranking_current, ranking = get_ranking(img_file_name) + favorites_btn, to_dir_btn = update_move_text(favorites_btn, to_dir_btn) + + return ranking_current, ranking, "", favorites_btn, to_dir_btn + +def update_exif(img_file_name, key, value): + image = Image.open(img_file_name) + geninfo, items = images.read_info_from_image(image) + if geninfo is not None: + if f"{key}: " in geninfo: + if value == "None": + geninfo = re.sub(f', {key}: \d+(\.\d+)*', '', geninfo) + else: + geninfo = re.sub(f'{key}: \d+(\.\d+)*', f'{key}: {value}', geninfo) + else: + geninfo = f'{geninfo}, {key}: {value}' + + original_time = os.path.getmtime(img_file_name) + images.save_image(image, os.path.dirname(img_file_name), "", extension=os.path.splitext(img_file_name)[1][1:], info=geninfo, forced_filename=os.path.splitext(os.path.basename(img_file_name))[0], save_to_dirs=False) + os.utime(img_file_name, (original_time, original_time)) + return geninfo + +def update_ranking(img_file_name, ranking_current, ranking, img_file_info): + # ranking = None is different than ranking = "None"! None means no radio button selected. "None" means radio button called "None" selected. + if ranking is None: + return ranking_current, None, img_file_info + + saved_ranking, _ = get_ranking(img_file_name) + if saved_ranking != ranking: + wib_db.update_ranking(img_file_name, ranking) + if opts.image_browser_ranking_pnginfo and any(img_file_name.endswith(ext) for ext in image_ext_list): + img_file_info = update_exif(img_file_name, "Ranking", ranking) + return ranking, None, img_file_info + +def generate_image_reward(filenames, turn_page_switch, aes_filter_min, aes_filter_max): + global image_reward_model + if image_reward_model is None: + image_reward_model = ImageReward.load("ImageReward-v1.0") + conn, cursor = wib_db.transaction_begin() + for filename in filenames: + saved_image_reward_score, saved_image_reward_prompt = wib_db.select_image_reward_score(cursor, filename) + if saved_image_reward_score is None and saved_image_reward_prompt is not None: + try: + with torch.no_grad(): + image_reward_score = image_reward_model.score(saved_image_reward_prompt, filename) + image_reward_score = f"{image_reward_score:.2f}" + try: + logger.warning(f"Generated ImageRewardScore: {image_reward_score} for {filename}") + except UnicodeEncodeError: + pass + wib_db.update_image_reward_score(cursor, filename, image_reward_score) + if any(filename.endswith(ext) for ext in image_ext_list): + img_file_info = update_exif(filename, "ImageRewardScore", image_reward_score) + except UnidentifiedImageError as e: + logger.warning(f"UnidentifiedImageError: {e}") + wib_db.transaction_end(conn, cursor) + return -turn_page_switch, aes_filter_min, aes_filter_max + +def create_tab(tab: ImageBrowserTab, current_gr_tab: gr.Tab): + global init, exif_cache, aes_cache, image_reward_cache, openoutpaint, controlnet, js_dummy_return + dir_name = None + others_dir = False + maint = False + standard_ui = True + path_recorder = {} + path_recorder_formatted = [] + path_recorder_unformatted = [] + + if init: + db_version = wib_db.check() + logger.debug(f"db_version: {db_version}") + exif_cache = wib_db.load_exif_data(exif_cache) + aes_cache = wib_db.load_exif_data_by_key(aes_cache, "aesthetic_score", "Score") + image_reward_cache = wib_db.load_exif_data_by_key(image_reward_cache, "ImageRewardScore", "ImageRewardScore") + init = False + + path_recorder, path_recorder_formatted, path_recorder_unformatted = read_path_recorder() + openoutpaint = check_ext("openoutpaint") + controlnet = check_ext("controlnet") + + if tab.name == "Others": + others_dir = True + standard_ui = False + elif tab.name == "Maintenance": + maint = True + standard_ui = False + else: + dir_name = tab.path + + if standard_ui: + dir_name = str(Path(dir_name)) + if not os.path.exists(dir_name): + os.makedirs(dir_name) + + with gr.Row(): + path_recorder = gr.State(path_recorder) + with gr.Column(scale=10): + warning_box = gr.HTML("

 ", elem_id=f"{tab.base_tag}_image_browser_warning_box") + with gr.Column(scale=5, visible=(tab.name==favorite_tab_name)): + gr.HTML(f"

Favorites path from settings: {opts.outdir_save}") + + with gr.Row(visible=others_dir): + with gr.Column(scale=10): + suffix = "" if others_dir else tab.name + img_path = gr.Textbox(dir_name, label="Images directory"+suffix, placeholder="Input images directory", interactive=others_dir) + with gr.Column(scale=1): + img_path_depth = gr.Number(value="0", label="Sub directory depth") + with gr.Column(scale=1): + img_path_save_button = gr.Button(value="Add to / replace in saved directories") + + with gr.Row(visible=others_dir): + with gr.Column(scale=10): + img_path_browser = gr.Dropdown(choices=path_recorder_formatted, label="Saved directories") + with gr.Column(scale=1): + img_path_remove_button = gr.Button(value="Remove from saved directories") + + with gr.Row(visible=others_dir): + with gr.Column(scale=10): + img_path_subdirs = gr.Dropdown(choices=[none_select], value=none_select, label="Sub directories", interactive=True, elem_id=f"{tab.base_tag}_img_path_subdirs") + with gr.Column(scale=1): + img_path_subdirs_button = gr.Button(value="Get sub directories") + + with gr.Row(visible=standard_ui, elem_id=f"{tab.base_tag}_image_browser") as main_panel: + with gr.Column(): + with gr.Row(): + with gr.Column(scale=2): + with gr.Row(elem_id=f"{tab.base_tag}_image_browser_gallery_controls") as gallery_controls_panel: + with gr.Column(scale=2, min_width=20): + first_page = gr.Button("First Page", elem_id=f"{tab.base_tag}_control_image_browser_first_page") + with gr.Column(scale=2, min_width=20): + prev_page = gr.Button("Prev Page", elem_id=f"{tab.base_tag}_control_image_browser_prev_page") + with gr.Column(scale=2, min_width=20): + page_index = gr.Number(value=1, label="Page Index", elem_id=f"{tab.base_tag}_control_image_browser_page_index") + with gr.Column(scale=1, min_width=20): + refresh_index_button = ToolButton(value=refresh_symbol, elem_id=f"{tab.base_tag}_control_image_browser_refresh_index") + with gr.Column(scale=2, min_width=20): + next_page = gr.Button("Next Page", elem_id=f"{tab.base_tag}_control_image_browser_next_page") + with gr.Column(scale=2, min_width=20): + end_page = gr.Button("End Page", elem_id=f"{tab.base_tag}_control_image_browser_end_page") + with gr.Row(visible=False) as ranking_panel: + with gr.Column(scale=1, min_width=20): + ranking_current = gr.Textbox(value="None", label="Current ranking", interactive=False) + with gr.Column(scale=4, min_width=20): + ranking = gr.Radio(choices=["1", "2", "3", "4", "5", "None"], label="Set ranking to", elem_id=f"{tab.base_tag}_control_image_browser_ranking", interactive=True) + with gr.Row(): + image_gallery = gr.Gallery(show_label=False, elem_id=f"{tab.base_tag}_image_browser_gallery").style(grid=opts.image_browser_page_columns) + with gr.Row() as delete_panel: + with gr.Column(scale=1): + delete_num = gr.Number(value=1, interactive=True, label="delete next", elem_id=f"{tab.base_tag}_image_browser_del_num") + delete_confirm = gr.Checkbox(value=False, label="also delete off-screen images") + with gr.Column(scale=3): + delete = gr.Button('Delete', elem_id=f"{tab.base_tag}_image_browser_del_img_btn") + with gr.Row() as info_add_panel: + with gr.Accordion("Additional Generation Info", open=False): + img_file_info_add = gr.HTML() + + with gr.Column(scale=1): + with gr.Row() as sort_panel: + sort_by = gr.Dropdown(value="date", choices=["path name", "date", "aesthetic_score", "ImageRewardScore", "random", "cfg scale", "steps", "seed", "sampler", "size", "model", "model hash", "ranking"], label="Sort by") + sort_order = ToolButton(value=down_symbol) + with gr.Row() as filename_search_panel: + filename_keyword_search = gr.Textbox(value="", label="Filename keyword search") + with gr.Box() as exif_search_panel: + with gr.Row(): + exif_keyword_search = gr.Textbox(value="", label="EXIF keyword search") + negative_prompt_search = gr.Radio(value="No", choices=["No", "Yes", "Only"], label="Search negative prompt", interactive=True) + with gr.Row(): + case_sensitive = gr.Checkbox(value=False, label="case sensitive") + use_regex = gr.Checkbox(value=False, label=r"regex - e.g. ^(?!.*Hires).*$") + with gr.Box() as ranking_filter_panel: + with gr.Row(): + ranking_filter = gr.Radio(value="All", choices=["All", "1", "2", "3", "4", "5", "None", "Min-max"], label="Ranking filter", interactive=True) + with gr.Row(): + with gr.Column(scale=2, min_width=20): + ranking_filter_min = gr.Textbox(value="1", label="Minimum ranking", interactive=False) + with gr.Column(scale=2, min_width=20): + ranking_filter_max = gr.Textbox(value="5", label="Maximum ranking", interactive=False) + with gr.Column(scale=4, min_width=20): + gr.Textbox(value="Choose Min-max to activate these controls", label="", interactive=False) + with gr.Box() as aesthetic_score_filter_panel: + with gr.Row(): + with gr.Column(scale=4, min_width=20): + score_type = gr.Dropdown(value=opts.image_browser_scoring_type, choices=["aesthetic_score", "ImageReward Score"], label="Scoring type", interactive=True) + with gr.Column(scale=2, min_width=20): + image_reward_button = gr.Button(value="Generate ImageReward Scores for all images", interactive=image_reward_installed, visible=False) + with gr.Row(): + aes_filter_min = gr.Textbox(value="", label="Minimum score") + aes_filter_max = gr.Textbox(value="", label="Maximum score") + with gr.Row() as generation_info_panel: + img_file_info = gr.Textbox(label="Generation Info", interactive=False, lines=6,elem_id=f"{tab.base_tag}_image_browser_file_info") + with gr.Row() as filename_panel: + img_file_name = gr.Textbox(value="", label="File Name", interactive=False) + with gr.Row() as filetime_panel: + img_file_time= gr.HTML() + with gr.Row() as open_folder_panel: + open_folder_button = gr.Button(folder_symbol, visible=standard_ui or others_dir) + gr.HTML(" ") + gr.HTML(" ") + gr.HTML(" ") + with gr.Row(elem_id=f"{tab.base_tag}_image_browser_button_panel", visible=False) as button_panel: + with gr.Column(): + with gr.Row(): + if tab.name == favorite_tab_name: + favorites_btn_show = False + else: + favorites_btn_show = True + favorites_btn = gr.Button(f'{copy_move[opts.image_browser_copy_image]} to favorites', elem_id=f"{tab.base_tag}_image_browser_favorites_btn", visible=favorites_btn_show) + try: + send_to_buttons = modules.generation_parameters_copypaste.create_buttons(["txt2img", "img2img", "inpaint", "extras"]) + except: + pass + sendto_openoutpaint = gr.Button("Send to openOutpaint", elem_id=f"{tab.base_tag}_image_browser_openoutpaint_btn", visible=openoutpaint) + with gr.Row(visible=controlnet): + sendto_controlnet_txt2img = gr.Button("Send to txt2img ControlNet", visible=controlnet) + sendto_controlnet_img2img = gr.Button("Send to img2img ControlNet", visible=controlnet) + controlnet_max = opts.data.get("control_net_max_models_num", 1) + sendto_controlnet_num = gr.Dropdown([str(i) for i in range(controlnet_max)], label="ControlNet number", value="0", interactive=True, visible=(controlnet and controlnet_max > 1)) + if controlnet_max is None: + sendto_controlnet_type = gr.Textbox(value="none", visible=False) + elif controlnet_max == 1: + sendto_controlnet_type = gr.Textbox(value="single", visible=False) + else: + sendto_controlnet_type = gr.Textbox(value="multiple", visible=False) + with gr.Row(elem_id=f"{tab.base_tag}_image_browser_to_dir_panel", visible=False) as to_dir_panel: + with gr.Box(): + with gr.Row(): + to_dir_path = gr.Textbox(label="Directory path") + with gr.Row(): + to_dir_saved = gr.Dropdown(choices=path_recorder_unformatted, label="Saved directories") + with gr.Row(): + to_dir_btn = gr.Button(f'{copy_move[opts.image_browser_copy_image]} to directory', elem_id=f"{tab.base_tag}_image_browser_to_dir_btn") + + with gr.Row(): + collected_warning = gr.HTML() + + with gr.Row(visible=False): + renew_page = gr.Button("Renew Page", elem_id=f"{tab.base_tag}_image_browser_renew_page") + visible_img_num = gr.Number() + tab_base_tag_box = gr.Textbox(tab.base_tag) + image_index = gr.Textbox(value=-1, elem_id=f"{tab.base_tag}_image_browser_image_index") + set_index = gr.Button('set_index', elem_id=f"{tab.base_tag}_image_browser_set_index") + filenames = gr.State([]) + hidden = gr.Image(type="pil", elem_id=f"{tab.base_tag}_image_browser_hidden_image") + image_page_list = gr.Textbox(elem_id=f"{tab.base_tag}_image_browser_image_page_list") + info1 = gr.Textbox() + info2 = gr.Textbox() + load_switch = gr.Textbox(value="load_switch", label="load_switch") + to_dir_load_switch = gr.Textbox(value="to dir load_switch", label="to_dir_load_switch") + turn_page_switch = gr.Number(value=1, label="turn_page_switch") + select_image = gr.Number(value=1) + img_path_add = gr.Textbox(value="add") + img_path_remove = gr.Textbox(value="remove") + favorites_path = gr.Textbox(value=opts.outdir_save) + mod_keys = "" + if opts.image_browser_mod_ctrl_shift: + mod_keys = f"{mod_keys}CS" + elif opts.image_browser_mod_shift: + mod_keys = f"{mod_keys}S" + image_browser_mod_keys = gr.Textbox(value=mod_keys, elem_id=f"{tab.base_tag}_image_browser_mod_keys") + image_browser_prompt = gr.Textbox(elem_id=f"{tab.base_tag}_image_browser_prompt") + image_browser_neg_prompt = gr.Textbox(elem_id=f"{tab.base_tag}_image_browser_neg_prompt") + js_logs = gr.Textbox() + image_browser_img_info = gr.Textbox(value="[]", elem_id=f"{tab.base_tag}_image_browser_img_info") + + # Maintenance tab + with gr.Row(visible=maint): + with gr.Column(scale=4): + gr.HTML(f"{caution_symbol} Caution: You should only use these options if you know what you are doing. {caution_symbol}") + with gr.Column(scale=3): + maint_wait = gr.HTML("Status:") + with gr.Column(scale=7): + gr.HTML(" ") + with gr.Row(visible=maint): + maint_last_msg = gr.Textbox(label="Last message", interactive=False) + with gr.Row(visible=maint): + with gr.Column(scale=1): + maint_exif_rebuild = gr.Button(value="Rebuild exif cache") + with gr.Column(scale=1): + maint_exif_delete_0 = gr.Button(value="Delete 0-entries from exif cache") + with gr.Column(scale=10): + gr.HTML(visible=False) + with gr.Row(visible=maint): + with gr.Column(scale=1): + maint_update_dirs = gr.Button(value="Update directory names in database") + with gr.Column(scale=10): + maint_update_dirs_from = gr.Textbox(label="From (full path)") + with gr.Column(scale=10): + maint_update_dirs_to = gr.Textbox(label="to (full path)") + with gr.Row(visible=maint): + with gr.Column(scale=1): + maint_reapply_ranking = gr.Button(value="Reapply ranking after moving files") + with gr.Column(scale=10): + gr.HTML(visible=False) + with gr.Row(visible=maint): + with gr.Column(scale=1): + maint_restart_debug = gr.Button(value="Restart debug") + with gr.Column(scale=10): + gr.HTML(visible=False) + with gr.Row(visible=maint): + with gr.Column(scale=1): + maint_get_js_logs = gr.Button(value="Get javascript logs") + with gr.Column(scale=10): + maint_show_logs = gr.Textbox(label="Javascript logs", lines=10, interactive=False) + with gr.Row(visible=False): + with gr.Column(scale=1): + maint_rebuild_ranking = gr.Button(value="Rebuild ranking from exif info") + with gr.Column(scale=10): + gr.HTML(visible=False) + + # Hide components based on opts.image_browser_hidden_components + hidden_component_map = { + "Sort by": sort_panel, + "Filename keyword search": filename_search_panel, + "EXIF keyword search": exif_search_panel, + "Ranking Filter": ranking_filter_panel, + "Aesthestic Score": aesthetic_score_filter_panel, + "Generation Info": generation_info_panel, + "File Name": filename_panel, + "File Time": filetime_panel, + "Open Folder": open_folder_panel, + "Send to buttons": button_panel, + "Copy to directory": to_dir_panel, + "Gallery Controls Bar": gallery_controls_panel, + "Ranking Bar": ranking_panel, + "Delete Bar": delete_panel, + "Additional Generation Info": info_add_panel + } + + if set(hidden_component_map.keys()) != set(components_list): + logger.warning(f"Invalid items present in either hidden_component_map or components_list. Make sure when adding new components they are added to both.") + + override_hidden = set() + if hasattr(opts, "image_browser_hidden_components"): + for item in opts.image_browser_hidden_components: + hidden_component_map[item].visible = False + override_hidden.add(hidden_component_map[item]) + + change_dir_outputs = [warning_box, main_panel, img_path_browser, path_recorder, load_switch, img_path, img_path_depth] + img_path.submit(change_dir, inputs=[img_path, path_recorder, load_switch, img_path_browser, img_path_depth, img_path], outputs=change_dir_outputs, show_progress=opts.image_browser_show_progress) + img_path_browser.change(change_dir, inputs=[img_path_browser, path_recorder, load_switch, img_path_browser, img_path_depth, img_path], outputs=change_dir_outputs, show_progress=opts.image_browser_show_progress) + # img_path_browser.change(browser2path, inputs=[img_path_browser], outputs=[img_path]) + to_dir_saved.change(change_dir, inputs=[to_dir_saved, path_recorder, to_dir_load_switch, to_dir_saved, img_path_depth, to_dir_path], outputs=[warning_box, main_panel, to_dir_saved, path_recorder, to_dir_load_switch, to_dir_path, img_path_depth], show_progress=opts.image_browser_show_progress) + + #delete + delete.click( + fn=delete_image, + inputs=[tab_base_tag_box, delete_num, img_file_name, filenames, image_index, visible_img_num, delete_confirm, turn_page_switch, image_page_list], + outputs=[filenames, delete_num, turn_page_switch, visible_img_num, image_gallery, select_image, image_page_list], + show_progress=opts.image_browser_show_progress + ).then( + fn=None, + _js="image_browser_select_image", + inputs=[tab_base_tag_box, image_index, select_image], + outputs=[js_dummy_return], + show_progress=opts.image_browser_show_progress + ) + + to_dir_btn.click(save_image, inputs=[img_file_name, filenames, page_index, turn_page_switch, to_dir_path], outputs=[collected_warning, filenames, page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + #turn page + first_page.click(lambda s:(1, -s) , inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + next_page.click(lambda p, s: (p + 1, -s), inputs=[page_index, turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + prev_page.click(lambda p, s: (p - 1, -s), inputs=[page_index, turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + end_page.click(lambda s: (-1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + load_switch.change(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + filename_keyword_search.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + exif_keyword_search.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + ranking_filter_min.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + ranking_filter_max.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + aes_filter_min.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + aes_filter_max.submit(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + sort_by.change(lambda s:(1, -s), inputs=[turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + page_index.submit(lambda s: -s, inputs=[turn_page_switch], outputs=[turn_page_switch], show_progress=opts.image_browser_show_progress) + renew_page.click(lambda s: -s, inputs=[turn_page_switch], outputs=[turn_page_switch], show_progress=opts.image_browser_show_progress) + refresh_index_button.click(lambda p, s:(p, -s), inputs=[page_index, turn_page_switch], outputs=[page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + img_path_depth.change(lambda s: -s, inputs=[turn_page_switch], outputs=[turn_page_switch], show_progress=opts.image_browser_show_progress) + + hide_on_thumbnail_view = [delete_panel, button_panel, ranking_panel, to_dir_panel, info_add_panel] + + sort_order.click( + fn=sort_order_flip, + inputs=[turn_page_switch, sort_order], + outputs=[page_index, turn_page_switch, sort_order], + show_progress=opts.image_browser_show_progress + ) + ranking_filter.change( + fn=ranking_filter_settings, + inputs=[page_index, turn_page_switch, ranking_filter], + outputs=[page_index, turn_page_switch, ranking_filter_min, ranking_filter_max], + show_progress=opts.image_browser_show_progress + ) + + # Others + img_path_subdirs_button.click( + fn=img_path_subdirs_get, + inputs=[img_path], + outputs=[img_path_subdirs], + show_progress=opts.image_browser_show_progress + ) + img_path_subdirs.change( + fn=change_dir, + inputs=[img_path_subdirs, path_recorder, load_switch, img_path_browser, img_path_depth, img_path], + outputs=change_dir_outputs, + show_progress=opts.image_browser_show_progress + ) + img_path_save_button.click( + fn=img_path_add_remove, + inputs=[img_path, path_recorder, img_path_add, img_path_depth], + outputs=[path_recorder, img_path_browser], + show_progress=opts.image_browser_show_progress + ) + img_path_remove_button.click( + fn=img_path_add_remove, + inputs=[img_path, path_recorder, img_path_remove, img_path_depth], + outputs=[path_recorder, img_path_browser], + show_progress=opts.image_browser_show_progress + ) + maint_exif_rebuild.click( + fn=exif_rebuild, + inputs=[maint_wait], + outputs=[maint_wait, maint_last_msg], + show_progress=True + ) + maint_exif_delete_0.click( + fn=exif_delete_0, + inputs=[maint_wait], + outputs=[maint_wait, maint_last_msg], + show_progress=True + ) + maint_update_dirs.click( + fn=exif_update_dirs, + inputs=[maint_update_dirs_from, maint_update_dirs_to, maint_wait], + outputs=[maint_wait, maint_last_msg], + show_progress=True + ) + maint_reapply_ranking.click( + fn=reapply_ranking, + inputs=[path_recorder, maint_wait], + outputs=[maint_wait, maint_last_msg], + show_progress=True + ) + maint_restart_debug.click( + fn=restart_debug, + inputs=[maint_wait], + outputs=[maint_wait, maint_last_msg], + show_progress=True + ) + maint_get_js_logs.click( + fn=js_logs_output, + _js="get_js_logs", + inputs=[js_logs], + outputs=[maint_show_logs], + show_progress=True + ) + + # other functions + if opts.image_browser_use_thumbnail: + set_index_outputs = [img_file_name, img_file_time, image_index, hidden, turn_page_switch, img_file_info_add, image_gallery] + else: + set_index_outputs = [img_file_name, img_file_time, image_index, hidden, turn_page_switch, img_file_info_add] + set_index.click( + fn=show_image_info, + _js="image_browser_get_current_img", + inputs=[tab_base_tag_box, image_index, page_index, filenames, turn_page_switch, image_gallery], + outputs=set_index_outputs, + show_progress=opts.image_browser_show_progress + ).then( + fn=None, + _js="image_browser_img_show_progress_update", + inputs=[], + outputs=[js_dummy_return], + show_progress=opts.image_browser_show_progress + ) + + set_index.click(fn=lambda:(gr.update(visible=delete_panel not in override_hidden), gr.update(visible=button_panel not in override_hidden), gr.update(visible=ranking_panel not in override_hidden), gr.update(visible=to_dir_panel not in override_hidden), gr.update(visible=info_add_panel not in override_hidden)), inputs=None, outputs=hide_on_thumbnail_view, show_progress=opts.image_browser_show_progress) + + favorites_btn.click(save_image, inputs=[img_file_name, filenames, page_index, turn_page_switch, favorites_path], outputs=[collected_warning, filenames, page_index, turn_page_switch], show_progress=opts.image_browser_show_progress) + img_file_name.change(img_file_name_changed, inputs=[img_file_name, favorites_btn, to_dir_btn], outputs=[ranking_current, ranking, collected_warning, favorites_btn, to_dir_btn], show_progress=opts.image_browser_show_progress) + + hidden.change(fn=run_pnginfo, inputs=[hidden, img_path, img_file_name], outputs=[info1, img_file_info, info2, image_browser_prompt, image_browser_neg_prompt], show_progress=opts.image_browser_show_progress) + + #ranking + ranking.change(update_ranking, inputs=[img_file_name, ranking_current, ranking, img_file_info], outputs=[ranking_current, ranking, img_file_info], show_progress=opts.image_browser_show_progress) + + try: + modules.generation_parameters_copypaste.bind_buttons(send_to_buttons, hidden, img_file_info) + except: + pass + + if standard_ui: + current_gr_tab.select( + fn=tab_select, + inputs=[], + outputs=[path_recorder, to_dir_saved], + show_progress=opts.image_browser_show_progress + ) + open_folder_button.click( + fn=lambda: open_folder(dir_name), + inputs=[], + outputs=[], + show_progress=opts.image_browser_show_progress + ) + elif others_dir: + open_folder_button.click( + fn=open_folder, + inputs=[img_path], + outputs=[], + show_progress=opts.image_browser_show_progress + ) + if standard_ui or others_dir: + turn_page_switch.change( + fn=get_image_page, + inputs=[img_path, page_index, filenames, filename_keyword_search, sort_by, sort_order, tab_base_tag_box, img_path_depth, ranking_filter, ranking_filter_min, ranking_filter_max, aes_filter_min, aes_filter_max, score_type, exif_keyword_search, negative_prompt_search, use_regex, case_sensitive, image_reward_button], + outputs=[filenames, page_index, image_gallery, img_file_name, img_file_time, img_file_info, visible_img_num, warning_box, hidden, image_page_list, image_browser_img_info, image_reward_button], + show_progress=opts.image_browser_show_progress + ).then( + fn=None, + _js="image_browser_turnpage", + inputs=[tab_base_tag_box], + outputs=[js_dummy_return], + show_progress=opts.image_browser_show_progress + ) + turn_page_switch.change(fn=lambda:(gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)), inputs=None, outputs=hide_on_thumbnail_view, show_progress=opts.image_browser_show_progress) + sendto_openoutpaint.click( + fn=None, + inputs=[tab_base_tag_box, image_index, image_browser_prompt, image_browser_neg_prompt], + outputs=[js_dummy_return], + _js="image_browser_openoutpaint_send", + show_progress=opts.image_browser_show_progress ) + sendto_controlnet_txt2img.click( + fn=None, + inputs=[tab_base_tag_box, image_index, sendto_controlnet_num, sendto_controlnet_type], + outputs=[js_dummy_return], + _js="image_browser_controlnet_send_txt2img", + show_progress=opts.image_browser_show_progress + ) + sendto_controlnet_img2img.click( + fn=None, + inputs=[tab_base_tag_box, image_index, sendto_controlnet_num, sendto_controlnet_type], + outputs=[js_dummy_return], + _js="image_browser_controlnet_send_img2img", + show_progress=opts.image_browser_show_progress + ) + image_reward_button.click( + fn=generate_image_reward, + inputs=[filenames, turn_page_switch, aes_filter_min, aes_filter_max], + outputs=[turn_page_switch, aes_filter_min, aes_filter_max], + show_progress=True + ) + +def run_pnginfo(image, image_path, image_file_name): + if image is None: + return '', '', '', '', '' + try: + geninfo, items = images.read_info_from_image(image) + items = {**{'parameters': geninfo}, **items} + + info = '' + for key, text in items.items(): + info += f""" +

+

{plaintext_to_html(str(key))}

+

{plaintext_to_html(str(text))}

+
+ """.strip()+"\n" + except UnidentifiedImageError as e: + geninfo = None + info = "" + + if geninfo is None: + try: + filename = os.path.splitext(image_file_name)[0] + ".txt" + geninfo = "" + with open(filename) as f: + for line in f: + geninfo += line + except Exception: + logger.warning(f"run_pnginfo: No EXIF in image or txt file") + + if openoutpaint: + prompt, neg_prompt = wib_db.select_prompts(image_file_name) + if prompt == "0": + prompt = "" + if neg_prompt == "0": + neg_prompt = "" + else: + prompt = "" + neg_prompt = "" + + return '', geninfo, info, prompt, neg_prompt + + +def on_ui_tabs(): + global num_of_imgs_per_page, loads_files_num, js_dummy_return + num_of_imgs_per_page = int(opts.image_browser_page_columns * opts.image_browser_page_rows) + loads_files_num = int(opts.image_browser_pages_perload * num_of_imgs_per_page) + with gr.Blocks(analytics_enabled=False) as image_browser: + gradio_needed = "3.23.0" + if version.parse(gr.__version__) < version.parse(gradio_needed): + gr.HTML(f'

You are running Gradio version {gr.__version__}. This version of the extension requires at least Gradio version {gradio_needed}.

For more details see https://github.com/AlUlkesh/stable-diffusion-webui-images-browser/issues/116#issuecomment-1493259585

') + else: + with gr.Tabs(elem_id="image_browser_tabs_container") as tabs: + js_dummy_return = gr.Textbox(interactive=False, visible=False) + for i, tab in enumerate(tabs_list): + with gr.Tab(tab.name, elem_id=f"{tab.base_tag}_image_browser_container") as current_gr_tab: + with gr.Blocks(analytics_enabled=False): + create_tab(tab, current_gr_tab) + gr.Checkbox(value=opts.image_browser_preload, elem_id="image_browser_preload", visible=False) + gr.Textbox(",".join( [tab.base_tag for tab in tabs_list] ), elem_id="image_browser_tab_base_tags_list", visible=False) + gr.Checkbox(value=opts.image_browser_swipe, elem_id=f"image_browser_swipe", visible=False) + + javascript_level_value, (javascript_level, javascript_level_text) = debug_levels(arg_level="javascript") + level_value, (level, level_text) = debug_levels(arg_text=opts.image_browser_debug_level) + if level_value >= javascript_level_value: + debug_level_option = level + else: + debug_level_option = "" + gr.Textbox(value=debug_level_option, elem_id="image_browser_debug_level_option", visible=False) + + return (image_browser, "Image Browser", "image_browser"), + +def move_setting(cur_setting_name, old_setting_name, option_info, section, added): + try: + old_value = shared.opts.__getattr__(old_setting_name) + except AttributeError: + old_value = None + try: + new_value = shared.opts.__getattr__(cur_setting_name) + except AttributeError: + new_value = None + if old_value is not None and new_value is None: + # Add new option + shared.opts.add_option(cur_setting_name, shared.OptionInfo(*option_info, section=section)) + shared.opts.__setattr__(cur_setting_name, old_value) + added = added + 1 + # Remove old option + shared.opts.data.pop(old_setting_name, None) + + return added + +def on_ui_settings(): + # [current setting_name], [old setting_name], [default], [label], [component], [component_args] + active_tabs_description = f"List of active tabs (separated by commas). Available options are {', '.join(default_tab_options)}. Custom folders are also supported by specifying their path." + debug_level_choices = [] + for i in range(len(debug_level_types)): + level_value, (level, level_text) = debug_levels(arg_value=i) + debug_level_choices.append(level_text) + + image_browser_options = [ + ("image_browser_active_tabs", None, ", ".join(default_tab_options), active_tabs_description), + ("image_browser_hidden_components", None, [], "Select components to hide", DropdownMulti, lambda: {"choices": components_list}), + ("image_browser_with_subdirs", "images_history_with_subdirs", True, "Include images in sub directories"), + ("image_browser_preload", "images_history_preload", False, "Preload images at startup for first tab"), + ("image_browser_copy_image", "images_copy_image", False, "Move buttons copy instead of move"), + ("image_browser_delete_message", "images_delete_message", True, "Print image deletion messages to the console"), + ("image_browser_txt_files", "images_txt_files", True, "Move/Copy/Delete matching .txt files"), + ("image_browser_debug_level", None, debug_level_choices[0], "Debug level", gr.Dropdown, lambda: {"choices": debug_level_choices}), + ("image_browser_delete_recycle", "images_delete_recycle", True, "Use recycle bin when deleting images"), + ("image_browser_scan_exif", "images_scan_exif", True, "Scan Exif-/.txt-data (initially slower, but required for many features to work)"), + ("image_browser_mod_shift", None, False, "Change CTRL keybindings to SHIFT"), + ("image_browser_mod_ctrl_shift", None, False, "or to CTRL+SHIFT"), + ("image_browser_enable_maint", None, True, "Enable Maintenance tab"), + ("image_browser_ranking_pnginfo", None, False, "Save ranking in image's pnginfo"), + ("image_browser_page_columns", "images_history_page_columns", 6, "Number of columns on the page"), + ("image_browser_page_rows", "images_history_page_rows", 6, "Number of rows on the page"), + ("image_browser_pages_perload", "images_history_pages_perload", 20, "Minimum number of pages per load"), + ("image_browser_use_thumbnail", None, False, "Use optimized images in the thumbnail interface (significantly reduces the amount of data transferred)"), + ("image_browser_thumbnail_size", None, 200, "Size of the thumbnails (px)"), + ("image_browser_swipe", None, False, "Swipe left/right navigates to the next image"), + ("image_browser_img_tooltips", None, True, "Enable thumbnail tooltips"), + ("image_browser_scoring_type", None, "aesthetic_score", "Default scoring type", gr.Dropdown, lambda: {"choices": ["aesthetic_score", "ImageReward Score"]}), + ("image_browser_show_progress", None, True, "Show progress indicator"), + ] + + section = ('image-browser', "Image Browser") + # Move historic setting names to current names + added = 0 + for cur_setting_name, old_setting_name, *option_info in image_browser_options: + if old_setting_name is not None: + added = move_setting(cur_setting_name, old_setting_name, option_info, section, added) + if added > 0: + shared.opts.save(shared.config_filename) + + for cur_setting_name, _, *option_info in image_browser_options: + shared.opts.add_option(cur_setting_name, shared.OptionInfo(*option_info, section=section)) + +script_callbacks.on_ui_settings(on_ui_settings) +script_callbacks.on_ui_tabs(on_ui_tabs) diff --git a/stable-diffusion-webui-images-browser/scripts/wib/__pycache__/wib_db.cpython-310.pyc b/stable-diffusion-webui-images-browser/scripts/wib/__pycache__/wib_db.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64902ba7cb72164df0b21e74de1f7d229c3e3666 Binary files /dev/null and b/stable-diffusion-webui-images-browser/scripts/wib/__pycache__/wib_db.cpython-310.pyc differ diff --git a/stable-diffusion-webui-images-browser/scripts/wib/wib_db.py b/stable-diffusion-webui-images-browser/scripts/wib/wib_db.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff9ed1bb9e9b263dab3e137ec70d89d12e25036 --- /dev/null +++ b/stable-diffusion-webui-images-browser/scripts/wib/wib_db.py @@ -0,0 +1,888 @@ +import hashlib +import json +import os +import sqlite3 +from modules import scripts +from PIL import Image + +version = 6 + +path_recorder_file = os.path.join(scripts.basedir(), "path_recorder.txt") +aes_cache_file = os.path.join(scripts.basedir(), "aes_scores.json") +exif_cache_file = os.path.join(scripts.basedir(), "exif_data.json") +ranking_file = os.path.join(scripts.basedir(), "ranking.json") +archive = os.path.join(scripts.basedir(), "archive") +db_file = os.path.join(scripts.basedir(), "wib.sqlite3") +np = "Negative prompt: " +st = "Steps: " +timeout = 30 + +def create_filehash(cursor): + cursor.execute(''' + CREATE TABLE IF NOT EXISTS filehash ( + file TEXT PRIMARY KEY, + hash TEXT, + created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + ''') + + cursor.execute(''' + CREATE TRIGGER filehash_tr + AFTER UPDATE ON filehash + BEGIN + UPDATE filehash SET updated = CURRENT_TIMESTAMP WHERE file = OLD.file; + END; + ''') + + return + +def create_work_files(cursor): + cursor.execute(''' + CREATE TABLE IF NOT EXISTS work_files ( + file TEXT PRIMARY KEY + ) + ''') + + return + +def create_db(cursor): + cursor.execute(''' + CREATE TABLE IF NOT EXISTS db_data ( + key TEXT PRIMARY KEY, + value TEXT + ) + ''') + + cursor.execute(''' + CREATE TABLE IF NOT EXISTS path_recorder ( + path TEXT PRIMARY KEY, + depth INT, + path_display TEXT, + created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + ''') + + cursor.execute(''' + CREATE TRIGGER path_recorder_tr + AFTER UPDATE ON path_recorder + BEGIN + UPDATE path_recorder SET updated = CURRENT_TIMESTAMP WHERE path = OLD.path; + END; + ''') + + cursor.execute(''' + CREATE TABLE IF NOT EXISTS exif_data ( + file TEXT, + key TEXT, + value TEXT, + created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (file, key) + ) + ''') + + cursor.execute(''' + CREATE INDEX IF NOT EXISTS exif_data_key ON exif_data (key) + ''') + + cursor.execute(''' + CREATE TRIGGER exif_data_tr + AFTER UPDATE ON exif_data + BEGIN + UPDATE exif_data SET updated = CURRENT_TIMESTAMP WHERE file = OLD.file AND key = OLD.key; + END; + ''') + + cursor.execute(''' + CREATE TABLE IF NOT EXISTS ranking ( + file TEXT PRIMARY KEY, + name TEXT, + ranking TEXT, + created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + ''') + + cursor.execute(''' + CREATE INDEX IF NOT EXISTS ranking_name ON ranking (name) + ''') + + cursor.execute(''' + CREATE TRIGGER ranking_tr + AFTER UPDATE ON ranking + BEGIN + UPDATE ranking SET updated = CURRENT_TIMESTAMP WHERE file = OLD.file; + END; + ''') + + create_filehash(cursor) + create_work_files(cursor) + + return + +def migrate_path_recorder(cursor): + if os.path.exists(path_recorder_file): + try: + with open(path_recorder_file) as f: + # json-version + path_recorder = json.load(f) + for path, values in path_recorder.items(): + path = os.path.realpath(path) + depth = values["depth"] + path_display = f"{path} [{depth}]" + cursor.execute(''' + INSERT INTO path_recorder (path, depth, path_display) + VALUES (?, ?, ?) + ''', (path, depth, path_display)) + except json.JSONDecodeError: + with open(path_recorder_file) as f: + # old txt-version + path = f.readline().rstrip("\n") + while len(path) > 0: + path = os.path.realpath(path) + cursor.execute(''' + INSERT INTO path_recorder (path, depth, path_display) + VALUES (?, ?, ?) + ''', (path, 0, f"{path} [0]")) + path = f.readline().rstrip("\n") + + return + +def update_exif_data(cursor, file, info): + prompt = "0" + negative_prompt = "0" + key_values = "0: 0" + if info != "0": + info_list = info.split("\n") + prompt = "" + negative_prompt = "" + key_values = "" + for info_item in info_list: + if info_item.startswith(st): + key_values = info_item + elif info_item.startswith(np): + negative_prompt = info_item.replace(np, "") + else: + if prompt == "": + prompt = info_item + else: + # multiline prompts + prompt = f"{prompt}\n{info_item}" + if key_values != "": + key_value_pairs = [] + key_value = "" + quote_open = False + for char in key_values + ",": + key_value += char + if char == '"': + quote_open = not quote_open + if char == "," and not quote_open: + try: + k, v = key_value.strip(" ,").split(": ") + except ValueError: + k = key_value.strip(" ,").split(": ")[0] + v = "" + key_value_pairs.append((k, v)) + key_value = "" + + try: + cursor.execute(''' + INSERT INTO exif_data (file, key, value) + VALUES (?, ?, ?) + ''', (file, "prompt", prompt)) + except sqlite3.IntegrityError: + # Duplicate, delete all "file" entries and try again + cursor.execute(''' + DELETE FROM exif_data + WHERE file = ? + ''', (file,)) + + cursor.execute(''' + INSERT INTO exif_data (file, key, value) + VALUES (?, ?, ?) + ''', (file, "prompt", prompt)) + + cursor.execute(''' + INSERT INTO exif_data (file, key, value) + VALUES (?, ?, ?) + ''', (file, "negative_prompt", negative_prompt)) + + for (key, value) in key_value_pairs: + try: + cursor.execute(''' + INSERT INTO exif_data (file, key, value) + VALUES (?, ?, ?) + ''', (file, key, value)) + except sqlite3.IntegrityError: + pass + + return + +def migrate_exif_data(cursor): + if os.path.exists(exif_cache_file): + with open(exif_cache_file, 'r') as file: + exif_cache = json.load(file) + + for file, info in exif_cache.items(): + file = os.path.realpath(file) + update_exif_data(cursor, file, info) + + return + +def migrate_ranking(cursor): + if os.path.exists(ranking_file): + with open(ranking_file, 'r') as file: + ranking = json.load(file) + for file, info in ranking.items(): + if info != "None": + file = os.path.realpath(file) + name = os.path.basename(file) + cursor.execute(''' + INSERT INTO ranking (file, name, ranking) + VALUES (?, ?, ?) + ''', (file, name, info)) + + return + +def get_hash(file): + # Get filehash without exif info + try: + image = Image.open(file) + except Exception as e: + print(e) + + hash = hashlib.sha512(image.tobytes()).hexdigest() + image.close() + + return hash + +def migrate_filehash(cursor, version): + if version <= "4": + create_filehash(cursor) + + cursor.execute(''' + SELECT file + FROM ranking + ''') + for (file,) in cursor.fetchall(): + if os.path.exists(file): + hash = get_hash(file) + cursor.execute(''' + INSERT INTO filehash (file, hash) + VALUES (?, ?) + ''', (file, hash)) + + return + +def migrate_work_files(cursor): + create_work_files(cursor) + + return + +def update_db_data(cursor, key, value): + cursor.execute(''' + INSERT OR REPLACE + INTO db_data (key, value) + VALUES (?, ?) + ''', (key, value)) + + return + +def get_version(): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + SELECT value + FROM db_data + WHERE key = 'version' + ''',) + db_version = cursor.fetchone() + + return db_version + +def migrate_path_recorder_dirs(cursor): + cursor.execute(''' + SELECT path, path_display + FROM path_recorder + ''') + for (path, path_display) in cursor.fetchall(): + real_path = os.path.realpath(path) + if path != real_path: + update_from = path + update_to = real_path + try: + cursor.execute(''' + UPDATE path_recorder + SET path = ?, + path_display = ? || SUBSTR(path_display, LENGTH(?) + 1) + WHERE path = ? + ''', (update_to, update_to, update_from, update_from)) + except sqlite3.IntegrityError as e: + # these are double keys, because the same file can be in the db with different path notations + (e_msg,) = e.args + if e_msg.startswith("UNIQUE constraint"): + cursor.execute(''' + DELETE FROM path_recorder + WHERE path = ? + ''', (update_from,)) + else: + raise + + return + +def migrate_exif_data_dirs(cursor): + cursor.execute(''' + SELECT file + FROM exif_data + ''') + for (filepath,) in cursor.fetchall(): + (path, file) = os.path.split(filepath) + real_path = os.path.realpath(path) + if path != real_path: + update_from = filepath + update_to = os.path.join(real_path, file) + try: + cursor.execute(''' + UPDATE exif_data + SET file = ? + WHERE file = ? + ''', (update_to, update_from)) + except sqlite3.IntegrityError as e: + # these are double keys, because the same file can be in the db with different path notations + (e_msg,) = e.args + if e_msg.startswith("UNIQUE constraint"): + cursor.execute(''' + DELETE FROM exif_data + WHERE file = ? + ''', (update_from,)) + else: + raise + + return + +def migrate_ranking_dirs(cursor, db_version): + if db_version == "1": + cursor.execute(''' + ALTER TABLE ranking + ADD COLUMN name TEXT + ''') + + cursor.execute(''' + CREATE INDEX IF NOT EXISTS ranking_name ON ranking (name) + ''') + + cursor.execute(''' + SELECT file, ranking + FROM ranking + ''') + for (filepath, ranking) in cursor.fetchall(): + if filepath == "" or ranking == "None": + cursor.execute(''' + DELETE FROM ranking + WHERE file = ? + ''', (filepath,)) + else: + (path, file) = os.path.split(filepath) + real_path = os.path.realpath(path) + name = file + update_from = filepath + update_to = os.path.join(real_path, file) + try: + cursor.execute(''' + UPDATE ranking + SET file = ?, + name = ? + WHERE file = ? + ''', (update_to, name, update_from)) + except sqlite3.IntegrityError as e: + # these are double keys, because the same file can be in the db with different path notations + (e_msg,) = e.args + if e_msg.startswith("UNIQUE constraint"): + cursor.execute(''' + DELETE FROM ranking + WHERE file = ? + ''', (update_from,)) + else: + raise + + return + +def check(): + if not os.path.exists(db_file): + conn, cursor = transaction_begin() + print("Image Browser: Creating database") + create_db(cursor) + update_db_data(cursor, "version", version) + migrate_path_recorder(cursor) + migrate_exif_data(cursor) + migrate_ranking(cursor) + migrate_filehash(cursor, str(version)) + transaction_end(conn, cursor) + print("Image Browser: Database created") + db_version = get_version() + conn, cursor = transaction_begin() + if db_version[0] <= "2": + # version 1 database had mixed path notations, changed them all to abspath + # version 2 database still had mixed path notations, because of windows short name, changed them all to realpath + print(f"Image Browser: Upgrading database from version {db_version[0]} to version {version}") + migrate_path_recorder_dirs(cursor) + migrate_exif_data_dirs(cursor) + migrate_ranking_dirs(cursor, db_version[0]) + if db_version[0] <= "4": + migrate_filehash(cursor, db_version[0]) + if db_version[0] <= "5": + migrate_work_files(cursor) + update_db_data(cursor, "version", version) + print(f"Image Browser: Database upgraded from version {db_version[0]} to version {version}") + transaction_end(conn, cursor) + + return version + +def load_path_recorder(): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + SELECT path, depth, path_display + FROM path_recorder + ''') + path_recorder = {path: {"depth": depth, "path_display": path_display} for path, depth, path_display in cursor.fetchall()} + + return path_recorder + +def select_ranking(file): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + SELECT ranking + FROM ranking + WHERE file = ? + ''', (file,)) + ranking_value = cursor.fetchone() + + if ranking_value is None: + return_ranking = "None" + else: + (return_ranking,) = ranking_value + + return return_ranking + +def update_ranking(file, ranking): + name = os.path.basename(file) + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + if ranking == "None": + cursor.execute(''' + DELETE FROM ranking + WHERE file = ? + ''', (file,)) + else: + cursor.execute(''' + INSERT OR REPLACE + INTO ranking (file, name, ranking) + VALUES (?, ?, ?) + ''', (file, name, ranking)) + + hash = get_hash(file) + cursor.execute(''' + INSERT OR REPLACE + INTO filehash (file, hash) + VALUES (?, ?) + ''', (file, hash)) + + return + +def select_image_reward_score(cursor, file): + cursor.execute(''' + SELECT value + FROM exif_data + WHERE file = ? + AND key = 'ImageRewardScore' + ''', (file,)) + image_reward_score = cursor.fetchone() + if image_reward_score is None: + return_image_reward_score = None + else: + (return_image_reward_score,) = image_reward_score + cursor.execute(''' + SELECT value + FROM exif_data + WHERE file = ? + AND key = 'prompt' + ''', (file,)) + image_reward_prompt = cursor.fetchone() + if image_reward_prompt is None: + return_image_reward_prompt = None + else: + (return_image_reward_prompt,) = image_reward_prompt + + return return_image_reward_score, return_image_reward_prompt + +def update_image_reward_score(cursor, file, image_reward_score): + cursor.execute(''' + INSERT OR REPLACE + INTO exif_data (file, key, value) + VALUES (?, ?, ?) + ''', (file, "ImageRewardScore", image_reward_score)) + + return + +def update_path_recorder(path, depth, path_display): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + INSERT OR REPLACE + INTO path_recorder (path, depth, path_display) + VALUES (?, ?, ?) + ''', (path, depth, path_display)) + + return + +def update_path_recorder(path, depth, path_display): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + INSERT OR REPLACE + INTO path_recorder (path, depth, path_display) + VALUES (?, ?, ?) + ''', (path, depth, path_display)) + + return + +def delete_path_recorder(path): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + DELETE FROM path_recorder + WHERE path = ? + ''', (path,)) + + return + +def update_path_recorder_mult(cursor, update_from, update_to): + cursor.execute(''' + UPDATE path_recorder + SET path = ?, + path_display = ? || SUBSTR(path_display, LENGTH(?) + 1) + WHERE path = ? + ''', (update_to, update_to, update_from, update_from)) + + return + +def update_exif_data_mult(cursor, update_from, update_to): + update_from = update_from + os.path.sep + update_to = update_to + os.path.sep + cursor.execute(''' + UPDATE exif_data + SET file = ? || SUBSTR(file, LENGTH(?) + 1) + WHERE file like ? || '%' + ''', (update_to, update_from, update_from)) + + return + +def update_ranking_mult(cursor, update_from, update_to): + update_from = update_from + os.path.sep + update_to = update_to + os.path.sep + cursor.execute(''' + UPDATE ranking + SET file = ? || SUBSTR(file, LENGTH(?) + 1) + WHERE file like ? || '%' + ''', (update_to, update_from, update_from)) + + return + +def delete_exif_0(cursor): + cursor.execute(''' + DELETE FROM exif_data + WHERE file IN ( + SELECT file FROM exif_data a + WHERE value = '0' + GROUP BY file + HAVING COUNT(*) = (SELECT COUNT(*) FROM exif_data WHERE file = a.file) + ) + ''') + + return + +def get_ranking_by_file(cursor, file): + cursor.execute(''' + SELECT ranking + FROM ranking + WHERE file = ? + ''', (file,)) + ranking_value = cursor.fetchone() + + return ranking_value + +def get_ranking_by_name(cursor, name): + cursor.execute(''' + SELECT file, ranking + FROM ranking + WHERE name = ? + ''', (name,)) + ranking_value = cursor.fetchone() + + if ranking_value is not None: + (file, _) = ranking_value + cursor.execute(''' + SELECT hash + FROM filehash + WHERE file = ? + ''', (file,)) + hash_value = cursor.fetchone() + else: + hash_value = None + + return ranking_value, hash_value + +def insert_ranking(cursor, file, ranking, hash): + name = os.path.basename(file) + cursor.execute(''' + INSERT INTO ranking (file, name, ranking) + VALUES (?, ?, ?) + ''', (file, name, ranking)) + + cursor.execute(''' + INSERT OR REPLACE + INTO filehash (file, hash) + VALUES (?, ?) + ''', (file, hash)) + + return + +def replace_ranking(cursor, file, alternate_file, hash): + name = os.path.basename(file) + cursor.execute(''' + UPDATE ranking + SET file = ? + WHERE file = ? + ''', (file, alternate_file)) + + cursor.execute(''' + INSERT OR REPLACE + INTO filehash (file, hash) + VALUES (?, ?) + ''', (file, hash)) + + return + +def transaction_begin(): + conn = sqlite3.connect(db_file, timeout=timeout) + conn.isolation_level = None + cursor = conn.cursor() + cursor.execute("BEGIN") + return conn, cursor + +def transaction_end(conn, cursor): + cursor.execute("COMMIT") + conn.close() + return + +def update_exif_data_by_key(cursor, file, key, value): + cursor.execute(''' + INSERT OR REPLACE + INTO exif_data (file, key, value) + VALUES (?, ?, ?) + ''', (file, key, value)) + + return + +def select_prompts(file): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + SELECT key, value + FROM exif_data + WHERE file = ? + AND KEY in ('prompt', 'negative_prompt') + ''', (file,)) + + rows = cursor.fetchall() + prompt = "" + neg_prompt = "" + for row in rows: + (key, value) = row + if key == 'prompt': + prompt = value + elif key == 'negative_prompt': + neg_prompt = value + + return prompt, neg_prompt + +def load_exif_data(exif_cache): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + SELECT file, group_concat( + case when key = 'prompt' or key = 'negative_prompt' then key || ': ' || value || '\n' + else key || ': ' || value + end, ', ') AS string + FROM ( + SELECT * + FROM exif_data + ORDER BY + CASE WHEN key = 'prompt' THEN 0 + WHEN key = 'negative_prompt' THEN 1 + ELSE 2 END, + key + ) + GROUP BY file + ''') + + rows = cursor.fetchall() + for row in rows: + exif_cache[row[0]] = row[1] + + return exif_cache + +def load_exif_data_by_key(cache, key1, key2): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + SELECT file, value + FROM exif_data + WHERE key IN (?, ?) + ''', (key1, key2)) + + rows = cursor.fetchall() + for row in rows: + cache[row[0]] = row[1] + + return cache + +def get_exif_dirs(): + with sqlite3.connect(db_file, timeout=timeout) as conn: + cursor = conn.cursor() + cursor.execute(''' + SELECT file + FROM exif_data + ''') + + rows = cursor.fetchall() + + dirs = {} + for row in rows: + dir = os.path.dirname(row[0]) + dirs[dir] = dir + + return dirs + +def fill_work_files(cursor, fileinfos): + filenames = [x[0] for x in fileinfos] + + cursor.execute(''' + DELETE + FROM work_files + ''') + + sql = ''' + INSERT INTO work_files (file) + VALUES (?) + ''' + + cursor.executemany(sql, [(x,) for x in filenames]) + + return + +def filter_aes(cursor, fileinfos, aes_filter_min_num, aes_filter_max_num, score_type): + if score_type == "aesthetic_score": + key = "aesthetic_score" + else: + key = "ImageRewardScore" + + cursor.execute(''' + DELETE + FROM work_files + WHERE file not in ( + SELECT file + FROM exif_data b + WHERE file = b.file + AND b.key = ? + AND CAST(b.value AS REAL) between ? and ? + ) + ''', (key, aes_filter_min_num, aes_filter_max_num)) + + cursor.execute(''' + SELECT file + FROM work_files + ''') + + rows = cursor.fetchall() + + fileinfos_dict = {pair[0]: pair[1] for pair in fileinfos} + fileinfos_new = [] + for (file,) in rows: + if fileinfos_dict.get(file) is not None: + fileinfos_new.append((file, fileinfos_dict[file])) + + return fileinfos_new + +def filter_ranking(cursor, fileinfos, ranking_filter, ranking_filter_min_num, ranking_filter_max_num): + if ranking_filter == "None": + cursor.execute(''' + DELETE + FROM work_files + WHERE file IN ( + SELECT file + FROM ranking b + WHERE file = b.file + ) + ''') + elif ranking_filter == "Min-max": + cursor.execute(''' + DELETE + FROM work_files + WHERE file NOT IN ( + SELECT file + FROM ranking b + WHERE file = b.file + AND b.ranking BETWEEN ? AND ? + ) + ''', (ranking_filter_min_num, ranking_filter_max_num)) + else: + cursor.execute(''' + DELETE + FROM work_files + WHERE file NOT IN ( + SELECT file + FROM ranking b + WHERE file = b.file + AND b.ranking = ? + ) + ''', (ranking_filter,)) + + cursor.execute(''' + SELECT file + FROM work_files + ''') + + rows = cursor.fetchall() + + fileinfos_dict = {pair[0]: pair[1] for pair in fileinfos} + fileinfos_new = [] + for (file,) in rows: + if fileinfos_dict.get(file) is not None: + fileinfos_new.append((file, fileinfos_dict[file])) + + return fileinfos_new + +def select_x_y(cursor, file): + cursor.execute(''' + SELECT value + FROM exif_data + WHERE file = ? + AND key = 'Size' + ''', (file,)) + size_value = cursor.fetchone() + + if size_value is None: + x = "?" + y = "?" + else: + (size,) = size_value + parts = size.split("x") + x = parts[0] + y = parts[1] + + return x, y \ No newline at end of file diff --git a/stable-diffusion-webui-images-browser/style.css b/stable-diffusion-webui-images-browser/style.css new file mode 100644 index 0000000000000000000000000000000000000000..0037c04934953ebf17bca17563d5c9f22aa3ec72 --- /dev/null +++ b/stable-diffusion-webui-images-browser/style.css @@ -0,0 +1,23 @@ +.thumbnails.svelte-1tkea93.svelte-1tkea93 { + justify-content: initial; +} + +.thumbnails.scroll-hide.svelte-g4rw9 { + justify-content: initial; +} + +div[id^="image_browser_tab"][id$="image_browser_gallery"].hide_loading > .svelte-gjihhp { + display: none; +} + +.image_browser_gallery img { + object-fit: scale-down !important; +} + +/* Workaround until gradio version is updated to a version that fixes it + see https://github.com/gradio-app/gradio/issues/1590 +*/ +#tab_image_browser .thumbnail-item > img { + width: auto !important; + height: auto !important; +} diff --git a/stable-diffusion-webui-images-browser/wib.sqlite3 b/stable-diffusion-webui-images-browser/wib.sqlite3 new file mode 100644 index 0000000000000000000000000000000000000000..10005980791697bba97be30e09f7d3602e565175 Binary files /dev/null and b/stable-diffusion-webui-images-browser/wib.sqlite3 differ diff --git a/ultimate-upscale-for-automatic1111/.gitignore b/ultimate-upscale-for-automatic1111/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..600d2d33badf45cc068e01d2e3c837e11c417bc4 --- /dev/null +++ b/ultimate-upscale-for-automatic1111/.gitignore @@ -0,0 +1 @@ +.vscode \ No newline at end of file diff --git a/ultimate-upscale-for-automatic1111/LICENSE b/ultimate-upscale-for-automatic1111/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ebfe3f5212b6396c75ee993947fe1ebdd6a91207 --- /dev/null +++ b/ultimate-upscale-for-automatic1111/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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. + + ultimate-upscale-for-automatic1111 + Copyright (C) 2023 Mirzam + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) 2023 Mirzam + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/ultimate-upscale-for-automatic1111/README.md b/ultimate-upscale-for-automatic1111/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d158139e43aa9f19a85b013299fd8fd6b03d405f --- /dev/null +++ b/ultimate-upscale-for-automatic1111/README.md @@ -0,0 +1,43 @@ +# Ultimate SD Upscale extension for [AUTOMATIC1111 Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) +Now you have the opportunity to use a large denoise (0.3-0.5) and not spawn many artifacts. Works on any video card, since you can use a 512x512 tile size and the image will converge. + +News channel: https://t.me/usdunews + +# Instructions +All instructions can be found on the project's [wiki](https://github.com/Coyote-A/ultimate-upscale-for-automatic1111/wiki). + +# Examples +More on [wiki page](https://github.com/Coyote-A/ultimate-upscale-for-automatic1111/wiki/Examples) + +
+ E1 + Original image + + ![Original](https://i.imgur.com/J8mRYOD.png) + + 2k upscaled. **Tile size**: 512, **Padding**: 32, **Mask blur**: 16, **Denoise**: 0.4 + ![2k upscale](https://i.imgur.com/0aKua4r.png) +
+ +
+ E2 + Original image + + ![Original](https://i.imgur.com/aALNI2w.png) + + 2k upscaled. **Tile size**: 768, **Padding**: 55, **Mask blur**: 20, **Denoise**: 0.35 + ![2k upscale](https://i.imgur.com/B5PHz0J.png) + + 4k upscaled. **Tile size**: 768, **Padding**: 55, **Mask blur**: 20, **Denoise**: 0.35 + ![4k upscale](https://i.imgur.com/tIUQ7TJ.jpg) +
+ +
+ E3 + Original image + + ![Original](https://i.imgur.com/AGtszA8.png) + + 4k upscaled. **Tile size**: 768, **Padding**: 55, **Mask blur**: 20, **Denoise**: 0.4 + ![4k upscale](https://i.imgur.com/LCYLfCs.jpg) +
diff --git a/ultimate-upscale-for-automatic1111/scripts/__pycache__/ultimate-upscale.cpython-310.pyc b/ultimate-upscale-for-automatic1111/scripts/__pycache__/ultimate-upscale.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9100b0c3ca2b88e1ddd0fa5370e88ec686e07570 Binary files /dev/null and b/ultimate-upscale-for-automatic1111/scripts/__pycache__/ultimate-upscale.cpython-310.pyc differ diff --git a/ultimate-upscale-for-automatic1111/scripts/ultimate-upscale.py b/ultimate-upscale-for-automatic1111/scripts/ultimate-upscale.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb7ae02b4629b9b171e3ff027851910e5f0ea43 --- /dev/null +++ b/ultimate-upscale-for-automatic1111/scripts/ultimate-upscale.py @@ -0,0 +1,557 @@ +import math +import gradio as gr +from PIL import Image, ImageDraw, ImageOps +from modules import processing, shared, images, devices, scripts +from modules.processing import StableDiffusionProcessing +from modules.processing import Processed +from modules.shared import opts, state +from enum import Enum + +class USDUMode(Enum): + LINEAR = 0 + CHESS = 1 + NONE = 2 + +class USDUSFMode(Enum): + NONE = 0 + BAND_PASS = 1 + HALF_TILE = 2 + HALF_TILE_PLUS_INTERSECTIONS = 3 + +class USDUpscaler(): + + def __init__(self, p, image, upscaler_index:int, save_redraw, save_seams_fix, tile_width, tile_height) -> None: + self.p:StableDiffusionProcessing = p + self.image:Image = image + self.scale_factor = math.ceil(max(p.width, p.height) / max(image.width, image.height)) + self.upscaler = shared.sd_upscalers[upscaler_index] + self.redraw = USDURedraw() + self.redraw.save = save_redraw + self.redraw.tile_width = tile_width if tile_width > 0 else tile_height + self.redraw.tile_height = tile_height if tile_height > 0 else tile_width + self.seams_fix = USDUSeamsFix() + self.seams_fix.save = save_seams_fix + self.seams_fix.tile_width = tile_width if tile_width > 0 else tile_height + self.seams_fix.tile_height = tile_height if tile_height > 0 else tile_width + self.initial_info = None + self.rows = math.ceil(self.p.height / self.redraw.tile_height) + self.cols = math.ceil(self.p.width / self.redraw.tile_width) + + def get_factor(self, num): + # Its just return, don't need elif + if num == 1: + return 2 + if num % 4 == 0: + return 4 + if num % 3 == 0: + return 3 + if num % 2 == 0: + return 2 + return 0 + + def get_factors(self): + scales = [] + current_scale = 1 + current_scale_factor = self.get_factor(self.scale_factor) + while current_scale_factor == 0: + self.scale_factor += 1 + current_scale_factor = self.get_factor(self.scale_factor) + while current_scale < self.scale_factor: + current_scale_factor = self.get_factor(self.scale_factor // current_scale) + scales.append(current_scale_factor) + current_scale = current_scale * current_scale_factor + if current_scale_factor == 0: + break + self.scales = enumerate(scales) + + def upscale(self): + # Log info + print(f"Canva size: {self.p.width}x{self.p.height}") + print(f"Image size: {self.image.width}x{self.image.height}") + print(f"Scale factor: {self.scale_factor}") + # Check upscaler is not empty + if self.upscaler.name == "None": + self.image = self.image.resize((self.p.width, self.p.height), resample=Image.LANCZOS) + return + # Get list with scale factors + self.get_factors() + # Upscaling image over all factors + for index, value in self.scales: + print(f"Upscaling iteration {index+1} with scale factor {value}") + self.image = self.upscaler.scaler.upscale(self.image, value, self.upscaler.data_path) + # Resize image to set values + self.image = self.image.resize((self.p.width, self.p.height), resample=Image.LANCZOS) + + def setup_redraw(self, redraw_mode, padding, mask_blur): + self.redraw.mode = USDUMode(redraw_mode) + self.redraw.enabled = self.redraw.mode != USDUMode.NONE + self.redraw.padding = padding + self.p.mask_blur = mask_blur + + def setup_seams_fix(self, padding, denoise, mask_blur, width, mode): + self.seams_fix.padding = padding + self.seams_fix.denoise = denoise + self.seams_fix.mask_blur = mask_blur + self.seams_fix.width = width + self.seams_fix.mode = USDUSFMode(mode) + self.seams_fix.enabled = self.seams_fix.mode != USDUSFMode.NONE + + def save_image(self): + if type(self.p.prompt) != list: + images.save_image(self.image, self.p.outpath_samples, "", self.p.seed, self.p.prompt, opts.samples_format, info=self.initial_info, p=self.p) + else: + images.save_image(self.image, self.p.outpath_samples, "", self.p.seed, self.p.prompt[0], opts.samples_format, info=self.initial_info, p=self.p) + + def calc_jobs_count(self): + redraw_job_count = (self.rows * self.cols) if self.redraw.enabled else 0 + seams_job_count = 0 + if self.seams_fix.mode == USDUSFMode.BAND_PASS: + seams_job_count = self.rows + self.cols - 2 + elif self.seams_fix.mode == USDUSFMode.HALF_TILE: + seams_job_count = self.rows * (self.cols - 1) + (self.rows - 1) * self.cols + elif self.seams_fix.mode == USDUSFMode.HALF_TILE_PLUS_INTERSECTIONS: + seams_job_count = self.rows * (self.cols - 1) + (self.rows - 1) * self.cols + (self.rows - 1) * (self.cols - 1) + + state.job_count = redraw_job_count + seams_job_count + + def print_info(self): + print(f"Tile size: {self.redraw.tile_width}x{self.redraw.tile_height}") + print(f"Tiles amount: {self.rows * self.cols}") + print(f"Grid: {self.rows}x{self.cols}") + print(f"Redraw enabled: {self.redraw.enabled}") + print(f"Seams fix mode: {self.seams_fix.mode.name}") + + def add_extra_info(self): + self.p.extra_generation_params["Ultimate SD upscale upscaler"] = self.upscaler.name + self.p.extra_generation_params["Ultimate SD upscale tile_width"] = self.redraw.tile_width + self.p.extra_generation_params["Ultimate SD upscale tile_height"] = self.redraw.tile_height + self.p.extra_generation_params["Ultimate SD upscale mask_blur"] = self.p.mask_blur + self.p.extra_generation_params["Ultimate SD upscale padding"] = self.redraw.padding + + def process(self): + state.begin() + self.calc_jobs_count() + self.result_images = [] + if self.redraw.enabled: + self.image = self.redraw.start(self.p, self.image, self.rows, self.cols) + self.initial_info = self.redraw.initial_info + self.result_images.append(self.image) + if self.redraw.save: + self.save_image() + + if self.seams_fix.enabled: + self.image = self.seams_fix.start(self.p, self.image, self.rows, self.cols) + self.initial_info = self.seams_fix.initial_info + self.result_images.append(self.image) + if self.seams_fix.save: + self.save_image() + state.end() + +class USDURedraw(): + + def init_draw(self, p, width, height): + p.inpaint_full_res = True + p.inpaint_full_res_padding = self.padding + p.width = math.ceil((self.tile_width+self.padding) / 64) * 64 + p.height = math.ceil((self.tile_height+self.padding) / 64) * 64 + mask = Image.new("L", (width, height), "black") + draw = ImageDraw.Draw(mask) + return mask, draw + + def calc_rectangle(self, xi, yi): + x1 = xi * self.tile_width + y1 = yi * self.tile_height + x2 = xi * self.tile_width + self.tile_width + y2 = yi * self.tile_height + self.tile_height + + return x1, y1, x2, y2 + + def linear_process(self, p, image, rows, cols): + mask, draw = self.init_draw(p, image.width, image.height) + for yi in range(rows): + for xi in range(cols): + if state.interrupted: + break + draw.rectangle(self.calc_rectangle(xi, yi), fill="white") + p.init_images = [image] + p.image_mask = mask + processed = processing.process_images(p) + draw.rectangle(self.calc_rectangle(xi, yi), fill="black") + if (len(processed.images) > 0): + image = processed.images[0] + + p.width = image.width + p.height = image.height + self.initial_info = processed.infotext(p, 0) + + return image + + def chess_process(self, p, image, rows, cols): + mask, draw = self.init_draw(p, image.width, image.height) + tiles = [] + # calc tiles colors + for yi in range(rows): + for xi in range(cols): + if state.interrupted: + break + if xi == 0: + tiles.append([]) + color = xi % 2 == 0 + if yi > 0 and yi % 2 != 0: + color = not color + tiles[yi].append(color) + + for yi in range(len(tiles)): + for xi in range(len(tiles[yi])): + if state.interrupted: + break + if not tiles[yi][xi]: + tiles[yi][xi] = not tiles[yi][xi] + continue + tiles[yi][xi] = not tiles[yi][xi] + draw.rectangle(self.calc_rectangle(xi, yi), fill="white") + p.init_images = [image] + p.image_mask = mask + processed = processing.process_images(p) + draw.rectangle(self.calc_rectangle(xi, yi), fill="black") + if (len(processed.images) > 0): + image = processed.images[0] + + for yi in range(len(tiles)): + for xi in range(len(tiles[yi])): + if state.interrupted: + break + if not tiles[yi][xi]: + continue + draw.rectangle(self.calc_rectangle(xi, yi), fill="white") + p.init_images = [image] + p.image_mask = mask + processed = processing.process_images(p) + draw.rectangle(self.calc_rectangle(xi, yi), fill="black") + if (len(processed.images) > 0): + image = processed.images[0] + + p.width = image.width + p.height = image.height + self.initial_info = processed.infotext(p, 0) + + return image + + def start(self, p, image, rows, cols): + self.initial_info = None + if self.mode == USDUMode.LINEAR: + return self.linear_process(p, image, rows, cols) + if self.mode == USDUMode.CHESS: + return self.chess_process(p, image, rows, cols) + +class USDUSeamsFix(): + + def init_draw(self, p): + self.initial_info = None + p.width = math.ceil((self.tile_width+self.padding) / 64) * 64 + p.height = math.ceil((self.tile_height+self.padding) / 64) * 64 + + def half_tile_process(self, p, image, rows, cols): + + self.init_draw(p) + processed = None + + gradient = Image.linear_gradient("L") + row_gradient = Image.new("L", (self.tile_width, self.tile_height), "black") + row_gradient.paste(gradient.resize( + (self.tile_width, self.tile_height//2), resample=Image.BICUBIC), (0, 0)) + row_gradient.paste(gradient.rotate(180).resize( + (self.tile_width, self.tile_height//2), resample=Image.BICUBIC), + (0, self.tile_height//2)) + col_gradient = Image.new("L", (self.tile_width, self.tile_height), "black") + col_gradient.paste(gradient.rotate(90).resize( + (self.tile_width//2, self.tile_height), resample=Image.BICUBIC), (0, 0)) + col_gradient.paste(gradient.rotate(270).resize( + (self.tile_width//2, self.tile_height), resample=Image.BICUBIC), (self.tile_width//2, 0)) + + p.denoising_strength = self.denoise + p.mask_blur = self.mask_blur + + for yi in range(rows-1): + for xi in range(cols): + if state.interrupted: + break + p.width = self.tile_width + p.height = self.tile_height + p.inpaint_full_res = True + p.inpaint_full_res_padding = self.padding + mask = Image.new("L", (image.width, image.height), "black") + mask.paste(row_gradient, (xi*self.tile_width, yi*self.tile_height + self.tile_height//2)) + + p.init_images = [image] + p.image_mask = mask + processed = processing.process_images(p) + if (len(processed.images) > 0): + image = processed.images[0] + + for yi in range(rows): + for xi in range(cols-1): + if state.interrupted: + break + p.width = self.tile_width + p.height = self.tile_height + p.inpaint_full_res = True + p.inpaint_full_res_padding = self.padding + mask = Image.new("L", (image.width, image.height), "black") + mask.paste(col_gradient, (xi*self.tile_width+self.tile_width//2, yi*self.tile_height)) + + p.init_images = [image] + p.image_mask = mask + processed = processing.process_images(p) + if (len(processed.images) > 0): + image = processed.images[0] + + p.width = image.width + p.height = image.height + if processed is not None: + self.initial_info = processed.infotext(p, 0) + + return image + + def half_tile_process_corners(self, p, image, rows, cols): + fixed_image = self.half_tile_process(p, image, rows, cols) + processed = None + self.init_draw(p) + gradient = Image.radial_gradient("L").resize( + (self.tile_width, self.tile_height), resample=Image.BICUBIC) + gradient = ImageOps.invert(gradient) + p.denoising_strength = self.denoise + #p.mask_blur = 0 + p.mask_blur = self.mask_blur + + for yi in range(rows-1): + for xi in range(cols-1): + if state.interrupted: + break + p.width = self.tile_width + p.height = self.tile_height + p.inpaint_full_res = True + p.inpaint_full_res_padding = 0 + mask = Image.new("L", (fixed_image.width, fixed_image.height), "black") + mask.paste(gradient, (xi*self.tile_width + self.tile_width//2, + yi*self.tile_height + self.tile_height//2)) + + p.init_images = [fixed_image] + p.image_mask = mask + processed = processing.process_images(p) + if (len(processed.images) > 0): + fixed_image = processed.images[0] + + p.width = fixed_image.width + p.height = fixed_image.height + if processed is not None: + self.initial_info = processed.infotext(p, 0) + + return fixed_image + + def band_pass_process(self, p, image, cols, rows): + + self.init_draw(p) + processed = None + + p.denoising_strength = self.denoise + p.mask_blur = 0 + + gradient = Image.linear_gradient("L") + mirror_gradient = Image.new("L", (256, 256), "black") + mirror_gradient.paste(gradient.resize((256, 128), resample=Image.BICUBIC), (0, 0)) + mirror_gradient.paste(gradient.rotate(180).resize((256, 128), resample=Image.BICUBIC), (0, 128)) + + row_gradient = mirror_gradient.resize((image.width, self.width), resample=Image.BICUBIC) + col_gradient = mirror_gradient.rotate(90).resize((self.width, image.height), resample=Image.BICUBIC) + + for xi in range(1, rows): + if state.interrupted: + break + p.width = self.width + self.padding * 2 + p.height = image.height + p.inpaint_full_res = True + p.inpaint_full_res_padding = self.padding + mask = Image.new("L", (image.width, image.height), "black") + mask.paste(col_gradient, (xi * self.tile_width - self.width // 2, 0)) + + p.init_images = [image] + p.image_mask = mask + processed = processing.process_images(p) + if (len(processed.images) > 0): + image = processed.images[0] + for yi in range(1, cols): + if state.interrupted: + break + p.width = image.width + p.height = self.width + self.padding * 2 + p.inpaint_full_res = True + p.inpaint_full_res_padding = self.padding + mask = Image.new("L", (image.width, image.height), "black") + mask.paste(row_gradient, (0, yi * self.tile_height - self.width // 2)) + + p.init_images = [image] + p.image_mask = mask + processed = processing.process_images(p) + if (len(processed.images) > 0): + image = processed.images[0] + + p.width = image.width + p.height = image.height + if processed is not None: + self.initial_info = processed.infotext(p, 0) + + return image + + def start(self, p, image, rows, cols): + if USDUSFMode(self.mode) == USDUSFMode.BAND_PASS: + return self.band_pass_process(p, image, rows, cols) + elif USDUSFMode(self.mode) == USDUSFMode.HALF_TILE: + return self.half_tile_process(p, image, rows, cols) + elif USDUSFMode(self.mode) == USDUSFMode.HALF_TILE_PLUS_INTERSECTIONS: + return self.half_tile_process_corners(p, image, rows, cols) + else: + return image + +class Script(scripts.Script): + def title(self): + return "Ultimate SD upscale" + + def show(self, is_img2img): + return is_img2img + + def ui(self, is_img2img): + + target_size_types = [ + "From img2img2 settings", + "Custom size", + "Scale from image size" + ] + + seams_fix_types = [ + "None", + "Band pass", + "Half tile offset pass", + "Half tile offset pass + intersections" + ] + + redrow_modes = [ + "Linear", + "Chess", + "None" + ] + + info = gr.HTML( + "

Will upscale the image depending on the selected target size type

") + + with gr.Row(): + target_size_type = gr.Dropdown(label="Target size type", choices=[k for k in target_size_types], type="index", + value=next(iter(target_size_types))) + + custom_width = gr.Slider(label='Custom width', minimum=64, maximum=8192, step=64, value=2048, visible=False, interactive=True) + custom_height = gr.Slider(label='Custom height', minimum=64, maximum=8192, step=64, value=2048, visible=False, interactive=True) + custom_scale = gr.Slider(label='Scale', minimum=1, maximum=16, step=0.01, value=2, visible=False, interactive=True) + + gr.HTML("

Redraw options:

") + with gr.Row(): + upscaler_index = gr.Radio(label='Upscaler', choices=[x.name for x in shared.sd_upscalers], + value=shared.sd_upscalers[0].name, type="index") + with gr.Row(): + redraw_mode = gr.Dropdown(label="Type", choices=[k for k in redrow_modes], type="index", value=next(iter(redrow_modes))) + tile_width = gr.Slider(minimum=0, maximum=2048, step=64, label='Tile width', value=512) + tile_height = gr.Slider(minimum=0, maximum=2048, step=64, label='Tile height', value=0) + mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=8) + padding = gr.Slider(label='Padding', minimum=0, maximum=128, step=1, value=32) + gr.HTML("

Seams fix:

") + with gr.Row(): + seams_fix_type = gr.Dropdown(label="Type", choices=[k for k in seams_fix_types], type="index", value=next(iter(seams_fix_types))) + seams_fix_denoise = gr.Slider(label='Denoise', minimum=0, maximum=1, step=0.01, value=0.35, visible=False, interactive=True) + seams_fix_width = gr.Slider(label='Width', minimum=0, maximum=128, step=1, value=64, visible=False, interactive=True) + seams_fix_mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=4, visible=False, interactive=True) + seams_fix_padding = gr.Slider(label='Padding', minimum=0, maximum=128, step=1, value=16, visible=False, interactive=True) + gr.HTML("

Save options:

") + with gr.Row(): + save_upscaled_image = gr.Checkbox(label="Upscaled", value=True) + save_seams_fix_image = gr.Checkbox(label="Seams fix", value=False) + + def select_fix_type(fix_index): + all_visible = fix_index != 0 + mask_blur_visible = fix_index == 2 or fix_index == 3 + width_visible = fix_index == 1 + + return [gr.update(visible=all_visible), + gr.update(visible=width_visible), + gr.update(visible=mask_blur_visible), + gr.update(visible=all_visible)] + + seams_fix_type.change( + fn=select_fix_type, + inputs=seams_fix_type, + outputs=[seams_fix_denoise, seams_fix_width, seams_fix_mask_blur, seams_fix_padding] + ) + + def select_scale_type(scale_index): + is_custom_size = scale_index == 1 + is_custom_scale = scale_index == 2 + + return [gr.update(visible=is_custom_size), + gr.update(visible=is_custom_size), + gr.update(visible=is_custom_scale), + ] + + target_size_type.change( + fn=select_scale_type, + inputs=target_size_type, + outputs=[custom_width, custom_height, custom_scale] + ) + + return [info, tile_width, tile_height, mask_blur, padding, seams_fix_width, seams_fix_denoise, seams_fix_padding, + upscaler_index, save_upscaled_image, redraw_mode, save_seams_fix_image, seams_fix_mask_blur, + seams_fix_type, target_size_type, custom_width, custom_height, custom_scale] + + def run(self, p, _, tile_width, tile_height, mask_blur, padding, seams_fix_width, seams_fix_denoise, seams_fix_padding, + upscaler_index, save_upscaled_image, redraw_mode, save_seams_fix_image, seams_fix_mask_blur, + seams_fix_type, target_size_type, custom_width, custom_height, custom_scale): + + # Init + processing.fix_seed(p) + devices.torch_gc() + + p.do_not_save_grid = True + p.do_not_save_samples = True + p.inpaint_full_res = False + + p.inpainting_fill = 1 + p.n_iter = 1 + p.batch_size = 1 + + seed = p.seed + + # Init image + init_img = p.init_images[0] + if init_img == None: + return Processed(p, [], seed, "Empty image") + init_img = images.flatten(init_img, opts.img2img_background_color) + + #override size + if target_size_type == 1: + p.width = custom_width + p.height = custom_height + if target_size_type == 2: + p.width = math.ceil((init_img.width * custom_scale) / 64) * 64 + p.height = math.ceil((init_img.height * custom_scale) / 64) * 64 + + # Upscaling + upscaler = USDUpscaler(p, init_img, upscaler_index, save_upscaled_image, save_seams_fix_image, tile_width, tile_height) + upscaler.upscale() + + # Drawing + upscaler.setup_redraw(redraw_mode, padding, mask_blur) + upscaler.setup_seams_fix(seams_fix_padding, seams_fix_denoise, seams_fix_mask_blur, seams_fix_width, seams_fix_type) + upscaler.print_info() + upscaler.add_extra_info() + upscaler.process() + result_images = upscaler.result_images + + return Processed(p, result_images, seed, upscaler.initial_info if upscaler.initial_info is not None else "") +